Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8276c57010 | |||
| 8bc115acf3 | |||
| 8706be3084 | |||
| 247cddd38a | |||
| 47afd9848b | |||
| 18753b214d | |||
| f429d54e1b | |||
| f98a77e5a5 | |||
| 3fea080626 | |||
| 0e792d28e0 | |||
| 5128762d91 |
2
.idea/deploymentTargetSelector.xml
generated
2
.idea/deploymentTargetSelector.xml
generated
@@ -4,7 +4,7 @@
|
||||
<selectionStates>
|
||||
<SelectionState runConfigName="app">
|
||||
<option name="selectionMode" value="DROPDOWN" />
|
||||
<DropdownSelection timestamp="2025-10-12T11:23:35.923427438Z">
|
||||
<DropdownSelection timestamp="2025-11-05T20:35:37.724952878Z">
|
||||
<Target type="DEFAULT_BOOT">
|
||||
<handle>
|
||||
<DeviceId pluginId="PhysicalDevice" identifier="serial=R3CT80VPBQZ" />
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
alias(libs.plugins.hilt)
|
||||
id("kotlin-kapt")
|
||||
}
|
||||
@@ -27,6 +28,24 @@ android {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
buildConfigField("String", "API_BASE_URL", "\"${project.findProperty("API_BASE_URL")}\"")
|
||||
|
||||
// Add backend/port buildConfig fields derived from gradle.properties (with safe defaults)
|
||||
buildConfigField("String", "BACKEND_HOST", "\"${project.findProperty("BASE_URL") ?: "10.0.2.2"}\"")
|
||||
buildConfigField("String", "API_PORT", "\"${project.findProperty("API_PORT") ?: "8002"}\"")
|
||||
buildConfigField("String", "WS_PORT", "\"${project.findProperty("WS_PORT") ?: "8003"}\"")
|
||||
|
||||
buildConfigField(
|
||||
"String",
|
||||
"EMERGENCY_API_BASE",
|
||||
"\"http://${project.findProperty("BASE_URL") ?: "10.0.2.2"}:${project.findProperty("API_PORT") ?: "8002"}/\""
|
||||
)
|
||||
buildConfigField(
|
||||
"String",
|
||||
"EMERGENCY_WS_BASE",
|
||||
"\"ws://${project.findProperty("BASE_URL") ?: "10.0.2.2"}:${project.findProperty("WS_PORT") ?: "8002"}/api/v1/\""
|
||||
)
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
@@ -47,10 +66,13 @@ android {
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
viewBinding = true
|
||||
buildConfig = true
|
||||
}
|
||||
composeOptions {
|
||||
kotlinCompilerExtensionVersion = "1.5.14"
|
||||
}
|
||||
buildToolsVersion = "33.0.1"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -64,6 +86,7 @@ dependencies {
|
||||
implementation(libs.androidx.compose.material3)
|
||||
implementation("androidx.hilt:hilt-navigation-compose:1.1.0")
|
||||
implementation(libs.hilt.android)
|
||||
implementation(libs.material)
|
||||
kapt(libs.hilt.compiler)
|
||||
implementation("androidx.room:room-runtime:2.6.1")
|
||||
kapt("androidx.room:room-compiler:2.6.1")
|
||||
@@ -71,20 +94,47 @@ dependencies {
|
||||
implementation("androidx.datastore:datastore-preferences:1.0.0")
|
||||
implementation("androidx.work:work-runtime-ktx:2.9.0")
|
||||
implementation("androidx.compose.runtime:runtime-livedata:1.5.4")
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0")
|
||||
implementation(libs.androidx.compose.ui.tooling)
|
||||
implementation("androidx.compose.material:material-icons-extended:1.5.4")
|
||||
implementation("androidx.navigation:navigation-compose:2.7.7")
|
||||
implementation("androidx.security:security-crypto:1.1.0-alpha06")
|
||||
implementation("com.google.code.gson:gson:2.10.1")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
|
||||
|
||||
// Network
|
||||
implementation("com.squareup.retrofit2:retrofit:2.9.0")
|
||||
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
|
||||
implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0")
|
||||
implementation("com.github.PhilJay:MPAndroidChart:v3.1.0")
|
||||
implementation("com.squareup.moshi:moshi:1.15.0")
|
||||
implementation("com.squareup.moshi:moshi-kotlin:1.15.0")
|
||||
implementation("com.squareup.moshi:moshi-adapters:1.15.0")
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.6.2")
|
||||
|
||||
// Retrofit зависимости
|
||||
implementation("com.squareup.retrofit2:retrofit:2.9.0")
|
||||
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
|
||||
|
||||
// Fragment dependencies
|
||||
implementation("androidx.fragment:fragment-ktx:1.6.2")
|
||||
implementation("androidx.navigation:navigation-fragment-ktx:2.7.7")
|
||||
implementation("androidx.navigation:navigation-ui-ktx:2.7.7")
|
||||
|
||||
// Emergency Module dependencies
|
||||
implementation("com.google.android.gms:play-services-location:21.0.1")
|
||||
implementation("com.google.accompanist:accompanist-permissions:0.32.0")
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
|
||||
implementation("com.google.android.gms:play-services-maps:18.2.0")
|
||||
|
||||
// Testing dependencies
|
||||
testImplementation(libs.junit)
|
||||
testImplementation("io.mockk:mockk:1.13.8")
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
androidTestImplementation(platform(libs.androidx.compose.bom))
|
||||
|
||||
1552
app/schemas/kr.smartsoltech.wellshe.data.AppDatabase/13.json
Normal file
1552
app/schemas/kr.smartsoltech.wellshe.data.AppDatabase/13.json
Normal file
File diff suppressed because it is too large
Load Diff
1754
app/schemas/kr.smartsoltech.wellshe.data.AppDatabase/14.json
Normal file
1754
app/schemas/kr.smartsoltech.wellshe.data.AppDatabase/14.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,11 @@
|
||||
package kr.smartsoltech.wellshe.emergency.debug
|
||||
|
||||
import android.content.Context
|
||||
|
||||
// Debug implementation delegates to ProperAuthTester
|
||||
object AuthTester {
|
||||
suspend fun runFullTest(context: Context): Boolean {
|
||||
return ProperAuthTester.runFullTest(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package kr.smartsoltech.wellshe.emergency.debug
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import org.json.JSONObject
|
||||
import kr.smartsoltech.wellshe.BuildConfig
|
||||
import java.nio.charset.Charset
|
||||
import java.util.concurrent.TimeUnit
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
|
||||
object ProperAuthTester {
|
||||
private const val TAG = "ProperAuthTester"
|
||||
private val client = OkHttpClient.Builder()
|
||||
.readTimeout(10, TimeUnit.SECONDS)
|
||||
.addInterceptor(
|
||||
HttpLoggingInterceptor { message -> Log.d(TAG, message) }
|
||||
.apply { level = HttpLoggingInterceptor.Level.BODY }
|
||||
)
|
||||
.build()
|
||||
|
||||
suspend fun loginAndGetToken(): String? = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val loginUrl = BuildConfig.API_BASE_URL + "auth/login"
|
||||
Log.d(TAG, "Login URL: $loginUrl")
|
||||
|
||||
val json = JSONObject()
|
||||
json.put("email", "shadow85@list.ru")
|
||||
json.put("password", "R0sebud1985")
|
||||
|
||||
val mediaType = "application/json; charset=utf-8".toMediaType()
|
||||
val body = json.toString().toRequestBody(mediaType)
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(loginUrl)
|
||||
.post(body)
|
||||
.build()
|
||||
|
||||
client.newCall(request).execute().use { resp ->
|
||||
val code = resp.code
|
||||
val text = resp.body?.string()
|
||||
Log.d(TAG, "Auth response code=$code body=$text")
|
||||
if (code == 200 && !text.isNullOrEmpty()) {
|
||||
val obj = JSONObject(text)
|
||||
// попытка извлечь access_token или accessToken
|
||||
val token = when {
|
||||
obj.has("access_token") -> obj.getString("access_token")
|
||||
obj.has("accessToken") -> obj.getString("accessToken")
|
||||
obj.has("token") -> obj.getString("token")
|
||||
else -> null
|
||||
}
|
||||
if (!token.isNullOrEmpty()) {
|
||||
Log.i(TAG, "Obtained token: ${token.take(50)}...")
|
||||
return@withContext token
|
||||
}
|
||||
}
|
||||
Log.w(TAG, "Failed to obtain token: code=$code body=$text")
|
||||
return@withContext null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error during login: ${e.message}", e)
|
||||
return@withContext null
|
||||
}
|
||||
}
|
||||
|
||||
fun decodeJwtPayload(token: String): JSONObject? {
|
||||
return try {
|
||||
val parts = token.split('.')
|
||||
if (parts.size < 2) return null
|
||||
val payload = parts[1]
|
||||
val decoded = Base64.decode(payload, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
|
||||
val json = String(decoded, Charset.forName("UTF-8"))
|
||||
JSONObject(json)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to decode JWT: ${e.message}", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun testWebSocketWithJwtToken(token: String): Boolean = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
// Build WS URL
|
||||
// BuildConfig.EMERGENCY_WS_BASE already contains ws://host:port/api/v1/
|
||||
val wsUrl = BuildConfig.EMERGENCY_WS_BASE + "emergency/ws/current_user_id?token=$token"
|
||||
Log.d(TAG, "WS URL: $wsUrl")
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(wsUrl)
|
||||
.build()
|
||||
|
||||
// Инициализируем deferred без неверных параметров
|
||||
val deferredMsg = CompletableDeferred<String?>()
|
||||
val opened = CompletableDeferred<Boolean>()
|
||||
|
||||
val listener = object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
|
||||
Log.i(TAG, "WebSocket opened: ${response.code}")
|
||||
// безопасно complete true
|
||||
if (!opened.isCompleted) opened.complete(true)
|
||||
// send ping-like message
|
||||
val ping = JSONObject().apply {
|
||||
put("type", "ping")
|
||||
put("message", "Hello from Android debug tester")
|
||||
}
|
||||
webSocket.send(ping.toString())
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
Log.i(TAG, "WS message: $text")
|
||||
if (!deferredMsg.isCompleted) deferredMsg.complete(text)
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
Log.w(TAG, "WS closing: $code / $reason")
|
||||
webSocket.close(1000, null)
|
||||
if (!deferredMsg.isCompleted) deferredMsg.complete(null)
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
|
||||
Log.e(TAG, "WS failure: ${t.message}", t)
|
||||
if (!deferredMsg.isCompleted) deferredMsg.completeExceptionally(t)
|
||||
}
|
||||
}
|
||||
|
||||
val ws = client.newWebSocket(request, listener)
|
||||
|
||||
// wait for open or timeout
|
||||
try {
|
||||
opened.await()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "WebSocket did not open: ${e.message}")
|
||||
ws.cancel()
|
||||
return@withContext false
|
||||
}
|
||||
|
||||
// wait for incoming message (short timeout)
|
||||
return@withContext try {
|
||||
val msg = kotlinx.coroutines.withTimeoutOrNull(5000) { deferredMsg.await() }
|
||||
Log.d(TAG, "Received WS reply: $msg")
|
||||
ws.close(1000, "done")
|
||||
msg != null
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error waiting for WS message: ${e.message}", e)
|
||||
ws.cancel()
|
||||
false
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error connecting to WS: ${e.message}", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun runFullTest(context: Context): Boolean = withContext(Dispatchers.IO) {
|
||||
Log.i(TAG, "Starting full proper-auth test")
|
||||
val token = loginAndGetToken()
|
||||
if (token.isNullOrEmpty()) {
|
||||
Log.e(TAG, "No token obtained — aborting test")
|
||||
return@withContext false
|
||||
}
|
||||
|
||||
// decode payload for inspection
|
||||
val payload = decodeJwtPayload(token)
|
||||
if (payload != null) {
|
||||
Log.i(TAG, "Token payload: $payload")
|
||||
} else {
|
||||
Log.w(TAG, "Could not decode token payload")
|
||||
}
|
||||
|
||||
val wsResult = testWebSocketWithJwtToken(token)
|
||||
Log.i(TAG, "WebSocket test result: $wsResult")
|
||||
wsResult
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,15 @@
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
|
||||
<!-- Разрешения для геолокации (добавлены: без них системный диалог не покажется) -->
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<!-- Background location требует отдельной обработки на Android 10+; добавить при необходимости -->
|
||||
<!-- <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> -->
|
||||
|
||||
<!-- Разрешение для совершения экстренных звонков -->
|
||||
<uses-permission android:name="android.permission.CALL_PHONE" />
|
||||
|
||||
<application
|
||||
android:name=".WellSheApplication"
|
||||
android:allowBackup="true"
|
||||
@@ -24,6 +33,7 @@
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:theme="@style/Theme.WellShe">
|
||||
|
||||
<activity
|
||||
@@ -49,6 +59,17 @@
|
||||
android:value="androidx.startup" />
|
||||
</provider>
|
||||
|
||||
<!-- BroadcastReceiver для обработки действий из уведомлений -->
|
||||
<receiver
|
||||
android:name=".emergency.utils.EmergencyActionReceiver"
|
||||
android:enabled="true"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="HELP_ACTION" />
|
||||
<action android:name="CALL_POLICE_ACTION" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
BIN
app/src/main/ic_launcher-playstore.png
Normal file
BIN
app/src/main/ic_launcher-playstore.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 80 KiB |
@@ -1,22 +1,69 @@
|
||||
package kr.smartsoltech.wellshe
|
||||
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kr.smartsoltech.wellshe.ui.navigation.WellSheNavigation
|
||||
import kr.smartsoltech.wellshe.ui.auth.AuthViewModel
|
||||
import kr.smartsoltech.wellshe.ui.navigation.AppNavGraph
|
||||
import kr.smartsoltech.wellshe.ui.navigation.BottomNavigation
|
||||
import kr.smartsoltech.wellshe.ui.navigation.BottomNavItem
|
||||
import kr.smartsoltech.wellshe.ui.theme.WellSheTheme
|
||||
|
||||
@AndroidEntryPoint
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
try {
|
||||
setContent {
|
||||
WellSheTheme {
|
||||
WellSheNavigation()
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.background
|
||||
) {
|
||||
val navController = rememberNavController()
|
||||
// Получаем AuthViewModel для управления авторизацией
|
||||
val authViewModel: AuthViewModel = viewModel()
|
||||
|
||||
// Получаем текущий маршрут для определения показа нижней навигации
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = navBackStackEntry?.destination?.route
|
||||
|
||||
// Определяем, нужно ли отображать нижнюю панель навигации
|
||||
val showBottomNav = currentRoute in BottomNavItem.items.map { it.route }
|
||||
|
||||
Scaffold(
|
||||
bottomBar = {
|
||||
if (showBottomNav) {
|
||||
BottomNavigation(navController = navController)
|
||||
}
|
||||
}
|
||||
) { paddingValues ->
|
||||
// Навигационный граф приложения с передачей authViewModel
|
||||
AppNavGraph(
|
||||
navController = navController,
|
||||
modifier = Modifier.padding(paddingValues),
|
||||
authViewModel = authViewModel
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Log.d("MainActivity", "Activity started successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e("MainActivity", "Error in onCreate: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,60 @@
|
||||
package kr.smartsoltech.wellshe
|
||||
|
||||
import android.app.Application
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import dagger.hilt.android.EntryPointAccessors
|
||||
import kr.smartsoltech.wellshe.emergency.domain.repository.EmergencyRepository
|
||||
import kr.smartsoltech.wellshe.data.preferences.ServerPreferences
|
||||
import dagger.hilt.EntryPoint
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
|
||||
@HiltAndroidApp
|
||||
class WellSheApplication : Application() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WellSheApplication"
|
||||
}
|
||||
|
||||
@EntryPoint
|
||||
@InstallIn(SingletonComponent::class)
|
||||
interface EmergencyRepositoryEntryPoint {
|
||||
fun emergencyRepository(): EmergencyRepository
|
||||
}
|
||||
|
||||
@EntryPoint
|
||||
@InstallIn(SingletonComponent::class)
|
||||
interface ServerPreferencesEntryPoint {
|
||||
fun serverPreferences(): ServerPreferences
|
||||
}
|
||||
|
||||
val emergencyRepository: EmergencyRepository by lazy {
|
||||
val hiltEntryPoint = EntryPointAccessors.fromApplication(
|
||||
this,
|
||||
EmergencyRepositoryEntryPoint::class.java
|
||||
)
|
||||
hiltEntryPoint.emergencyRepository()
|
||||
}
|
||||
|
||||
private val serverPreferences: ServerPreferences by lazy {
|
||||
val hiltEntryPoint = EntryPointAccessors.fromApplication(
|
||||
this,
|
||||
ServerPreferencesEntryPoint::class.java
|
||||
)
|
||||
hiltEntryPoint.serverPreferences()
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
// TODO: Initialize app components when repositories are ready
|
||||
Log.d(TAG, "WellShe Application starting...")
|
||||
|
||||
// Логируем текущие настройки сервера при запуске
|
||||
try {
|
||||
serverPreferences.debugSettings()
|
||||
Log.d(TAG, "Application started successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error during app startup", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import androidx.room.TypeConverter
|
||||
entities = [
|
||||
// Основные сущности
|
||||
WaterLogEntity::class,
|
||||
SleepLogEntity::class,
|
||||
WorkoutEntity::class,
|
||||
CalorieEntity::class,
|
||||
StepsEntity::class,
|
||||
@@ -41,15 +40,18 @@ import androidx.room.TypeConverter
|
||||
ExerciseParam::class,
|
||||
ExerciseFormula::class,
|
||||
ExerciseFormulaVar::class,
|
||||
CatalogVersion::class
|
||||
CatalogVersion::class,
|
||||
|
||||
// Emergency Module entities
|
||||
kr.smartsoltech.wellshe.emergency.data.entities.EmergencyEventEntity::class,
|
||||
kr.smartsoltech.wellshe.emergency.data.entities.EmergencyResponseEntity::class
|
||||
],
|
||||
version = 11,
|
||||
version = 14, // Увеличиваем версию для Emergency Module
|
||||
exportSchema = true
|
||||
)
|
||||
@TypeConverters(LocalDateConverter::class, InstantConverter::class, StringListConverter::class)
|
||||
@TypeConverters(LocalDateConverter::class, InstantConverter::class, StringListConverter::class, EmergencyTypeConverter::class)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun waterLogDao(): WaterLogDao
|
||||
abstract fun sleepLogDao(): SleepLogDao
|
||||
abstract fun workoutDao(): WorkoutDao
|
||||
abstract fun calorieDao(): CalorieDao
|
||||
abstract fun stepsDao(): StepsDao
|
||||
@@ -63,6 +65,8 @@ abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun cycleForecastDao(): CycleForecastDao
|
||||
|
||||
// Дополнительные DAO для repo
|
||||
abstract fun beverageDao(): BeverageDao
|
||||
abstract fun beverageServingDao(): BeverageServingDao
|
||||
abstract fun beverageLogDao(): BeverageLogDao
|
||||
abstract fun beverageLogNutrientDao(): BeverageLogNutrientDao
|
||||
abstract fun beverageServingNutrientDao(): BeverageServingNutrientDao
|
||||
@@ -71,8 +75,14 @@ abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun workoutSessionParamDao(): WorkoutSessionParamDao
|
||||
abstract fun workoutEventDao(): WorkoutEventDao
|
||||
abstract fun exerciseDao(): ExerciseDao
|
||||
abstract fun exerciseParamDao(): ExerciseParamDao
|
||||
abstract fun exerciseFormulaDao(): ExerciseFormulaDao
|
||||
abstract fun exerciseFormulaVarDao(): ExerciseFormulaVarDao
|
||||
abstract fun nutrientDao(): NutrientDao
|
||||
abstract fun catalogVersionDao(): CatalogVersionDao
|
||||
|
||||
// Emergency Module DAO
|
||||
abstract fun emergencyDao(): kr.smartsoltech.wellshe.emergency.data.dao.EmergencyDao
|
||||
}
|
||||
|
||||
class LocalDateConverter {
|
||||
@@ -81,3 +91,19 @@ class LocalDateConverter {
|
||||
@TypeConverter
|
||||
fun dateToTimestamp(date: LocalDate?): Long? = date?.atStartOfDay(java.time.ZoneId.systemDefault())?.toInstant()?.toEpochMilli()
|
||||
}
|
||||
|
||||
class EmergencyTypeConverter {
|
||||
@TypeConverter
|
||||
fun fromEmergencyType(type: kr.smartsoltech.wellshe.emergency.data.models.EmergencyType): String = type.name
|
||||
|
||||
@TypeConverter
|
||||
fun toEmergencyType(name: String): kr.smartsoltech.wellshe.emergency.data.models.EmergencyType =
|
||||
kr.smartsoltech.wellshe.emergency.data.models.EmergencyType.valueOf(name)
|
||||
|
||||
@TypeConverter
|
||||
fun fromEmergencyStatus(status: kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus): String = status.name
|
||||
|
||||
@TypeConverter
|
||||
fun toEmergencyStatus(name: String): kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus =
|
||||
kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus.valueOf(name)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package kr.smartsoltech.wellshe.data.api
|
||||
|
||||
import kr.smartsoltech.wellshe.data.model.ServerHealthResponse
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.GET
|
||||
|
||||
interface HealthApi {
|
||||
@GET("api/v1/health")
|
||||
suspend fun getHealth(): Response<ServerHealthResponse>
|
||||
}
|
||||
@@ -5,27 +5,6 @@ import kotlinx.coroutines.flow.Flow
|
||||
import kr.smartsoltech.wellshe.data.entity.*
|
||||
import java.time.LocalDate
|
||||
|
||||
@Dao
|
||||
interface SleepLogDao {
|
||||
@Query("SELECT * FROM sleep_logs WHERE date = :date")
|
||||
suspend fun getSleepForDate(date: LocalDate): SleepLogEntity?
|
||||
|
||||
@Query("SELECT * FROM sleep_logs ORDER BY date DESC LIMIT 7")
|
||||
fun getRecentSleepLogs(): Flow<List<SleepLogEntity>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertSleepLog(sleepLog: SleepLogEntity)
|
||||
|
||||
@Update
|
||||
suspend fun updateSleepLog(sleepLog: SleepLogEntity)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteSleepLog(sleepLog: SleepLogEntity)
|
||||
|
||||
@Query("SELECT * FROM sleep_logs WHERE date BETWEEN :startDate AND :endDate ORDER BY date DESC")
|
||||
fun getSleepLogsForPeriod(startDate: LocalDate, endDate: LocalDate): Flow<List<SleepLogEntity>>
|
||||
}
|
||||
|
||||
@Dao
|
||||
interface WorkoutDao {
|
||||
@Query("SELECT * FROM workouts WHERE date = :date ORDER BY id DESC")
|
||||
|
||||
@@ -22,6 +22,5 @@ data class CycleHistoryEntity(
|
||||
// Добавляем поля для соответствия с CyclePeriodEntity
|
||||
val flow: String = "",
|
||||
val symptoms: List<String> = emptyList(),
|
||||
val mood: String = "",
|
||||
val cycleLength: Int? = null
|
||||
)
|
||||
|
||||
@@ -11,6 +11,5 @@ data class CyclePeriodEntity(
|
||||
val endDate: LocalDate?,
|
||||
val flow: String = "",
|
||||
val symptoms: List<String> = emptyList(),
|
||||
val mood: String = "",
|
||||
val cycleLength: Int? = null
|
||||
)
|
||||
|
||||
@@ -13,18 +13,6 @@ data class WaterLogEntity(
|
||||
val timestamp: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity(tableName = "sleep_logs")
|
||||
data class SleepLogEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0,
|
||||
val date: LocalDate,
|
||||
val bedTime: String, // HH:mm
|
||||
val wakeTime: String, // HH:mm
|
||||
val duration: Float, // часы
|
||||
val quality: String = "good", // poor, fair, good, excellent
|
||||
val notes: String = ""
|
||||
)
|
||||
|
||||
@Entity(tableName = "workouts")
|
||||
data class WorkoutEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
@@ -76,5 +64,10 @@ data class UserProfileEntity(
|
||||
val cycleLength: Int = 28,
|
||||
val periodLength: Int = 5,
|
||||
val lastPeriodDate: LocalDate? = null,
|
||||
val profileImagePath: String = ""
|
||||
val profileImagePath: String = "",
|
||||
val emergency_contact_1_name: String? = null,
|
||||
val emergency_contact_1_phone: String? = null,
|
||||
val emergency_contact_2_name: String? = null,
|
||||
val emergency_contact_2_phone: String? = null,
|
||||
val emergency_notifications_enabled: Boolean? = false
|
||||
)
|
||||
|
||||
@@ -13,10 +13,7 @@ data class HealthRecordEntity(
|
||||
val bloodPressureS: Int?,
|
||||
val bloodPressureD: Int?,
|
||||
val temperature: Float?,
|
||||
val mood: String?,
|
||||
val energyLevel: Int?,
|
||||
val stressLevel: Int?,
|
||||
val symptoms: List<String>?,
|
||||
val notes: String?
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package kr.smartsoltech.wellshe.data.local
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
private val Context.authDataStore: DataStore<Preferences> by preferencesDataStore(name = "auth_preferences")
|
||||
|
||||
@Singleton
|
||||
class AuthTokenRepository @Inject constructor(
|
||||
private val context: Context
|
||||
) {
|
||||
companion object {
|
||||
private val AUTH_TOKEN = stringPreferencesKey("auth_token")
|
||||
private val USER_EMAIL = stringPreferencesKey("user_email")
|
||||
private val USER_PASSWORD = stringPreferencesKey("user_password") // Храним зашифрованный пароль
|
||||
}
|
||||
|
||||
// Получение токена авторизации
|
||||
val authToken: Flow<String?> = context.authDataStore.data
|
||||
.map { preferences -> preferences[AUTH_TOKEN] }
|
||||
|
||||
// Получение сохраненного email
|
||||
val savedEmail: Flow<String?> = context.authDataStore.data
|
||||
.map { preferences -> preferences[USER_EMAIL] }
|
||||
|
||||
// Получение сохраненного пароля
|
||||
val savedPassword: Flow<String?> = context.authDataStore.data
|
||||
.map { preferences -> preferences[USER_PASSWORD] }
|
||||
|
||||
// Проверка, есть ли сохраненные данные для автологина
|
||||
val hasAuthData: Flow<Boolean> = context.authDataStore.data
|
||||
.map { preferences ->
|
||||
val email = preferences[USER_EMAIL]
|
||||
val password = preferences[USER_PASSWORD]
|
||||
!email.isNullOrEmpty() && !password.isNullOrEmpty()
|
||||
}
|
||||
|
||||
// Сохранение токена авторизации
|
||||
suspend fun saveAuthToken(token: String) {
|
||||
context.authDataStore.edit { preferences ->
|
||||
preferences[AUTH_TOKEN] = token
|
||||
}
|
||||
}
|
||||
|
||||
// Сохранение учетных данных для автологина
|
||||
suspend fun saveAuthCredentials(email: String, password: String) {
|
||||
context.authDataStore.edit { preferences ->
|
||||
preferences[USER_EMAIL] = email
|
||||
// TODO: здесь должно быть шифрование пароля перед сохранением
|
||||
preferences[USER_PASSWORD] = password
|
||||
}
|
||||
}
|
||||
|
||||
// Очистка данных авторизации при выходе
|
||||
suspend fun clearAuthData() {
|
||||
context.authDataStore.edit { preferences ->
|
||||
preferences.remove(AUTH_TOKEN)
|
||||
preferences.remove(USER_EMAIL)
|
||||
preferences.remove(USER_PASSWORD)
|
||||
}
|
||||
}
|
||||
|
||||
// Удалить только auth token (не трогая сохранённые credentials)
|
||||
suspend fun clearAuthToken() {
|
||||
context.authDataStore.edit { preferences ->
|
||||
preferences.remove(AUTH_TOKEN)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
package kr.smartsoltech.wellshe.data.mapper
|
||||
|
||||
import kr.smartsoltech.wellshe.data.entity.*
|
||||
import kr.smartsoltech.wellshe.domain.model.*
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.time.Instant
|
||||
|
||||
// =================
|
||||
// ПОЛЬЗОВАТЕЛЬ
|
||||
// =================
|
||||
|
||||
fun UserProfileEntity.toDomainModel() = User(
|
||||
id = id,
|
||||
name = name,
|
||||
email = email,
|
||||
age = age,
|
||||
height = height.toFloat(),
|
||||
weight = weight,
|
||||
dailyWaterGoal = dailyWaterGoal / 1000f, // конвертируем в литры
|
||||
dailyStepsGoal = dailyStepsGoal,
|
||||
dailyCaloriesGoal = dailyCalorieGoal
|
||||
)
|
||||
|
||||
fun User.toEntity() = UserProfileEntity(
|
||||
id = id,
|
||||
name = name,
|
||||
email = email,
|
||||
age = age,
|
||||
height = height.toInt(),
|
||||
weight = weight,
|
||||
dailyWaterGoal = (dailyWaterGoal * 1000).toInt(), // конвертируем в мл
|
||||
dailyStepsGoal = dailyStepsGoal,
|
||||
dailyCalorieGoal = dailyCaloriesGoal
|
||||
)
|
||||
|
||||
// =================
|
||||
// ВОДНЫЙ БАЛАНС (BodyEntities.kt)
|
||||
// =================
|
||||
|
||||
fun WaterLog.toDomainModel() = WaterIntake(
|
||||
id = id,
|
||||
date = ts.atZone(ZoneId.systemDefault()).toLocalDate(),
|
||||
time = ts.atZone(ZoneId.systemDefault()).toLocalTime(),
|
||||
amount = volumeMl / 1000f // конвертируем в литры
|
||||
)
|
||||
|
||||
fun WaterIntake.toWaterLog() = WaterLog(
|
||||
id = id,
|
||||
ts = date.atTime(time).atZone(ZoneId.systemDefault()).toInstant(),
|
||||
volumeMl = (amount * 1000).toInt(),
|
||||
source = "manual"
|
||||
)
|
||||
|
||||
// Для совместимости с простой структурой WaterLogEntity
|
||||
fun WaterLogEntity.toDomainModel() = WaterIntake(
|
||||
id = id,
|
||||
date = date,
|
||||
time = LocalTime.of(
|
||||
((timestamp % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000)).toInt(),
|
||||
((timestamp % (60 * 60 * 1000)) / (60 * 1000)).toInt()
|
||||
),
|
||||
amount = amount / 1000f // конвертируем в литры
|
||||
)
|
||||
|
||||
fun WaterIntake.toEntity() = WaterLogEntity(
|
||||
id = id,
|
||||
date = date,
|
||||
amount = (amount * 1000).toInt(), // конвертируем в мл
|
||||
timestamp = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
// =================
|
||||
// ВЕС (BodyEntities.kt)
|
||||
// =================
|
||||
|
||||
fun WeightLog.toDomainModel() = WeightData(
|
||||
id = id,
|
||||
date = ts.atZone(ZoneId.systemDefault()).toLocalDate(),
|
||||
weight = weightKg,
|
||||
source = source
|
||||
)
|
||||
|
||||
fun WeightData.toWeightLog() = WeightLog(
|
||||
id = id,
|
||||
ts = date.atStartOfDay(ZoneId.systemDefault()).toInstant(),
|
||||
weightKg = weight,
|
||||
source = source
|
||||
)
|
||||
|
||||
// =================
|
||||
// ТРЕНИРОВКИ (BodyEntities.kt)
|
||||
// =================
|
||||
|
||||
fun kr.smartsoltech.wellshe.data.entity.WorkoutSession.toDomainModel() = WorkoutSessionData(
|
||||
id = id,
|
||||
startTime = startedAt.atZone(ZoneId.systemDefault()).toLocalDateTime(),
|
||||
endTime = endedAt?.atZone(ZoneId.systemDefault())?.toLocalDateTime(),
|
||||
exerciseId = exerciseId,
|
||||
caloriesBurned = kcalTotal?.toInt() ?: 0,
|
||||
distance = distanceKm ?: 0f,
|
||||
notes = notes ?: ""
|
||||
)
|
||||
|
||||
fun WorkoutSessionData.toWorkoutSession() = kr.smartsoltech.wellshe.data.entity.WorkoutSession(
|
||||
id = id,
|
||||
startedAt = startTime.atZone(ZoneId.systemDefault()).toInstant(),
|
||||
endedAt = endTime?.atZone(ZoneId.systemDefault())?.toInstant(),
|
||||
exerciseId = exerciseId,
|
||||
kcalTotal = caloriesBurned.toFloat(),
|
||||
distanceKm = distance,
|
||||
notes = notes
|
||||
)
|
||||
|
||||
// Для совместимости с простой структурой WorkoutEntity
|
||||
fun WorkoutEntity.toDomainModel() = kr.smartsoltech.wellshe.domain.model.WorkoutSession(
|
||||
id = id,
|
||||
type = type,
|
||||
duration = duration,
|
||||
caloriesBurned = caloriesBurned,
|
||||
date = date,
|
||||
startTime = date.atStartOfDay()
|
||||
)
|
||||
|
||||
fun kr.smartsoltech.wellshe.domain.model.WorkoutSession.toEntity() = WorkoutEntity(
|
||||
id = id,
|
||||
date = date,
|
||||
type = type,
|
||||
name = "$type тренировка",
|
||||
duration = duration,
|
||||
caloriesBurned = caloriesBurned,
|
||||
intensity = "moderate"
|
||||
)
|
||||
|
||||
fun WorkoutEntity.toWorkoutData() = WorkoutData(
|
||||
id = id.toString(),
|
||||
date = date,
|
||||
type = when (type.lowercase()) {
|
||||
"cardio" -> WorkoutType.CARDIO
|
||||
"strength" -> WorkoutType.STRENGTH
|
||||
"yoga" -> WorkoutType.YOGA
|
||||
"pilates" -> WorkoutType.PILATES
|
||||
"running" -> WorkoutType.RUNNING
|
||||
"walking" -> WorkoutType.WALKING
|
||||
"cycling" -> WorkoutType.CYCLING
|
||||
"swimming" -> WorkoutType.SWIMMING
|
||||
else -> WorkoutType.CARDIO
|
||||
},
|
||||
duration = duration,
|
||||
intensity = when (intensity.lowercase()) {
|
||||
"low" -> WorkoutIntensity.LOW
|
||||
"moderate" -> WorkoutIntensity.MODERATE
|
||||
"high" -> WorkoutIntensity.HIGH
|
||||
"intense" -> WorkoutIntensity.INTENSE
|
||||
else -> WorkoutIntensity.MODERATE
|
||||
},
|
||||
caloriesBurned = caloriesBurned
|
||||
)
|
||||
|
||||
fun WorkoutData.toWorkoutEntity() = WorkoutEntity(
|
||||
id = id.toLongOrNull() ?: 0,
|
||||
date = date,
|
||||
type = type.name.lowercase(),
|
||||
name = "${type.name} тренировка",
|
||||
duration = duration,
|
||||
caloriesBurned = caloriesBurned,
|
||||
intensity = intensity.name.lowercase()
|
||||
)
|
||||
|
||||
// =================
|
||||
// ФИТНЕС ДАННЫЕ
|
||||
// =================
|
||||
|
||||
fun StepsEntity.toFitnessData() = FitnessData(
|
||||
id = id,
|
||||
date = date,
|
||||
steps = steps,
|
||||
distance = distance,
|
||||
caloriesBurned = caloriesBurned,
|
||||
activeMinutes = 0 // TODO: добавить в entity
|
||||
)
|
||||
|
||||
fun FitnessData.toStepsEntity() = StepsEntity(
|
||||
id = id,
|
||||
date = date,
|
||||
steps = steps,
|
||||
distance = distance,
|
||||
caloriesBurned = caloriesBurned,
|
||||
target = 10000
|
||||
)
|
||||
|
||||
// =================
|
||||
// КАЛОРИИ
|
||||
// =================
|
||||
|
||||
fun CalorieEntity.toDomainModel() = CalorieData(
|
||||
id = id.toString(),
|
||||
date = date,
|
||||
consumed = consumed,
|
||||
burned = burned,
|
||||
target = target
|
||||
)
|
||||
|
||||
fun CalorieData.toEntity() = CalorieEntity(
|
||||
id = id.toLongOrNull() ?: 0,
|
||||
date = date,
|
||||
consumed = consumed,
|
||||
burned = burned,
|
||||
target = target
|
||||
)
|
||||
|
||||
// =================
|
||||
// ЗДОРОВЬЕ
|
||||
// =================
|
||||
|
||||
fun HealthRecordEntity.toHealthData() = HealthData(
|
||||
id = id.toString(),
|
||||
date = date,
|
||||
weight = weight ?: 0f,
|
||||
heartRate = heartRate ?: 70,
|
||||
bloodPressureSystolic = bloodPressureS ?: 120,
|
||||
bloodPressureDiastolic = bloodPressureD ?: 80,
|
||||
mood = Mood.NEUTRAL, // TODO: добавить mood в HealthRecordEntity
|
||||
energyLevel = energyLevel ?: 5,
|
||||
stressLevel = 5, // TODO: добавить stressLevel в HealthRecordEntity
|
||||
symptoms = symptoms ?: emptyList()
|
||||
)
|
||||
|
||||
fun HealthData.toEntity() = HealthRecordEntity(
|
||||
id = id.toLongOrNull() ?: 0,
|
||||
date = date,
|
||||
weight = weight,
|
||||
heartRate = heartRate,
|
||||
bloodPressureS = bloodPressureSystolic,
|
||||
bloodPressureD = bloodPressureDiastolic,
|
||||
temperature = null,
|
||||
energyLevel = energyLevel,
|
||||
symptoms = symptoms,
|
||||
notes = null
|
||||
)
|
||||
|
||||
// =================
|
||||
// МЕНСТРУАЛЬНЫЙ ЦИКЛ
|
||||
// =================
|
||||
|
||||
fun CyclePeriodEntity.toCycleData() = CycleData(
|
||||
id = id.toString(),
|
||||
cycleLength = cycleLength ?: 28,
|
||||
periodLength = if (endDate != null) {
|
||||
(endDate.toEpochDay() - startDate.toEpochDay()).toInt()
|
||||
} else 5,
|
||||
lastPeriodDate = startDate,
|
||||
nextPeriodDate = startDate.plusDays(cycleLength?.toLong() ?: 28),
|
||||
ovulationDate = startDate.plusDays((cycleLength ?: 28) / 2L)
|
||||
)
|
||||
|
||||
fun CycleData.toPeriodEntity() = CyclePeriodEntity(
|
||||
id = id.toLongOrNull() ?: 0,
|
||||
startDate = lastPeriodDate,
|
||||
endDate = lastPeriodDate.plusDays(periodLength.toLong()),
|
||||
flow = "",
|
||||
symptoms = emptyList(),
|
||||
cycleLength = cycleLength
|
||||
)
|
||||
|
||||
// =================
|
||||
// НАПИТКИ И ПИТАНИЕ
|
||||
// =================
|
||||
|
||||
fun Beverage.toDomainModel() = BeverageData(
|
||||
id = id,
|
||||
name = name,
|
||||
brand = brand,
|
||||
category = category,
|
||||
isCaffeinated = isCaffeinated,
|
||||
isSweetened = isSweetened
|
||||
)
|
||||
|
||||
fun BeverageLog.toDomainModel() = BeverageLogData(
|
||||
id = id,
|
||||
timestamp = ts,
|
||||
beverageId = beverageId,
|
||||
servingId = servingId,
|
||||
servingsCount = servingsCount,
|
||||
notes = notes
|
||||
)
|
||||
|
||||
// =================
|
||||
// УПРАЖНЕНИЯ
|
||||
// =================
|
||||
|
||||
fun Exercise.toDomainModel() = ExerciseData(
|
||||
id = id,
|
||||
name = name,
|
||||
category = category,
|
||||
description = description,
|
||||
metValue = metValue,
|
||||
source = source
|
||||
)
|
||||
|
||||
// =================
|
||||
// ДОПОЛНИТЕЛЬНЫЕ МОДЕЛИ ДАННЫХ
|
||||
// =================
|
||||
|
||||
data class CalorieData(
|
||||
val id: String = "",
|
||||
val date: LocalDate = LocalDate.now(),
|
||||
val consumed: Int = 0,
|
||||
val burned: Int = 0,
|
||||
val target: Int = 2000
|
||||
)
|
||||
|
||||
data class WeightData(
|
||||
val id: Long = 0,
|
||||
val date: LocalDate = LocalDate.now(),
|
||||
val weight: Float = 0f,
|
||||
val source: String = "manual"
|
||||
)
|
||||
|
||||
data class WorkoutSessionData(
|
||||
val id: Long = 0,
|
||||
val startTime: LocalDateTime = LocalDateTime.now(),
|
||||
val endTime: LocalDateTime? = null,
|
||||
val exerciseId: Long = 0,
|
||||
val caloriesBurned: Int = 0,
|
||||
val distance: Float = 0f,
|
||||
val notes: String = ""
|
||||
)
|
||||
|
||||
data class BeverageData(
|
||||
val id: Long = 0,
|
||||
val name: String = "",
|
||||
val brand: String? = null,
|
||||
val category: String = "",
|
||||
val isCaffeinated: Boolean = false,
|
||||
val isSweetened: Boolean = false
|
||||
)
|
||||
|
||||
data class BeverageLogData(
|
||||
val id: Long = 0,
|
||||
val timestamp: Instant = Instant.now(),
|
||||
val beverageId: Long = 0,
|
||||
val servingId: Long = 0,
|
||||
val servingsCount: Int = 1,
|
||||
val notes: String? = null
|
||||
)
|
||||
|
||||
data class ExerciseData(
|
||||
val id: Long = 0,
|
||||
val name: String = "",
|
||||
val category: String = "",
|
||||
val description: String? = null,
|
||||
val metValue: Float? = null,
|
||||
val source: String = ""
|
||||
)
|
||||
|
||||
// =================
|
||||
// ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ
|
||||
// =================
|
||||
|
||||
fun Long.toLocalDateTime(): LocalDateTime =
|
||||
LocalDateTime.ofInstant(Instant.ofEpochMilli(this), ZoneId.systemDefault())
|
||||
|
||||
fun LocalDateTime.toTimestamp(): Long =
|
||||
this.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
|
||||
|
||||
fun LocalDate.toTimestamp(): Long =
|
||||
this.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
|
||||
|
||||
fun Instant.toLocalDate(): LocalDate =
|
||||
this.atZone(ZoneId.systemDefault()).toLocalDate()
|
||||
|
||||
fun Instant.toLocalDateTime(): LocalDateTime =
|
||||
this.atZone(ZoneId.systemDefault()).toLocalDateTime()
|
||||
|
||||
fun LocalDateTime.toInstant(): Instant =
|
||||
this.atZone(ZoneId.systemDefault()).toInstant()
|
||||
|
||||
fun LocalDate.toInstant(): Instant =
|
||||
this.atStartOfDay(ZoneId.systemDefault()).toInstant()
|
||||
@@ -0,0 +1,32 @@
|
||||
package kr.smartsoltech.wellshe.data.model
|
||||
|
||||
data class ServerHealthResponse(
|
||||
val status: String,
|
||||
val timestamp: String? = null,
|
||||
val version: String? = null
|
||||
)
|
||||
|
||||
data class ServerStatus(
|
||||
val url: String,
|
||||
val isHealthy: Boolean,
|
||||
val pingMs: Long,
|
||||
val status: HealthStatus,
|
||||
val error: String? = null
|
||||
)
|
||||
|
||||
enum class HealthStatus {
|
||||
EXCELLENT, // < 10ms, зеленый
|
||||
GOOD, // 10-200ms, желтый
|
||||
POOR, // 200-600ms, оранжевый
|
||||
BAD, // 600ms+, красный
|
||||
OFFLINE // недоступен, серый
|
||||
}
|
||||
|
||||
fun Long.toHealthStatus(): HealthStatus {
|
||||
return when {
|
||||
this < 10 -> HealthStatus.EXCELLENT
|
||||
this < 200 -> HealthStatus.GOOD
|
||||
this < 600 -> HealthStatus.POOR
|
||||
else -> HealthStatus.BAD
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package kr.smartsoltech.wellshe.data.network
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import kr.smartsoltech.wellshe.data.preferences.ServerPreferences
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.gson.GsonConverterFactory
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Класс для настройки и создания API-клиентов
|
||||
*/
|
||||
class ApiClient(private val serverPreferences: ServerPreferences) {
|
||||
private val defaultBaseUrl = "http://192.168.0.112:8000/api/v1/"
|
||||
private val connectTimeout = 15L
|
||||
private val readTimeout = 15L
|
||||
private val writeTimeout = 15L
|
||||
|
||||
/**
|
||||
* Создает экземпляр Retrofit с настройками для работы с API
|
||||
*/
|
||||
private fun createRetrofit(baseUrl: String? = null): Retrofit {
|
||||
val actualBaseUrl = baseUrl ?: serverPreferences.getApiBaseUrl()
|
||||
|
||||
val gson: Gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(actualBaseUrl)
|
||||
.client(createOkHttpClient())
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Создает настроенный OkHttpClient с логированием и таймаутами
|
||||
*/
|
||||
private fun createOkHttpClient(): OkHttpClient {
|
||||
val loggingInterceptor = HttpLoggingInterceptor().apply {
|
||||
level = HttpLoggingInterceptor.Level.BODY
|
||||
}
|
||||
|
||||
return OkHttpClient.Builder()
|
||||
.addInterceptor(loggingInterceptor)
|
||||
.connectTimeout(connectTimeout, TimeUnit.SECONDS)
|
||||
.readTimeout(readTimeout, TimeUnit.SECONDS)
|
||||
.writeTimeout(writeTimeout, TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Создает сервис для работы с авторизацией
|
||||
*/
|
||||
fun createAuthService(): AuthService {
|
||||
return createRetrofit().create(AuthService::class.java)
|
||||
}
|
||||
|
||||
/**
|
||||
* Создает сервис для работы с экстренными оповещениями
|
||||
*/
|
||||
fun createEmergencyService(): EmergencyService {
|
||||
return createRetrofit().create(EmergencyService::class.java)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package kr.smartsoltech.wellshe.data.network
|
||||
|
||||
import kotlinx.coroutines.flow.firstOrNull
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kr.smartsoltech.wellshe.data.local.AuthTokenRepository
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Response
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Перехватчик, добавляющий токен авторизации в заголовки запросов
|
||||
*/
|
||||
@Singleton
|
||||
class AuthInterceptor @Inject constructor(
|
||||
private val authTokenRepository: AuthTokenRepository
|
||||
) : Interceptor {
|
||||
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val originalRequest = chain.request()
|
||||
|
||||
// Пробуем получить токен авторизации (в блокирующем режиме, т.к. Interceptor не поддерживает suspend функции)
|
||||
val token = runBlocking { authTokenRepository.authToken.firstOrNull() }
|
||||
|
||||
// Если токен есть, добавляем его в заголовок запроса
|
||||
val modifiedRequest = if (!token.isNullOrEmpty()) {
|
||||
originalRequest.newBuilder()
|
||||
.header("Authorization", "Bearer $token")
|
||||
.build()
|
||||
} else {
|
||||
originalRequest
|
||||
}
|
||||
|
||||
return chain.proceed(modifiedRequest)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package kr.smartsoltech.wellshe.data.network
|
||||
|
||||
import kr.smartsoltech.wellshe.model.auth.*
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Header
|
||||
import retrofit2.http.POST
|
||||
|
||||
/**
|
||||
* Интерфейс для работы с API авторизации
|
||||
*/
|
||||
interface AuthService {
|
||||
/**
|
||||
* Регистрация нового пользователя
|
||||
*/
|
||||
@POST("auth/register")
|
||||
suspend fun register(@Body request: RegisterRequest): Response<RegisterResponseWrapper>
|
||||
|
||||
/**
|
||||
* Вход в систему
|
||||
*/
|
||||
@POST("auth/login")
|
||||
suspend fun login(@Body request: AuthRequest): Response<DirectAuthResponse>
|
||||
|
||||
/**
|
||||
* Обновление токена
|
||||
*/
|
||||
@POST("auth/refresh")
|
||||
suspend fun refreshToken(@Body request: TokenRefreshRequest): Response<TokenRefreshResponseWrapper>
|
||||
|
||||
/**
|
||||
* Выход из системы
|
||||
*/
|
||||
@POST("auth/logout")
|
||||
suspend fun logout(@Header("Authorization") token: String): Response<BaseResponseWrapper>
|
||||
|
||||
/**
|
||||
* Получение профиля текущего пользователя
|
||||
*/
|
||||
@GET("users/me")
|
||||
suspend fun getProfile(@Header("Authorization") token: String): Response<UserProfileResponseWrapper>
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package kr.smartsoltech.wellshe.data.network
|
||||
|
||||
import kr.smartsoltech.wellshe.model.auth.BaseResponseWrapper
|
||||
import kr.smartsoltech.wellshe.model.emergency.*
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.*
|
||||
|
||||
/**
|
||||
* Интерфейс для работы с API экстренных оповещений
|
||||
*/
|
||||
interface EmergencyService {
|
||||
/**
|
||||
* Создание нового экстренного оповещения
|
||||
*/
|
||||
@POST("emergency/alert")
|
||||
suspend fun createAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: EmergencyAlertRequest
|
||||
): Response<EmergencyAlertResponseWrapper>
|
||||
|
||||
/**
|
||||
* Получение информации о статусе экстренного оповещения
|
||||
*/
|
||||
@GET("emergency/alert/{alert_id}")
|
||||
suspend fun getAlertStatus(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: String
|
||||
): Response<EmergencyAlertStatusWrapper>
|
||||
|
||||
/**
|
||||
* Обновление местоположения для активного оповещения
|
||||
*/
|
||||
@PUT("emergency/alert/{alert_id}/location")
|
||||
suspend fun updateLocation(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: String,
|
||||
@Body request: LocationUpdateRequest
|
||||
): Response<LocationUpdateResponseWrapper>
|
||||
|
||||
/**
|
||||
* Отмена активного экстренного оповещения
|
||||
*/
|
||||
@POST("emergency/alert/{alert_id}/cancel")
|
||||
suspend fun cancelAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: String,
|
||||
@Body request: AlertCancelRequest
|
||||
): Response<AlertCancelResponseWrapper>
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package kr.smartsoltech.wellshe.data.network
|
||||
|
||||
import com.google.gson.Gson
|
||||
import kr.smartsoltech.wellshe.data.local.AuthTokenRepository
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.gson.GsonConverterFactory
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class RetrofitFactory @Inject constructor(
|
||||
private val gson: Gson,
|
||||
private val authTokenRepository: AuthTokenRepository
|
||||
) {
|
||||
|
||||
fun create(baseUrl: String): Retrofit {
|
||||
val loggingInterceptor = HttpLoggingInterceptor().apply {
|
||||
level = HttpLoggingInterceptor.Level.BASIC
|
||||
}
|
||||
|
||||
val authInterceptor = AuthInterceptor(authTokenRepository)
|
||||
|
||||
val client = OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
.readTimeout(15, TimeUnit.SECONDS)
|
||||
.writeTimeout(15, TimeUnit.SECONDS)
|
||||
.addInterceptor(authInterceptor)
|
||||
.addInterceptor(loggingInterceptor)
|
||||
.build()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(baseUrl)
|
||||
.client(client)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package kr.smartsoltech.wellshe.data.network
|
||||
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.scopes.ActivityRetainedScoped
|
||||
import kr.smartsoltech.wellshe.data.preferences.ServerPreferences
|
||||
import retrofit2.Retrofit
|
||||
import javax.inject.Inject
|
||||
|
||||
@ActivityRetainedScoped
|
||||
class RetrofitProvider @Inject constructor(
|
||||
private val serverPreferences: ServerPreferences,
|
||||
private val retrofitFactory: RetrofitFactory
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "RetrofitProvider"
|
||||
}
|
||||
|
||||
private var currentServerUrl: String? = null
|
||||
private var currentRetrofit: Retrofit? = null
|
||||
|
||||
fun getRetrofit(): Retrofit {
|
||||
val serverUrl = serverPreferences.getApiBaseUrl()
|
||||
Log.d(TAG, "Getting Retrofit for serverUrl: $serverUrl")
|
||||
|
||||
if (currentRetrofit == null || currentServerUrl != serverUrl) {
|
||||
Log.d(TAG, "Creating new Retrofit instance. Old URL: $currentServerUrl, New URL: $serverUrl")
|
||||
currentServerUrl = serverUrl
|
||||
currentRetrofit = retrofitFactory.create(serverUrl)
|
||||
Log.d(TAG, "Retrofit instance created successfully with baseUrl: $serverUrl")
|
||||
|
||||
// Показываем настройки для отладки
|
||||
serverPreferences.debugSettings()
|
||||
} else {
|
||||
Log.d(TAG, "Reusing existing Retrofit instance with baseUrl: $serverUrl")
|
||||
}
|
||||
|
||||
return currentRetrofit!!
|
||||
}
|
||||
|
||||
fun recreateRetrofit() {
|
||||
Log.d(TAG, "Forcing Retrofit recreation. Current URL: $currentServerUrl")
|
||||
currentRetrofit = null
|
||||
currentServerUrl = null
|
||||
Log.d(TAG, "Retrofit instance cleared, will be recreated on next access")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package kr.smartsoltech.wellshe.data.preferences
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class ServerPreferences @Inject constructor(
|
||||
@ApplicationContext private val context: Context
|
||||
) {
|
||||
private val sharedPreferences: SharedPreferences =
|
||||
context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ServerPreferences"
|
||||
private const val PREF_NAME = "server_preferences"
|
||||
private const val KEY_SERVER_URL = "server_url"
|
||||
// Используем локальный IP для разработки - можно легко изменить через UI
|
||||
private const val DEFAULT_SERVER_URL = "http://10.0.2.2:8000"
|
||||
}
|
||||
|
||||
fun getServerUrl(): String {
|
||||
val url = sharedPreferences.getString(KEY_SERVER_URL, DEFAULT_SERVER_URL) ?: DEFAULT_SERVER_URL
|
||||
Log.d(TAG, "Getting server URL: $url")
|
||||
return url
|
||||
}
|
||||
|
||||
fun getApiBaseUrl(): String {
|
||||
val serverUrl = getServerUrl()
|
||||
val apiUrl = if (serverUrl.endsWith("/")) {
|
||||
"${serverUrl}api/v1/"
|
||||
} else {
|
||||
"$serverUrl/api/v1/"
|
||||
}
|
||||
Log.d(TAG, "Getting API base URL: $apiUrl")
|
||||
return apiUrl
|
||||
}
|
||||
|
||||
fun setServerUrl(url: String) {
|
||||
Log.d(TAG, "Setting server URL: $url")
|
||||
val success = sharedPreferences.edit()
|
||||
.putString(KEY_SERVER_URL, url)
|
||||
.commit() // Используем commit() вместо apply() для синхронного сохранения
|
||||
|
||||
if (success) {
|
||||
Log.d(TAG, "Server URL saved successfully: $url")
|
||||
// Проверяем, что значение действительно сохранилось
|
||||
val savedUrl = sharedPreferences.getString(KEY_SERVER_URL, "NOT_FOUND")
|
||||
Log.d(TAG, "Verification - saved URL: $savedUrl")
|
||||
} else {
|
||||
Log.e(TAG, "Failed to save server URL: $url")
|
||||
}
|
||||
}
|
||||
|
||||
// Метод для получения предложенных серверов
|
||||
fun getSuggestedServers(): List<String> {
|
||||
return listOf(
|
||||
"http://10.0.2.2:8000", // Android Emulator localhost
|
||||
"http://192.168.0.112:8000", // Локальная сеть
|
||||
"http://localhost:8000", // Localhost
|
||||
"https://api.wellshe.example.com" // Пример продакшн сервера
|
||||
)
|
||||
}
|
||||
|
||||
// Метод для отладки - показывает все сохраненные настройки
|
||||
fun debugSettings() {
|
||||
Log.d(TAG, "=== Debug Server Settings ===")
|
||||
Log.d(TAG, "Preferences file: $PREF_NAME")
|
||||
Log.d(TAG, "Current server URL: ${getServerUrl()}")
|
||||
Log.d(TAG, "Default server URL: $DEFAULT_SERVER_URL")
|
||||
Log.d(TAG, "All preferences: ${sharedPreferences.all}")
|
||||
Log.d(TAG, "===============================")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package kr.smartsoltech.wellshe.data.repo
|
||||
|
||||
// Устаревший репозиторий, используйте kr.smartsoltech.wellshe.data.repository.AuthRepository вместо этого
|
||||
@Deprecated("Используйте kr.smartsoltech.wellshe.data.repository.AuthRepository вместо этого")
|
||||
typealias AuthRepository = kr.smartsoltech.wellshe.data.repository.AuthRepository
|
||||
@@ -0,0 +1,203 @@
|
||||
package kr.smartsoltech.wellshe.data.repository
|
||||
|
||||
import kr.smartsoltech.wellshe.data.local.AuthTokenRepository
|
||||
import kr.smartsoltech.wellshe.data.network.AuthService
|
||||
import kr.smartsoltech.wellshe.data.storage.TokenManager
|
||||
import kr.smartsoltech.wellshe.model.auth.*
|
||||
import kr.smartsoltech.wellshe.util.Result
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Репозиторий для работы с авторизацией и профилем пользователя
|
||||
*/
|
||||
@Singleton
|
||||
class AuthRepository @Inject constructor(
|
||||
private val authService: AuthService,
|
||||
private val authTokenRepository: AuthTokenRepository,
|
||||
private val tokenManager: TokenManager
|
||||
) {
|
||||
|
||||
/**
|
||||
* Вход в систему
|
||||
*/
|
||||
suspend fun login(identifier: String, password: String, isEmail: Boolean): Result<AuthTokenResponse> {
|
||||
return try {
|
||||
// Если имя пользователя - galya0815, преобразуем его в Galya0815 с большой буквы
|
||||
val correctedIdentifier = if (!isEmail && identifier.equals("galya0815", ignoreCase = true)) {
|
||||
"Galya0815"
|
||||
} else {
|
||||
identifier
|
||||
}
|
||||
|
||||
val authRequest = if (isEmail) {
|
||||
AuthRequest(email = correctedIdentifier, password = password)
|
||||
} else {
|
||||
AuthRequest(username = correctedIdentifier, password = password)
|
||||
}
|
||||
|
||||
// Вызываем реальный API-метод login
|
||||
val response = authService.login(authRequest)
|
||||
|
||||
// Логирование для отладки
|
||||
android.util.Log.d("AuthRepository", "Login response: ${response.code()}, isSuccessful: ${response.isSuccessful}")
|
||||
if (response.body() != null) {
|
||||
android.util.Log.d("AuthRepository", "Response body: ${response.body()}")
|
||||
} else if (response.errorBody() != null) {
|
||||
android.util.Log.d("AuthRepository", "Error body: ${response.errorBody()?.string()}")
|
||||
}
|
||||
|
||||
if (response.isSuccessful) {
|
||||
val directAuthResponse = response.body()
|
||||
|
||||
// Если ответ успешен, но не содержит ожидаемых данных
|
||||
if (directAuthResponse == null) {
|
||||
return Result.Error(Exception("Получен пустой ответ от сервера"))
|
||||
}
|
||||
|
||||
try {
|
||||
// Создаем объект AuthTokenResponse из DirectAuthResponse
|
||||
val authTokenResponse = AuthTokenResponse(
|
||||
accessToken = directAuthResponse.accessToken,
|
||||
tokenType = directAuthResponse.tokenType,
|
||||
refreshToken = "", // Может отсутствовать в ответе сервера
|
||||
expiresIn = 0 // Может отсутствовать в ответе сервера
|
||||
)
|
||||
|
||||
// Сохраняем токен в локальное хранилище
|
||||
tokenManager.saveAccessToken(authTokenResponse.accessToken)
|
||||
tokenManager.saveTokenType(authTokenResponse.tokenType)
|
||||
|
||||
android.util.Log.d("AuthRepository", "Login successful, token: ${authTokenResponse.accessToken.take(15)}...")
|
||||
Result.Success(authTokenResponse)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("AuthRepository", "Error processing auth response: ${e.message}", e)
|
||||
Result.Error(Exception("Ошибка обработки ответа авторизации: ${e.message}"))
|
||||
}
|
||||
} else {
|
||||
val errorMessage = response.errorBody()?.string() ?: "Неизвестная ошибка авторизации"
|
||||
android.util.Log.e("AuthRepository", "Login error: $errorMessage (code ${response.code()})")
|
||||
Result.Error(Exception("Ошибка авторизации: $errorMessage (код ${response.code()})"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("AuthRepository", "Exception during login: ${e.message}", e)
|
||||
Result.Error(Exception("Ошибка при подключении к серверу: ${e.message}", e))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрация нового пользователя
|
||||
*/
|
||||
suspend fun register(
|
||||
email: String,
|
||||
username: String,
|
||||
password: String,
|
||||
firstName: String,
|
||||
lastName: String,
|
||||
phone: String
|
||||
): Result<Boolean> {
|
||||
return try {
|
||||
val registerRequest = RegisterRequest(
|
||||
email = email,
|
||||
username = username,
|
||||
password = password,
|
||||
first_name = firstName,
|
||||
last_name = lastName,
|
||||
phone = phone
|
||||
)
|
||||
|
||||
// Вызываем реальный API-метод register
|
||||
val response = authService.register(registerRequest)
|
||||
|
||||
if (response.isSuccessful) {
|
||||
Result.Success(true)
|
||||
} else {
|
||||
val errorMessage = response.errorBody()?.string() ?: "Неизвестная ошибка регистрации"
|
||||
Result.Error(Exception("Ошибка регистрации: $errorMessage (код ${response.code()})"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.Error(Exception("Ошибка при подключении к серверу: ${e.message}", e))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выход из системы
|
||||
*/
|
||||
suspend fun logout(accessToken: String): Result<Boolean> {
|
||||
return try {
|
||||
// Формируем заголовок авторизации
|
||||
val authHeader = "Bearer $accessToken"
|
||||
|
||||
// Вызываем реальный API-метод logout
|
||||
val response = authService.logout(authHeader)
|
||||
|
||||
// Независимо от результата запроса очищаем локальные данные авторизации
|
||||
authTokenRepository.clearAuthData()
|
||||
tokenManager.clearTokens()
|
||||
|
||||
if (response.isSuccessful) {
|
||||
Result.Success(true)
|
||||
} else {
|
||||
// Даже при ошибке API считаем выход успешным, так как локальные данные очищены
|
||||
Result.Success(true)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Даже при исключении считаем выход успешным, так как локальные данные очищены
|
||||
Result.Success(true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновление токена доступа
|
||||
*/
|
||||
suspend fun refreshToken(refreshToken: String): Result<TokenResponse> {
|
||||
return try {
|
||||
// Создаем запрос на обновление токена
|
||||
val tokenRefreshRequest = TokenRefreshRequest(refresh_token = refreshToken)
|
||||
|
||||
// Вызываем реальный API-метод refreshToken
|
||||
val response = authService.refreshToken(tokenRefreshRequest)
|
||||
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
val tokenResponse = response.body()?.data
|
||||
if (tokenResponse != null) {
|
||||
Result.Success(tokenResponse)
|
||||
} else {
|
||||
Result.Error(Exception("Ответ сервера не содержит данных обновления токена"))
|
||||
}
|
||||
} else {
|
||||
val errorMessage = response.errorBody()?.string() ?: "Неизвестная ошибка обновления токена"
|
||||
Result.Error(Exception("Ошибка обновления токена: $errorMessage (код ${response.code()})"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.Error(Exception("Ошибка при подключении к серверу: ${e.message}", e))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение профиля пользователя
|
||||
*/
|
||||
suspend fun getUserProfile(accessToken: String): Result<UserProfile> {
|
||||
return try {
|
||||
// Формируем заголовок авторизации
|
||||
val authHeader = "Bearer $accessToken"
|
||||
|
||||
// Вызываем реальный API-метод получения профиля
|
||||
val response = authService.getProfile(authHeader)
|
||||
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
val userProfile = response.body()?.data
|
||||
if (userProfile != null) {
|
||||
Result.Success(userProfile)
|
||||
} else {
|
||||
Result.Error(Exception("Ответ сервера не содержит данных профиля"))
|
||||
}
|
||||
} else {
|
||||
val errorMessage = response.errorBody()?.string() ?: "Неизвестная ошибка получения профиля"
|
||||
Result.Error(Exception("Ошибка получения профиля: $errorMessage (код ${response.code()})"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.Error(Exception("Ошибка при подключении к серверу: ${e.message}", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -263,7 +263,6 @@ class CycleRepository @Inject constructor(
|
||||
endDate = historyEntity.periodEnd,
|
||||
flow = historyEntity.flow,
|
||||
symptoms = historyEntity.symptoms,
|
||||
mood = historyEntity.mood,
|
||||
cycleLength = historyEntity.cycleLength
|
||||
)
|
||||
}
|
||||
@@ -277,7 +276,6 @@ class CycleRepository @Inject constructor(
|
||||
periodEnd = period.endDate,
|
||||
flow = period.flow,
|
||||
symptoms = period.symptoms,
|
||||
mood = period.mood,
|
||||
cycleLength = period.cycleLength,
|
||||
atypical = false // по умолчанию не отмечаем как нетипичный
|
||||
)
|
||||
@@ -292,7 +290,6 @@ class CycleRepository @Inject constructor(
|
||||
periodEnd = period.endDate,
|
||||
flow = period.flow,
|
||||
symptoms = period.symptoms,
|
||||
mood = period.mood,
|
||||
cycleLength = period.cycleLength,
|
||||
atypical = false // сохраняем существующее значение, если возможно
|
||||
)
|
||||
@@ -306,7 +303,6 @@ class CycleRepository @Inject constructor(
|
||||
periodEnd = period.endDate,
|
||||
flow = period.flow,
|
||||
symptoms = period.symptoms,
|
||||
mood = period.mood,
|
||||
cycleLength = period.cycleLength,
|
||||
atypical = false
|
||||
)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package kr.smartsoltech.wellshe.data.repository
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kr.smartsoltech.wellshe.data.network.EmergencyService
|
||||
import kr.smartsoltech.wellshe.model.emergency.*
|
||||
import kr.smartsoltech.wellshe.util.Result
|
||||
|
||||
/**
|
||||
* Репозиторий для работы с экстренными оповещениями
|
||||
*/
|
||||
class EmergencyRepository(private val emergencyService: EmergencyService) {
|
||||
|
||||
/**
|
||||
* Создание нового экстренного оповещения
|
||||
*/
|
||||
suspend fun createAlert(
|
||||
token: String,
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
message: String? = null,
|
||||
batteryLevel: Int? = null,
|
||||
contactIds: List<String>? = null
|
||||
): Result<EmergencyAlertResponse> {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val bearerToken = "Bearer $token"
|
||||
val locationData = LocationData(latitude, longitude)
|
||||
val request = EmergencyAlertRequest(locationData, message, batteryLevel, contactIds)
|
||||
|
||||
val response = emergencyService.createAlert(bearerToken, request)
|
||||
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
Result.Success(response.body()!!.data)
|
||||
} else {
|
||||
Result.Error(Exception("Ошибка создания оповещения: ${response.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение статуса экстренного оповещения
|
||||
*/
|
||||
suspend fun getAlertStatus(token: String, alertId: String): Result<EmergencyAlertStatus> {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val bearerToken = "Bearer $token"
|
||||
val response = emergencyService.getAlertStatus(bearerToken, alertId)
|
||||
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
Result.Success(response.body()!!.data)
|
||||
} else {
|
||||
Result.Error(Exception("Ошибка получения статуса оповещения: ${response.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновление местоположения в активном оповещении
|
||||
*/
|
||||
suspend fun updateLocation(
|
||||
token: String,
|
||||
alertId: String,
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
accuracy: Float? = null,
|
||||
batteryLevel: Int? = null
|
||||
): Result<LocationUpdateResponse> {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val bearerToken = "Bearer $token"
|
||||
val request = LocationUpdateRequest(latitude, longitude, accuracy, batteryLevel)
|
||||
|
||||
val response = emergencyService.updateLocation(bearerToken, alertId, request)
|
||||
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
Result.Success(response.body()!!.data)
|
||||
} else {
|
||||
Result.Error(Exception("Ошибка обновления местоположения: ${response.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Отмена экстренного оповещения
|
||||
*/
|
||||
suspend fun cancelAlert(
|
||||
token: String,
|
||||
alertId: String,
|
||||
reason: String? = null,
|
||||
details: String? = null
|
||||
): Result<AlertCancelResponse> {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val bearerToken = "Bearer $token"
|
||||
val request = AlertCancelRequest(reason, details)
|
||||
|
||||
val response = emergencyService.cancelAlert(bearerToken, alertId, request)
|
||||
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
Result.Success(response.body()!!.data)
|
||||
} else {
|
||||
Result.Error(Exception("Ошибка отмены оповещения: ${response.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package kr.smartsoltech.wellshe.data.repository
|
||||
|
||||
import android.util.Log
|
||||
import kr.smartsoltech.wellshe.data.api.HealthApi
|
||||
import kr.smartsoltech.wellshe.data.model.HealthStatus
|
||||
import kr.smartsoltech.wellshe.data.model.ServerStatus
|
||||
import kr.smartsoltech.wellshe.data.model.toHealthStatus
|
||||
import kr.smartsoltech.wellshe.data.network.RetrofitFactory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class ServerHealthRepository @Inject constructor(
|
||||
private val retrofitFactory: RetrofitFactory
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "ServerHealthRepository"
|
||||
private const val HEALTH_CHECK_TIMEOUT_MS = 5000L
|
||||
}
|
||||
|
||||
suspend fun checkServerHealth(serverUrl: String): ServerStatus = withContext(Dispatchers.IO) {
|
||||
Log.d(TAG, "Checking health for server: $serverUrl")
|
||||
|
||||
try {
|
||||
val startTime = System.currentTimeMillis()
|
||||
|
||||
// Создаем отдельный Retrofit для health check'а
|
||||
val baseUrl = if (serverUrl.endsWith("/")) serverUrl else "$serverUrl/"
|
||||
val retrofit = retrofitFactory.create(baseUrl)
|
||||
val healthApi = retrofit.create(HealthApi::class.java)
|
||||
|
||||
// Выполняем запрос с таймаутом
|
||||
val response = withTimeoutOrNull(HEALTH_CHECK_TIMEOUT_MS) {
|
||||
healthApi.getHealth()
|
||||
}
|
||||
|
||||
val endTime = System.currentTimeMillis()
|
||||
val pingMs = endTime - startTime
|
||||
|
||||
Log.d(TAG, "Health check for $serverUrl completed in ${pingMs}ms")
|
||||
|
||||
if (response != null && response.isSuccessful) {
|
||||
val healthResponse = response.body()
|
||||
val isHealthy = healthResponse?.status?.lowercase() == "healthy" ||
|
||||
healthResponse?.status?.lowercase() == "ok"
|
||||
|
||||
Log.d(TAG, "Server $serverUrl is ${if (isHealthy) "healthy" else "unhealthy"}, ping: ${pingMs}ms")
|
||||
|
||||
ServerStatus(
|
||||
url = serverUrl,
|
||||
isHealthy = isHealthy,
|
||||
pingMs = pingMs,
|
||||
status = if (isHealthy) pingMs.toHealthStatus() else HealthStatus.POOR
|
||||
)
|
||||
} else {
|
||||
Log.w(TAG, "Health check failed for $serverUrl: HTTP ${response?.code()}")
|
||||
ServerStatus(
|
||||
url = serverUrl,
|
||||
isHealthy = false,
|
||||
pingMs = pingMs,
|
||||
status = HealthStatus.OFFLINE,
|
||||
error = "HTTP ${response?.code() ?: "timeout"}"
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error checking health for $serverUrl", e)
|
||||
ServerStatus(
|
||||
url = serverUrl,
|
||||
isHealthy = false,
|
||||
pingMs = HEALTH_CHECK_TIMEOUT_MS,
|
||||
status = HealthStatus.OFFLINE,
|
||||
error = e.message ?: "Connection failed"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun checkMultipleServers(serverUrls: List<String>): List<ServerStatus> = withContext(Dispatchers.IO) {
|
||||
Log.d(TAG, "Checking health for ${serverUrls.size} servers")
|
||||
|
||||
val deferredResults = serverUrls.map { url ->
|
||||
async { checkServerHealth(url) }
|
||||
}
|
||||
|
||||
val results = deferredResults.awaitAll()
|
||||
|
||||
Log.d(TAG, "Health check completed for all servers")
|
||||
results.forEach { status ->
|
||||
Log.d(TAG, "Server ${status.url}: ${status.status} (${status.pingMs}ms)")
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@ import kr.smartsoltech.wellshe.domain.model.User
|
||||
import kr.smartsoltech.wellshe.domain.model.WaterIntake
|
||||
import kr.smartsoltech.wellshe.domain.model.WorkoutSession
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
@@ -21,7 +20,6 @@ import javax.inject.Singleton
|
||||
class WellSheRepository @Inject constructor(
|
||||
private val waterLogDao: WaterLogDao,
|
||||
private val cyclePeriodDao: CyclePeriodDao,
|
||||
private val sleepLogDao: SleepLogDao,
|
||||
private val healthRecordDao: HealthRecordDao,
|
||||
private val workoutDao: WorkoutDao,
|
||||
private val calorieDao: CalorieDao,
|
||||
@@ -45,8 +43,7 @@ class WellSheRepository @Inject constructor(
|
||||
weight = 60f,
|
||||
dailyWaterGoal = 2.5f,
|
||||
dailyStepsGoal = 10000,
|
||||
dailyCaloriesGoal = 2000,
|
||||
dailySleepGoal = 8.0f
|
||||
dailyCaloriesGoal = 2000
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -157,231 +154,89 @@ class WellSheRepository @Inject constructor(
|
||||
// TODO: Реализовать окончание тренировки
|
||||
}
|
||||
|
||||
// =================
|
||||
// СОН
|
||||
// =================
|
||||
|
||||
suspend fun getSleepForDate(date: LocalDate): SleepLogEntity? {
|
||||
return sleepLogDao.getSleepForDate(date)
|
||||
}
|
||||
|
||||
fun getRecentSleepLogs(): Flow<List<SleepLogEntity>> {
|
||||
return sleepLogDao.getRecentSleepLogs()
|
||||
}
|
||||
|
||||
suspend fun addSleepRecord(date: LocalDate, bedTime: String, wakeTime: String, quality: String, notes: String) {
|
||||
// Вычисляем продолжительность сна
|
||||
val duration = calculateSleepDuration(bedTime, wakeTime)
|
||||
|
||||
sleepLogDao.insertSleepLog(
|
||||
SleepLogEntity(
|
||||
date = date,
|
||||
bedTime = bedTime,
|
||||
wakeTime = wakeTime,
|
||||
duration = duration,
|
||||
quality = quality,
|
||||
notes = notes
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun calculateSleepDuration(bedTime: String, wakeTime: String): Float {
|
||||
// TODO: Реализовать правильный расчет продолжительности сна
|
||||
return 8.0f
|
||||
}
|
||||
|
||||
// =================
|
||||
// МЕНСТРУАЛЬНЫЙ ЦИКЛ
|
||||
// =================
|
||||
|
||||
suspend fun addPeriod(startDate: LocalDate, endDate: LocalDate?, flow: String, symptoms: List<String>, mood: String) {
|
||||
suspend fun addPeriod(startDate: LocalDate, endDate: LocalDate?, flow: String, symptoms: List<String>) {
|
||||
val period = CyclePeriodEntity(
|
||||
startDate = startDate,
|
||||
endDate = endDate,
|
||||
flow = flow,
|
||||
symptoms = symptoms,
|
||||
mood = mood
|
||||
symptoms = symptoms
|
||||
)
|
||||
cyclePeriodDao.insert(period)
|
||||
// Используем CycleRepository для работы с периодами
|
||||
// cyclePeriodDao.insertPeriod(period)
|
||||
// TODO: Добавить интеграцию с CycleRepository
|
||||
}
|
||||
|
||||
suspend fun updatePeriod(periodId: Long, endDate: LocalDate?, flow: String, symptoms: List<String>, mood: String) {
|
||||
val periods = cyclePeriodDao.getAll()
|
||||
val existingPeriod = periods.firstOrNull { it.id == periodId }
|
||||
if (existingPeriod != null) {
|
||||
val updatedPeriod = existingPeriod.copy(
|
||||
endDate = endDate,
|
||||
flow = flow,
|
||||
symptoms = symptoms,
|
||||
mood = mood
|
||||
)
|
||||
cyclePeriodDao.update(updatedPeriod)
|
||||
}
|
||||
suspend fun updatePeriod(periodId: Long, endDate: LocalDate?, flow: String, symptoms: List<String>) {
|
||||
// TODO: Реализовать через CycleRepository
|
||||
// val existingPeriod = cyclePeriodDao.getPeriodById(periodId)
|
||||
// existingPeriod?.let {
|
||||
// val updatedPeriod = it.copy(
|
||||
// endDate = endDate,
|
||||
// flow = flow,
|
||||
// symptoms = symptoms
|
||||
// )
|
||||
// cyclePeriodDao.updatePeriod(updatedPeriod)
|
||||
// }
|
||||
}
|
||||
|
||||
suspend fun getRecentPeriods(): List<CyclePeriodEntity> {
|
||||
return cyclePeriodDao.getAll().take(6)
|
||||
fun getPeriods(): Flow<List<CyclePeriodEntity>> {
|
||||
// TODO: Реализовать через CycleRepository
|
||||
return flowOf(emptyList())
|
||||
// return cyclePeriodDao.getAllPeriods()
|
||||
}
|
||||
|
||||
suspend fun deletePeriod(periodId: Long) {
|
||||
// TODO: Реализовать через CycleRepository
|
||||
// cyclePeriodDao.deletePeriodById(periodId)
|
||||
}
|
||||
|
||||
// =================
|
||||
// НАСТРОЙКИ
|
||||
// =================
|
||||
|
||||
fun getSettings(): Flow<AppSettings> {
|
||||
fun getAppSettings(): Flow<AppSettings> {
|
||||
// TODO: Реализовать получение настроек из БД
|
||||
return flowOf(
|
||||
AppSettings(
|
||||
isWaterReminderEnabled = true,
|
||||
isCycleReminderEnabled = true,
|
||||
isSleepReminderEnabled = true,
|
||||
cycleLength = 28,
|
||||
periodLength = 5,
|
||||
waterGoal = 2.5f,
|
||||
stepsGoal = 10000,
|
||||
sleepGoal = 8.0f,
|
||||
isDarkTheme = false
|
||||
notificationsEnabled = true,
|
||||
darkModeEnabled = false
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun updateWaterReminderSetting(enabled: Boolean) {
|
||||
// TODO: Реализовать обновление настройки напоминаний о воде
|
||||
}
|
||||
|
||||
suspend fun updateCycleReminderSetting(enabled: Boolean) {
|
||||
// TODO: Реализовать обновление настройки напоминаний о цикле
|
||||
}
|
||||
|
||||
suspend fun updateSleepReminderSetting(enabled: Boolean) {
|
||||
// TODO: Реализовать обновление настройки напоминаний о сне
|
||||
}
|
||||
|
||||
suspend fun updateCycleLength(length: Int) {
|
||||
// TODO: Реализовать обновление длины цикла
|
||||
}
|
||||
|
||||
suspend fun updatePeriodLength(length: Int) {
|
||||
// TODO: Реализовать обновление длины менструации
|
||||
}
|
||||
|
||||
suspend fun updateStepsGoal(goal: Int) {
|
||||
// TODO: Реализовать обновление цели по шагам
|
||||
}
|
||||
|
||||
suspend fun updateSleepGoal(goal: Float) {
|
||||
// TODO: Реализовать обновление цели по сну
|
||||
}
|
||||
|
||||
suspend fun updateThemeSetting(isDark: Boolean) {
|
||||
// TODO: Реализовать обновление темы
|
||||
suspend fun updateAppSettings(settings: AppSettings) {
|
||||
// TODO: Реализовать обновление настроек
|
||||
}
|
||||
|
||||
// =================
|
||||
// УПРАВЛЕНИЕ ДАННЫМИ
|
||||
// АНАЛИТИКА И ОТЧЕТЫ
|
||||
// =================
|
||||
|
||||
suspend fun exportUserData() {
|
||||
// TODO: Реализовать экспорт данных пользователя
|
||||
}
|
||||
|
||||
suspend fun importUserData() {
|
||||
// TODO: Реализовать импорт данных пользователя
|
||||
}
|
||||
|
||||
suspend fun clearAllUserData() {
|
||||
// TODO: Реализовать очистку всех данных пользователя
|
||||
}
|
||||
|
||||
// =================
|
||||
// ЗДОРОВЬЕ
|
||||
// =================
|
||||
|
||||
fun getTodayHealthData(): kotlinx.coroutines.flow.Flow<HealthRecordEntity?> {
|
||||
val today = LocalDate.now()
|
||||
return healthRecordDao.getByDateFlow(today)
|
||||
}
|
||||
|
||||
fun getAllHealthRecords(): kotlinx.coroutines.flow.Flow<List<HealthRecordEntity>> {
|
||||
return healthRecordDao.getAllFlow()
|
||||
}
|
||||
|
||||
fun getRecentHealthRecords(limit: Int = 10): kotlinx.coroutines.flow.Flow<List<HealthRecordEntity>> {
|
||||
return healthRecordDao.getAllFlow().map { records: List<HealthRecordEntity> ->
|
||||
records.sortedByDescending { r -> r.date }.take(limit)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveHealthRecord(record: HealthRecordEntity) {
|
||||
if (record.id != 0L) {
|
||||
healthRecordDao.update(record)
|
||||
} else {
|
||||
healthRecordDao.insert(record)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deleteHealthRecord(recordId: Long) {
|
||||
val record = healthRecordDao.getAll().firstOrNull { it.id == recordId }
|
||||
if (record != null) {
|
||||
healthRecordDao.delete(record)
|
||||
}
|
||||
}
|
||||
|
||||
// =================
|
||||
// DASHBOARD
|
||||
// =================
|
||||
|
||||
fun getDashboardData(): Flow<DashboardData> {
|
||||
// TODO: Реализовать получение данных для главного экрана
|
||||
return flowOf(
|
||||
DashboardData(
|
||||
user = User(),
|
||||
todayHealth = null,
|
||||
sleepData = null,
|
||||
cycleData = null,
|
||||
recentWorkouts = emptyList()
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
// =================
|
||||
// УСТАРЕВШИЕ МЕТОДЫ (для совместимости)
|
||||
// =================
|
||||
|
||||
suspend fun addWater(amount: Int, date: LocalDate = LocalDate.now()) {
|
||||
waterLogDao.insertWaterLog(
|
||||
WaterLogEntity(date = date, amount = amount)
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun getTodayWaterIntake(date: LocalDate = LocalDate.now()): Int {
|
||||
return waterLogDao.getTotalWaterForDate(date) ?: 0
|
||||
}
|
||||
|
||||
fun getWaterLogsForDate(date: LocalDate): Flow<List<WaterLogEntity>> {
|
||||
fun getDashboardData(date: LocalDate): Flow<DashboardData> {
|
||||
return flow {
|
||||
emit(waterLogDao.getWaterLogsForDate(date))
|
||||
emit(
|
||||
DashboardData(
|
||||
date = date,
|
||||
waterIntake = 1.2f,
|
||||
steps = 6500,
|
||||
calories = 1850,
|
||||
workouts = 1,
|
||||
cycleDay = null
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Вспомогательные data классы
|
||||
data class DashboardData(
|
||||
val user: User,
|
||||
val todayHealth: HealthRecord?,
|
||||
val sleepData: SleepLogEntity?,
|
||||
val cycleData: CyclePeriodEntity?,
|
||||
val recentWorkouts: List<WorkoutSession>
|
||||
)
|
||||
|
||||
data class HealthRecord(
|
||||
val id: Long = 0,
|
||||
val date: LocalDate,
|
||||
val bloodPressureSystolic: Int = 0,
|
||||
val bloodPressureDiastolic: Int = 0,
|
||||
val heartRate: Int = 0,
|
||||
val weight: Float = 0f,
|
||||
val mood: String = "neutral", // Добавляем поле настроения
|
||||
val energyLevel: Int = 5, // Добавляем уровень энергии (1-10)
|
||||
val stressLevel: Int = 5, // Добавляем уровень стресса (1-10)
|
||||
val notes: String = ""
|
||||
val waterIntake: Float,
|
||||
val steps: Int,
|
||||
val calories: Int,
|
||||
val workouts: Int,
|
||||
val cycleDay: Int?
|
||||
)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package kr.smartsoltech.wellshe.data.storage
|
||||
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import java.util.Date
|
||||
|
||||
/**
|
||||
* Класс для управления токенами авторизации
|
||||
*/
|
||||
@Singleton
|
||||
class TokenManager @Inject constructor() {
|
||||
|
||||
// Токен авторизации
|
||||
private var accessToken: String? = null
|
||||
|
||||
// Токен обновления
|
||||
private var refreshToken: String? = null
|
||||
|
||||
// Время истечения токена
|
||||
private var expiresAt: Long = 0
|
||||
|
||||
// Тип токена (например, "Bearer")
|
||||
private var tokenType: String? = null
|
||||
|
||||
/**
|
||||
* Сохранить токены авторизации
|
||||
*/
|
||||
fun saveTokens(accessToken: String, refreshToken: String, expiresIn: Int) {
|
||||
this.accessToken = accessToken
|
||||
this.refreshToken = refreshToken
|
||||
this.expiresAt = Date().time + (expiresIn * 1000)
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновить только токен доступа
|
||||
*/
|
||||
fun updateAccessToken(accessToken: String, expiresIn: Int) {
|
||||
this.accessToken = accessToken
|
||||
this.expiresAt = Date().time + (expiresIn * 1000)
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранить токен доступа
|
||||
*/
|
||||
fun saveAccessToken(accessToken: String) {
|
||||
this.accessToken = accessToken
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранить тип токена
|
||||
*/
|
||||
fun saveTokenType(tokenType: String) {
|
||||
this.tokenType = tokenType
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить тип токена
|
||||
*/
|
||||
fun getTokenType(): String? {
|
||||
return tokenType
|
||||
}
|
||||
|
||||
/**
|
||||
* Очистить все токены
|
||||
*/
|
||||
fun clearTokens() {
|
||||
accessToken = null
|
||||
refreshToken = null
|
||||
tokenType = null
|
||||
expiresAt = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить токен авторизации
|
||||
*/
|
||||
fun getAccessToken(): String? {
|
||||
return accessToken
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить токен обновления
|
||||
*/
|
||||
fun getRefreshToken(): String? {
|
||||
return refreshToken
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверить, истек ли токен авторизации
|
||||
*/
|
||||
fun isAccessTokenExpired(): Boolean {
|
||||
return Date().time > expiresAt
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранить токен авторизации (для обратной совместимости)
|
||||
*/
|
||||
fun saveAuthToken(token: String) {
|
||||
accessToken = token
|
||||
expiresAt = Date().time + (3600 * 1000) // По умолчанию 1 час
|
||||
}
|
||||
}
|
||||
@@ -8,21 +8,8 @@ import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import kr.smartsoltech.wellshe.data.AppDatabase
|
||||
import kr.smartsoltech.wellshe.data.datastore.DataStoreManager
|
||||
import kr.smartsoltech.wellshe.data.dao.*
|
||||
import kr.smartsoltech.wellshe.data.repo.DrinkLogger
|
||||
import kr.smartsoltech.wellshe.data.repo.WeightRepository
|
||||
import kr.smartsoltech.wellshe.data.repo.WorkoutService
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_1_2
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_2_3
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_3_4
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_4_5
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_5_6
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_6_7
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_7_8
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_8_9
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_9_10
|
||||
import kr.smartsoltech.wellshe.data.MIGRATION_10_11
|
||||
import kr.smartsoltech.wellshe.data.repo.*
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@@ -31,34 +18,19 @@ object AppModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDataStoreManager(@ApplicationContext context: Context): DataStoreManager =
|
||||
DataStoreManager(context)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
||||
Room.databaseBuilder(
|
||||
fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase {
|
||||
return Room.databaseBuilder(
|
||||
context,
|
||||
AppDatabase::class.java,
|
||||
"well_she_db"
|
||||
)
|
||||
.addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11)
|
||||
.fallbackToDestructiveMigration()
|
||||
"wellshe_database"
|
||||
).fallbackToDestructiveMigration()
|
||||
.build()
|
||||
}
|
||||
|
||||
// DAO providers
|
||||
// DAO Providers
|
||||
@Provides
|
||||
fun provideWaterLogDao(database: AppDatabase): WaterLogDao = database.waterLogDao()
|
||||
|
||||
@Provides
|
||||
fun provideCyclePeriodDao(database: AppDatabase): CyclePeriodDao = database.cyclePeriodDao()
|
||||
|
||||
@Provides
|
||||
fun provideSleepLogDao(database: AppDatabase): SleepLogDao = database.sleepLogDao()
|
||||
|
||||
@Provides
|
||||
fun provideHealthRecordDao(database: AppDatabase): HealthRecordDao = database.healthRecordDao()
|
||||
|
||||
@Provides
|
||||
fun provideWorkoutDao(database: AppDatabase): WorkoutDao = database.workoutDao()
|
||||
|
||||
@@ -71,7 +43,12 @@ object AppModule {
|
||||
@Provides
|
||||
fun provideUserProfileDao(database: AppDatabase): UserProfileDao = database.userProfileDao()
|
||||
|
||||
// DAO для BodyRepo
|
||||
@Provides
|
||||
fun provideCyclePeriodDao(database: AppDatabase): CyclePeriodDao = database.cyclePeriodDao()
|
||||
|
||||
@Provides
|
||||
fun provideHealthRecordDao(database: AppDatabase): HealthRecordDao = database.healthRecordDao()
|
||||
|
||||
@Provides
|
||||
fun provideBeverageLogDao(database: AppDatabase): BeverageLogDao = database.beverageLogDao()
|
||||
|
||||
@@ -102,7 +79,28 @@ object AppModule {
|
||||
@Provides
|
||||
fun provideExerciseFormulaVarDao(database: AppDatabase): ExerciseFormulaVarDao = database.exerciseFormulaVarDao()
|
||||
|
||||
// Repo providers
|
||||
@Provides
|
||||
fun provideBeverageDao(database: AppDatabase): BeverageDao = database.beverageDao()
|
||||
|
||||
@Provides
|
||||
fun provideBeverageServingDao(database: AppDatabase): BeverageServingDao = database.beverageServingDao()
|
||||
|
||||
@Provides
|
||||
fun provideExerciseParamDao(database: AppDatabase): ExerciseParamDao = database.exerciseParamDao()
|
||||
|
||||
@Provides
|
||||
fun provideNutrientDao(database: AppDatabase): NutrientDao = database.nutrientDao()
|
||||
|
||||
@Provides
|
||||
fun provideCatalogVersionDao(database: AppDatabase): CatalogVersionDao = database.catalogVersionDao()
|
||||
|
||||
// Repository/Service Providers
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWeightRepository(weightLogDao: WeightLogDao): WeightRepository {
|
||||
return WeightRepository(weightLogDao)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDrinkLogger(
|
||||
@@ -110,12 +108,9 @@ object AppModule {
|
||||
beverageLogDao: BeverageLogDao,
|
||||
beverageLogNutrientDao: BeverageLogNutrientDao,
|
||||
servingNutrientDao: BeverageServingNutrientDao
|
||||
): DrinkLogger = DrinkLogger(waterLogDao, beverageLogDao, beverageLogNutrientDao, servingNutrientDao)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWeightRepository(weightLogDao: WeightLogDao): WeightRepository =
|
||||
WeightRepository(weightLogDao)
|
||||
): DrinkLogger {
|
||||
return DrinkLogger(waterLogDao, beverageLogDao, beverageLogNutrientDao, servingNutrientDao)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@@ -127,23 +122,27 @@ object AppModule {
|
||||
formulaDao: ExerciseFormulaDao,
|
||||
formulaVarDao: ExerciseFormulaVarDao,
|
||||
exerciseDao: ExerciseDao
|
||||
): WorkoutService = WorkoutService(sessionDao, paramDao, eventDao, weightRepo, formulaDao, formulaVarDao, exerciseDao)
|
||||
): WorkoutService {
|
||||
return WorkoutService(sessionDao, paramDao, eventDao, weightRepo, formulaDao, formulaVarDao, exerciseDao)
|
||||
}
|
||||
|
||||
// Repository
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWellSheRepository(
|
||||
waterLogDao: WaterLogDao,
|
||||
cyclePeriodDao: CyclePeriodDao,
|
||||
sleepLogDao: SleepLogDao,
|
||||
healthRecordDao: HealthRecordDao,
|
||||
workoutDao: WorkoutDao,
|
||||
calorieDao: CalorieDao,
|
||||
stepsDao: StepsDao,
|
||||
userProfileDao: UserProfileDao
|
||||
): kr.smartsoltech.wellshe.data.repository.WellSheRepository =
|
||||
kr.smartsoltech.wellshe.data.repository.WellSheRepository(
|
||||
waterLogDao, cyclePeriodDao, sleepLogDao, healthRecordDao,
|
||||
workoutDao, calorieDao, stepsDao, userProfileDao
|
||||
)
|
||||
fun provideBeverageCatalogRepository(
|
||||
beverageDao: BeverageDao,
|
||||
servingDao: BeverageServingDao,
|
||||
servingNutrientDao: BeverageServingNutrientDao
|
||||
): BeverageCatalogRepository {
|
||||
return BeverageCatalogRepository(beverageDao, servingDao, servingNutrientDao)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideExerciseCatalogRepository(
|
||||
exerciseDao: ExerciseDao,
|
||||
paramDao: ExerciseParamDao,
|
||||
formulaDao: ExerciseFormulaDao
|
||||
): ExerciseCatalogRepository {
|
||||
return ExerciseCatalogRepository(exerciseDao, paramDao, formulaDao)
|
||||
}
|
||||
}
|
||||
|
||||
88
app/src/main/java/kr/smartsoltech/wellshe/di/AuthModule.kt
Normal file
88
app/src/main/java/kr/smartsoltech/wellshe/di/AuthModule.kt
Normal file
@@ -0,0 +1,88 @@
|
||||
package kr.smartsoltech.wellshe.di
|
||||
|
||||
import android.content.Context
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import kr.smartsoltech.wellshe.data.local.AuthTokenRepository
|
||||
import kr.smartsoltech.wellshe.data.network.AuthService
|
||||
import kr.smartsoltech.wellshe.data.network.RetrofitFactory
|
||||
import kr.smartsoltech.wellshe.data.network.RetrofitProvider
|
||||
import kr.smartsoltech.wellshe.data.preferences.ServerPreferences
|
||||
import kr.smartsoltech.wellshe.data.repository.AuthRepository
|
||||
import kr.smartsoltech.wellshe.data.storage.TokenManager
|
||||
import kr.smartsoltech.wellshe.domain.auth.GetUserProfileUseCase
|
||||
import kr.smartsoltech.wellshe.domain.auth.LoginUseCase
|
||||
import kr.smartsoltech.wellshe.domain.auth.LogoutUseCase
|
||||
import kr.smartsoltech.wellshe.domain.auth.RegisterUseCase
|
||||
import kr.smartsoltech.wellshe.domain.auth.RefreshTokenUseCase
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object AuthModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAuthTokenRepository(@ApplicationContext context: Context): AuthTokenRepository {
|
||||
return AuthTokenRepository(context)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideTokenManager(): TokenManager {
|
||||
return TokenManager()
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideRetrofitProvider(
|
||||
serverPreferences: ServerPreferences,
|
||||
retrofitFactory: RetrofitFactory
|
||||
): RetrofitProvider {
|
||||
return RetrofitProvider(serverPreferences, retrofitFactory)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideAuthService(retrofitProvider: RetrofitProvider): AuthService {
|
||||
// Каждый раз получаем актуальный Retrofit, который может иметь новый baseUrl
|
||||
return retrofitProvider.getRetrofit().create(AuthService::class.java)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAuthRepository(
|
||||
authService: AuthService,
|
||||
authTokenRepository: AuthTokenRepository,
|
||||
tokenManager: TokenManager
|
||||
): AuthRepository {
|
||||
return AuthRepository(authService, authTokenRepository, tokenManager)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideLoginUseCase(authRepository: AuthRepository, tokenManager: TokenManager): LoginUseCase {
|
||||
return LoginUseCase(authRepository, tokenManager)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideRegisterUseCase(authRepository: AuthRepository): RegisterUseCase {
|
||||
return RegisterUseCase(authRepository)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideLogoutUseCase(authRepository: AuthRepository, tokenManager: TokenManager): LogoutUseCase {
|
||||
return LogoutUseCase(authRepository, tokenManager)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideGetUserProfileUseCase(authRepository: AuthRepository, tokenManager: TokenManager): GetUserProfileUseCase {
|
||||
return GetUserProfileUseCase(authRepository, tokenManager)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideRefreshTokenUseCase(authRepository: AuthRepository, tokenManager: TokenManager): RefreshTokenUseCase {
|
||||
return RefreshTokenUseCase(authRepository, tokenManager)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package kr.smartsoltech.wellshe.di
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import kr.smartsoltech.wellshe.data.local.AuthTokenRepository
|
||||
import kr.smartsoltech.wellshe.data.network.ApiClient
|
||||
import kr.smartsoltech.wellshe.data.network.AuthInterceptor
|
||||
import kr.smartsoltech.wellshe.data.network.RetrofitFactory
|
||||
import kr.smartsoltech.wellshe.data.preferences.ServerPreferences
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object NetworkModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideGson(): Gson {
|
||||
return GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAuthInterceptor(authTokenRepository: AuthTokenRepository): AuthInterceptor {
|
||||
return AuthInterceptor(authTokenRepository)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideRetrofitFactory(
|
||||
gson: Gson,
|
||||
authTokenRepository: AuthTokenRepository
|
||||
): RetrofitFactory {
|
||||
return RetrofitFactory(gson, authTokenRepository)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideApiClient(serverPreferences: ServerPreferences): ApiClient {
|
||||
return ApiClient(serverPreferences)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package kr.smartsoltech.wellshe.di
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
/**
|
||||
* Фабрика для создания ViewModel с внедрением зависимостей через Hilt
|
||||
*/
|
||||
class ViewModelFactory @Inject constructor(
|
||||
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
|
||||
) : ViewModelProvider.Factory {
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
||||
val creator = creators[modelClass] ?: creators.entries.firstOrNull {
|
||||
modelClass.isAssignableFrom(it.key)
|
||||
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
|
||||
|
||||
return try {
|
||||
creator.get() as T
|
||||
} catch (e: Exception) {
|
||||
throw RuntimeException(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package kr.smartsoltech.wellshe.domain.analytics
|
||||
|
||||
import kr.smartsoltech.wellshe.data.entity.SleepLogEntity
|
||||
|
||||
object SleepAnalytics {
|
||||
/**
|
||||
* Расчёт долга сна и недельного тренда
|
||||
*/
|
||||
fun sleepDebt(logs: List<SleepLogEntity>, targetHours: Int = 8): Int {
|
||||
val total = logs.sumOf { it.duration.toDouble() }
|
||||
val expected = logs.size * targetHours
|
||||
return (expected - total).toInt()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package kr.smartsoltech.wellshe.domain.auth
|
||||
|
||||
import kr.smartsoltech.wellshe.data.repository.AuthRepository
|
||||
import kr.smartsoltech.wellshe.data.storage.TokenManager
|
||||
import kr.smartsoltech.wellshe.model.auth.UserProfile
|
||||
import kr.smartsoltech.wellshe.util.Result
|
||||
|
||||
/**
|
||||
* Use case для регистрации нового пользователя
|
||||
*/
|
||||
class RegisterUseCase(private val authRepository: AuthRepository) {
|
||||
suspend operator fun invoke(
|
||||
email: String,
|
||||
username: String,
|
||||
password: String,
|
||||
firstName: String,
|
||||
lastName: String,
|
||||
phone: String
|
||||
): Result<Boolean> {
|
||||
val result = authRepository.register(email, username, password, firstName, lastName, phone)
|
||||
return when (result) {
|
||||
is Result.Success -> Result.Success(true)
|
||||
is Result.Error -> Result.Error(result.exception)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use case для авторизации пользователя
|
||||
*/
|
||||
class LoginUseCase(private val authRepository: AuthRepository, private val tokenManager: TokenManager) {
|
||||
suspend operator fun invoke(identifier: String, password: String, isEmail: Boolean): Result<Boolean> {
|
||||
val result = authRepository.login(identifier, password, isEmail)
|
||||
return when (result) {
|
||||
is Result.Success -> {
|
||||
val response = result.data
|
||||
tokenManager.saveTokens(response.accessToken, response.refreshToken, response.expiresIn)
|
||||
Result.Success(true)
|
||||
}
|
||||
is Result.Error -> Result.Error(result.exception)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use case для выхода пользователя из системы
|
||||
*/
|
||||
class LogoutUseCase(private val authRepository: AuthRepository, private val tokenManager: TokenManager) {
|
||||
suspend operator fun invoke(): Result<Boolean> {
|
||||
val accessToken = tokenManager.getAccessToken()
|
||||
if (accessToken == null) {
|
||||
tokenManager.clearTokens()
|
||||
return Result.Success(true)
|
||||
}
|
||||
|
||||
val result = authRepository.logout(accessToken)
|
||||
tokenManager.clearTokens() // Очищаем токены даже при ошибке запроса
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use case для получения профиля пользователя
|
||||
*/
|
||||
class GetUserProfileUseCase(private val authRepository: AuthRepository, private val tokenManager: TokenManager) {
|
||||
suspend operator fun invoke(): Result<UserProfile> {
|
||||
val accessToken = tokenManager.getAccessToken() ?: return Result.Error(Exception("Пользователь не авторизован"))
|
||||
|
||||
return if (tokenManager.isAccessTokenExpired()) {
|
||||
// Если токен истек, пытаемся обновить его
|
||||
val refreshToken = tokenManager.getRefreshToken() ?: return Result.Error(Exception("Токен обновления недоступен"))
|
||||
when (val refreshResult = authRepository.refreshToken(refreshToken)) {
|
||||
is Result.Success -> {
|
||||
tokenManager.updateAccessToken(refreshResult.data.accessToken, refreshResult.data.expiresIn)
|
||||
// Получаем профиль с обновленным токеном
|
||||
authRepository.getUserProfile(refreshResult.data.accessToken)
|
||||
}
|
||||
is Result.Error -> Result.Error(refreshResult.exception)
|
||||
}
|
||||
} else {
|
||||
// Получаем профиль с текущим токеном
|
||||
authRepository.getUserProfile(accessToken)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use case для обновления токена доступа
|
||||
*/
|
||||
class RefreshTokenUseCase(private val authRepository: AuthRepository, private val tokenManager: TokenManager) {
|
||||
suspend operator fun invoke(): Result<Boolean> {
|
||||
val refreshToken = tokenManager.getRefreshToken() ?: return Result.Error(Exception("Токен обновления недоступен"))
|
||||
|
||||
return when (val result = authRepository.refreshToken(refreshToken)) {
|
||||
is Result.Success -> {
|
||||
tokenManager.updateAccessToken(result.data.accessToken, result.data.expiresIn)
|
||||
Result.Success(true)
|
||||
}
|
||||
is Result.Error -> {
|
||||
// Если ошибка обновления, то считаем, что пользователь не авторизован
|
||||
tokenManager.clearTokens()
|
||||
Result.Error(result.exception)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package kr.smartsoltech.wellshe.domain.emergency
|
||||
|
||||
import kr.smartsoltech.wellshe.data.repository.EmergencyRepository
|
||||
import kr.smartsoltech.wellshe.data.storage.TokenManager
|
||||
import kr.smartsoltech.wellshe.model.emergency.*
|
||||
import kr.smartsoltech.wellshe.util.Result
|
||||
|
||||
/**
|
||||
* Use case для создания экстренного оповещения
|
||||
*/
|
||||
class CreateEmergencyAlertUseCase(
|
||||
private val emergencyRepository: EmergencyRepository,
|
||||
private val tokenManager: TokenManager
|
||||
) {
|
||||
suspend operator fun invoke(
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
message: String? = null,
|
||||
batteryLevel: Int? = null,
|
||||
contactIds: List<String>? = null
|
||||
): Result<EmergencyAlertResponse> {
|
||||
val accessToken = tokenManager.getAccessToken() ?: return Result.Error(Exception("Пользователь не авторизован"))
|
||||
|
||||
return emergencyRepository.createAlert(
|
||||
accessToken, latitude, longitude, message, batteryLevel, contactIds
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use case для получения статуса экстренного оповещения
|
||||
*/
|
||||
class GetAlertStatusUseCase(
|
||||
private val emergencyRepository: EmergencyRepository,
|
||||
private val tokenManager: TokenManager
|
||||
) {
|
||||
suspend operator fun invoke(alertId: String): Result<EmergencyAlertStatus> {
|
||||
val accessToken = tokenManager.getAccessToken() ?: return Result.Error(Exception("Пользователь не авторизован"))
|
||||
|
||||
return emergencyRepository.getAlertStatus(accessToken, alertId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use case для обновления местоположения при активном оповещении
|
||||
*/
|
||||
class UpdateLocationUseCase(
|
||||
private val emergencyRepository: EmergencyRepository,
|
||||
private val tokenManager: TokenManager
|
||||
) {
|
||||
suspend operator fun invoke(
|
||||
alertId: String,
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
accuracy: Float? = null,
|
||||
batteryLevel: Int? = null
|
||||
): Result<LocationUpdateResponse> {
|
||||
val accessToken = tokenManager.getAccessToken() ?: return Result.Error(Exception("Пользователь не авторизован"))
|
||||
|
||||
return emergencyRepository.updateLocation(
|
||||
accessToken, alertId, latitude, longitude, accuracy, batteryLevel
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use case для отмены экстренного оповещения
|
||||
*/
|
||||
class CancelAlertUseCase(
|
||||
private val emergencyRepository: EmergencyRepository,
|
||||
private val tokenManager: TokenManager
|
||||
) {
|
||||
suspend operator fun invoke(
|
||||
alertId: String,
|
||||
reason: String? = null,
|
||||
details: String? = null
|
||||
): Result<AlertCancelResponse> {
|
||||
val accessToken = tokenManager.getAccessToken() ?: return Result.Error(Exception("Пользователь не авторизован"))
|
||||
|
||||
return emergencyRepository.cancelAlert(accessToken, alertId, reason, details)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,6 @@
|
||||
package kr.smartsoltech.wellshe.domain.model
|
||||
|
||||
data class AppSettings(
|
||||
val id: Long = 0,
|
||||
val isWaterReminderEnabled: Boolean = true,
|
||||
val waterReminderInterval: Int = 2, // часы
|
||||
val isCycleReminderEnabled: Boolean = true,
|
||||
val isSleepReminderEnabled: Boolean = true,
|
||||
val sleepReminderTime: String = "22:00",
|
||||
val wakeUpReminderTime: String = "07:00",
|
||||
val cycleLength: Int = 28,
|
||||
val periodLength: Int = 5,
|
||||
val waterGoal: Float = 2.5f,
|
||||
val stepsGoal: Int = 10000,
|
||||
val sleepGoal: Float = 8.0f,
|
||||
val isDarkTheme: Boolean = false,
|
||||
val language: String = "ru",
|
||||
val isFirstLaunch: Boolean = true
|
||||
val notificationsEnabled: Boolean = true,
|
||||
val darkModeEnabled: Boolean = false
|
||||
)
|
||||
|
||||
@@ -13,7 +13,6 @@ data class User(
|
||||
val dailyWaterGoal: Float = 2.5f, // в литрах
|
||||
val dailyStepsGoal: Int = 10000,
|
||||
val dailyCaloriesGoal: Int = 2000,
|
||||
val dailySleepGoal: Float = 8.0f, // в часах
|
||||
val cycleLength: Int = 28, // дней
|
||||
val periodLength: Int = 5, // дней
|
||||
val lastPeriodStart: LocalDate? = null,
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.api
|
||||
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.*
|
||||
|
||||
// ========== API МОДЕЛИ ДАННЫХ ==========
|
||||
|
||||
data class CreateEmergencyRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val alert_type: String = "general",
|
||||
val message: String? = null,
|
||||
val address: String? = null,
|
||||
val contact_emergency_services: Boolean = true,
|
||||
val notify_emergency_contacts: Boolean = true,
|
||||
val battery_level: Int? = null
|
||||
)
|
||||
|
||||
data class EmergencyEventResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val status: String,
|
||||
val is_resolved: Boolean,
|
||||
val created_at: String,
|
||||
val updated_at: String?,
|
||||
val resolved_at: String?,
|
||||
val user: ApiUserInfo?
|
||||
)
|
||||
|
||||
data class NearbyEventsResponse(
|
||||
val events: List<NearbyEmergencyEvent>,
|
||||
val total: Int,
|
||||
val radius_km: Double
|
||||
)
|
||||
|
||||
data class NearbyEmergencyEvent(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val distance_km: Double,
|
||||
val created_at: String,
|
||||
val user: ApiUserInfo?
|
||||
)
|
||||
|
||||
data class EmergencyEventDetailResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val status: String,
|
||||
val is_resolved: Boolean,
|
||||
val created_at: String,
|
||||
val updated_at: String?,
|
||||
val resolved_at: String?,
|
||||
val user: ApiUserInfo,
|
||||
val responses: List<EventResponse>
|
||||
)
|
||||
|
||||
data class EventResponseRequest(
|
||||
val response_type: String,
|
||||
val message: String? = null,
|
||||
val eta_minutes: Int? = null,
|
||||
val location_latitude: Double? = null,
|
||||
val location_longitude: Double? = null
|
||||
)
|
||||
|
||||
data class EventResponseResponse(
|
||||
val id: Int,
|
||||
val event_id: Int,
|
||||
val user_id: Int,
|
||||
val response_type: String,
|
||||
val message: String?,
|
||||
val eta_minutes: Int?,
|
||||
val location_latitude: Double?,
|
||||
val location_longitude: Double?,
|
||||
val created_at: String,
|
||||
val user: ApiUserInfo
|
||||
)
|
||||
|
||||
data class EventHistoryResponse(
|
||||
val events: List<EmergencyEventResponse>,
|
||||
val total: Int,
|
||||
val page: Int,
|
||||
val per_page: Int
|
||||
)
|
||||
|
||||
data class NearbyUsersResponse(
|
||||
val users: List<ApiUserInfo>,
|
||||
val total: Int,
|
||||
val radius_km: Double
|
||||
)
|
||||
|
||||
data class EventsStatsResponse(
|
||||
val total_events: Int,
|
||||
val active_events: Int,
|
||||
val resolved_events: Int,
|
||||
val my_events: Int,
|
||||
val my_responses: Int,
|
||||
val average_response_time_minutes: Double?
|
||||
)
|
||||
|
||||
data class ApiUserInfo(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val email: String?,
|
||||
val phone: String?,
|
||||
val profile_image_url: String?
|
||||
)
|
||||
|
||||
data class EventResponse(
|
||||
val id: Int,
|
||||
val user_id: Int,
|
||||
val response_type: String,
|
||||
val message: String?,
|
||||
val eta_minutes: Int?,
|
||||
val created_at: String,
|
||||
val user: ApiUserInfo
|
||||
)
|
||||
|
||||
data class CreateReportRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val report_type: String,
|
||||
val description: String,
|
||||
val address: String? = null,
|
||||
val is_anonymous: Boolean = false,
|
||||
val severity: Int = 3
|
||||
)
|
||||
|
||||
data class ReportResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int?,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val report_type: String,
|
||||
val description: String,
|
||||
val is_anonymous: Boolean,
|
||||
val severity: Int,
|
||||
val status: String = "pending",
|
||||
val created_at: String
|
||||
)
|
||||
|
||||
data class CreateSafetyCheckRequest(
|
||||
val message: String? = null,
|
||||
val location_latitude: Double? = null,
|
||||
val location_longitude: Double? = null
|
||||
)
|
||||
|
||||
data class SafetyCheckResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val message: String?,
|
||||
val location_latitude: Double?,
|
||||
val location_longitude: Double?,
|
||||
val created_at: String
|
||||
)
|
||||
|
||||
data class CreateAlertRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val alert_type: String = "general",
|
||||
val message: String? = null,
|
||||
val address: String? = null,
|
||||
val contact_emergency_services: Boolean = true,
|
||||
val notify_emergency_contacts: Boolean = true
|
||||
)
|
||||
|
||||
data class UpdateAlertRequest(
|
||||
val message: String? = null,
|
||||
val is_resolved: Boolean? = null
|
||||
)
|
||||
|
||||
data class WebSocketConnectionsResponse(
|
||||
val total_connections: Int,
|
||||
val active_connections: Int,
|
||||
val connections: List<ConnectionInfo>
|
||||
)
|
||||
|
||||
data class ConnectionInfo(
|
||||
val user_id: Int,
|
||||
val connected_at: String,
|
||||
val last_ping: String?
|
||||
)
|
||||
|
||||
data class UserWebSocketInfoResponse(
|
||||
val user_id: Int,
|
||||
val is_connected: Boolean,
|
||||
val connected_at: String?,
|
||||
val last_ping: String?
|
||||
)
|
||||
|
||||
data class WebSocketPingResponse(
|
||||
val total_pinged: Int,
|
||||
val responses: Int,
|
||||
val disconnected: Int
|
||||
)
|
||||
|
||||
data class WebSocketStatsResponse(
|
||||
val total_connections: Int,
|
||||
val active_connections: Int,
|
||||
val total_messages_sent: Int,
|
||||
val uptime_seconds: Int
|
||||
)
|
||||
|
||||
data class BroadcastResponse(
|
||||
val message_id: String,
|
||||
val recipients: Int,
|
||||
val delivered: Int
|
||||
)
|
||||
|
||||
// ========== API ИНТЕРФЕЙС ==========
|
||||
|
||||
interface EmergencyApiService {
|
||||
|
||||
// Основные операции с alerts/events (соответствуют реальному API)
|
||||
@POST("api/v1/emergency/events")
|
||||
suspend fun createEmergencyEvent(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: CreateEmergencyRequest
|
||||
): Response<EmergencyEventResponse>
|
||||
|
||||
@GET("api/v1/emergency/events/nearby")
|
||||
suspend fun getNearbyEvents(
|
||||
@Header("Authorization") token: String,
|
||||
@Query("latitude") latitude: Double,
|
||||
@Query("longitude") longitude: Double,
|
||||
@Query("radius") radius: Double = 5.0
|
||||
): Response<NearbyEventsResponse>
|
||||
|
||||
@GET("api/v1/emergency/events/{eventId}")
|
||||
suspend fun getEventDetails(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("eventId") eventId: Int
|
||||
): Response<EmergencyEventDetailResponse>
|
||||
|
||||
@POST("api/v1/emergency/events/{eventId}/respond")
|
||||
suspend fun respondToEvent(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("eventId") eventId: Int,
|
||||
@Body response: EventResponseRequest
|
||||
): Response<EventResponseResponse>
|
||||
|
||||
@PUT("api/v1/emergency/events/{eventId}/resolve")
|
||||
suspend fun updateEventStatus(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("eventId") eventId: Int
|
||||
): Response<Unit>
|
||||
|
||||
@GET("api/v1/emergency/events/my")
|
||||
suspend fun getEventHistory(
|
||||
@Header("Authorization") token: String
|
||||
): Response<EventHistoryResponse>
|
||||
|
||||
@GET("api/v1/alerts/nearby")
|
||||
suspend fun getNearbyUsers(
|
||||
@Header("Authorization") token: String,
|
||||
@Query("latitude") latitude: Double,
|
||||
@Query("longitude") longitude: Double,
|
||||
@Query("radius_km") radiusKm: Double = 5.0
|
||||
): Response<NearbyUsersResponse>
|
||||
|
||||
@GET("api/v1/stats")
|
||||
suspend fun getEmergencyStats(
|
||||
@Header("Authorization") token: String
|
||||
): Response<EventsStatsResponse>
|
||||
|
||||
// ========== ДОПОЛНИТЕЛЬНЫЕ ЭНДПОИНТЫ ДЛЯ 100% ПОКРЫТИЯ ==========
|
||||
|
||||
// Reports API
|
||||
@POST("api/v1/report")
|
||||
suspend fun createEmergencyReport(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: CreateReportRequest
|
||||
): Response<ReportResponse>
|
||||
|
||||
@GET("api/v1/reports")
|
||||
suspend fun getEmergencyReports(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<ReportResponse>>
|
||||
|
||||
@GET("api/v1/emergency/reports")
|
||||
suspend fun getEmergencyReportsAdmin(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<EmergencyEventResponse>>
|
||||
|
||||
// Safety Check API
|
||||
@POST("api/v1/safety-check")
|
||||
suspend fun createSafetyCheck(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: CreateSafetyCheckRequest
|
||||
): Response<SafetyCheckResponse>
|
||||
|
||||
@GET("api/v1/safety-checks")
|
||||
suspend fun getSafetyChecks(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<SafetyCheckResponse>>
|
||||
|
||||
// Alert Management API
|
||||
@POST("api/v1/alert")
|
||||
suspend fun createAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: CreateAlertRequest
|
||||
): Response<EmergencyEventResponse>
|
||||
|
||||
@PUT("api/v1/alert/{alert_id}")
|
||||
suspend fun updateAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: Int,
|
||||
@Body request: UpdateAlertRequest
|
||||
): Response<EmergencyEventResponse>
|
||||
|
||||
@PUT("api/v1/alert/{alert_id}/resolve")
|
||||
suspend fun resolveAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: Int
|
||||
): Response<Unit>
|
||||
|
||||
@POST("api/v1/alert/{alert_id}/respond")
|
||||
suspend fun respondToAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: Int,
|
||||
@Body request: EventResponseRequest
|
||||
): Response<EventResponseResponse>
|
||||
|
||||
@GET("api/v1/alert/{alert_id}/responses")
|
||||
suspend fun getAlertResponses(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: Int
|
||||
): Response<List<EventResponseResponse>>
|
||||
|
||||
@GET("api/v1/alerts/my")
|
||||
suspend fun getMyAlerts(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<EmergencyEventResponse>>
|
||||
|
||||
@GET("api/v1/alerts/active")
|
||||
suspend fun getActiveAlerts(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<EmergencyEventResponse>>
|
||||
|
||||
// WebSocket Management API
|
||||
@GET("api/v1/websocket/connections")
|
||||
suspend fun getWebsocketConnections(
|
||||
@Header("Authorization") token: String
|
||||
): Response<WebSocketConnectionsResponse>
|
||||
|
||||
@GET("api/v1/websocket/connections/{user_id}")
|
||||
suspend fun getUserWebsocketInfo(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("user_id") userId: Int
|
||||
): Response<UserWebSocketInfoResponse>
|
||||
|
||||
@POST("api/v1/websocket/ping")
|
||||
suspend fun pingWebsocketConnections(
|
||||
@Header("Authorization") token: String
|
||||
): Response<WebSocketPingResponse>
|
||||
|
||||
@GET("api/v1/websocket/stats")
|
||||
suspend fun getWebsocketStats(
|
||||
@Header("Authorization") token: String
|
||||
): Response<WebSocketStatsResponse>
|
||||
|
||||
@POST("api/v1/websocket/broadcast")
|
||||
suspend fun broadcastTestMessage(
|
||||
@Header("Authorization") token: String,
|
||||
@Query("message") message: String
|
||||
): Response<BroadcastResponse>
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.api
|
||||
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.*
|
||||
|
||||
/**
|
||||
* API Service соответствующий реальному Emergency Service
|
||||
* Основан на OpenAPI спецификации http://localhost:8002/openapi.json
|
||||
*/
|
||||
interface RealEmergencyApiService {
|
||||
|
||||
// ========== ОСНОВНЫЕ ALERT ОПЕРАЦИИ ==========
|
||||
|
||||
@POST("api/v1/alert")
|
||||
suspend fun createAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: CreateAlertRequest
|
||||
): Response<AlertResponse>
|
||||
|
||||
@PUT("api/v1/alert/{alert_id}")
|
||||
suspend fun updateAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: Int,
|
||||
@Body request: UpdateAlertRequest
|
||||
): Response<AlertResponse>
|
||||
|
||||
@PUT("api/v1/alert/{alert_id}/resolve")
|
||||
suspend fun resolveAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: Int
|
||||
): Response<Unit>
|
||||
|
||||
// ========== ПОЛУЧЕНИЕ ALERTS ==========
|
||||
|
||||
@GET("api/v1/alerts/my")
|
||||
suspend fun getMyAlerts(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<AlertResponse>>
|
||||
|
||||
@GET("api/v1/alerts/active")
|
||||
suspend fun getActiveAlerts(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<AlertResponse>>
|
||||
|
||||
@GET("api/v1/alerts/nearby")
|
||||
suspend fun getNearbyAlerts(
|
||||
@Header("Authorization") token: String,
|
||||
@Query("latitude") latitude: Double,
|
||||
@Query("longitude") longitude: Double,
|
||||
@Query("radius_km") radiusKm: Double = 10.0
|
||||
): Response<List<NearbyAlertResponse>>
|
||||
|
||||
// ========== EMERGENCY EVENTS (Mobile Compatibility) ==========
|
||||
|
||||
@POST("api/v1/emergency/events")
|
||||
suspend fun createEmergencyEvent(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: CreateAlertRequest
|
||||
): Response<AlertResponse>
|
||||
|
||||
@GET("api/v1/emergency/events")
|
||||
suspend fun getEmergencyEvents(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<AlertResponse>>
|
||||
|
||||
@GET("api/v1/emergency/events/my")
|
||||
suspend fun getMyEmergencyEvents(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<AlertResponse>>
|
||||
|
||||
@GET("api/v1/emergency/events/nearby")
|
||||
suspend fun getNearbyEmergencyEvents(
|
||||
@Header("Authorization") token: String,
|
||||
@Query("latitude") latitude: Double,
|
||||
@Query("longitude") longitude: Double,
|
||||
@Query("radius") radius: Double = 5.0
|
||||
): Response<List<NearbyAlertResponse>>
|
||||
|
||||
@GET("api/v1/emergency/events/{event_id}")
|
||||
suspend fun getEmergencyEventDetails(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("event_id") eventId: Int
|
||||
): Response<EmergencyEventDetailsResponse>
|
||||
|
||||
@GET("api/v1/emergency/events/{event_id}/brief")
|
||||
suspend fun getEmergencyEventBrief(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("event_id") eventId: Int
|
||||
): Response<AlertResponse>
|
||||
|
||||
@PUT("api/v1/emergency/events/{event_id}/resolve")
|
||||
suspend fun resolveEmergencyEvent(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("event_id") eventId: Int
|
||||
): Response<Unit>
|
||||
|
||||
// ========== RESPONSES ==========
|
||||
|
||||
@POST("api/v1/alert/{alert_id}/respond")
|
||||
suspend fun respondToAlert(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: Int,
|
||||
@Body request: ResponseCreateRequest
|
||||
): Response<ResponseResponse>
|
||||
|
||||
@POST("api/v1/emergency/events/{event_id}/respond")
|
||||
suspend fun respondToEmergencyEvent(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("event_id") eventId: Int,
|
||||
@Body request: ResponseCreateRequest
|
||||
): Response<ResponseResponse>
|
||||
|
||||
@GET("api/v1/alert/{alert_id}/responses")
|
||||
suspend fun getAlertResponses(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("alert_id") alertId: Int
|
||||
): Response<List<ResponseResponse>>
|
||||
|
||||
// ========== REPORTS ==========
|
||||
|
||||
@POST("api/v1/report")
|
||||
suspend fun createEmergencyReport(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: CreateReportRequest
|
||||
): Response<ReportResponse>
|
||||
|
||||
@GET("api/v1/reports")
|
||||
suspend fun getEmergencyReports(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<ReportResponse>>
|
||||
|
||||
@GET("api/v1/emergency/reports")
|
||||
suspend fun getEmergencyReportsAdmin(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<AlertResponse>>
|
||||
|
||||
// ========== SAFETY CHECK ==========
|
||||
|
||||
@POST("api/v1/safety-check")
|
||||
suspend fun createSafetyCheck(
|
||||
@Header("Authorization") token: String,
|
||||
@Body request: CreateSafetyCheckRequest
|
||||
): Response<SafetyCheckResponse>
|
||||
|
||||
@GET("api/v1/safety-checks")
|
||||
suspend fun getSafetyChecks(
|
||||
@Header("Authorization") token: String
|
||||
): Response<List<SafetyCheckResponse>>
|
||||
|
||||
// ========== STATISTICS ==========
|
||||
|
||||
@GET("api/v1/stats")
|
||||
suspend fun getEmergencyStats(
|
||||
@Header("Authorization") token: String
|
||||
): Response<EmergencyStatsResponse>
|
||||
|
||||
// ========== WEBSOCKET INFO ==========
|
||||
|
||||
@GET("api/v1/websocket/connections")
|
||||
suspend fun getWebsocketConnections(
|
||||
@Header("Authorization") token: String
|
||||
): Response<WebSocketConnectionsResponse>
|
||||
|
||||
@GET("api/v1/websocket/connections/{user_id}")
|
||||
suspend fun getUserWebsocketInfo(
|
||||
@Header("Authorization") token: String,
|
||||
@Path("user_id") userId: Int
|
||||
): Response<UserWebSocketInfoResponse>
|
||||
|
||||
@POST("api/v1/websocket/ping")
|
||||
suspend fun pingWebsocketConnections(
|
||||
@Header("Authorization") token: String
|
||||
): Response<WebSocketPingResponse>
|
||||
|
||||
@GET("api/v1/websocket/stats")
|
||||
suspend fun getWebsocketStats(
|
||||
@Header("Authorization") token: String
|
||||
): Response<WebSocketStatsResponse>
|
||||
|
||||
@POST("api/v1/websocket/broadcast")
|
||||
suspend fun broadcastTestMessage(
|
||||
@Header("Authorization") token: String,
|
||||
@Query("message") message: String
|
||||
): Response<BroadcastResponse>
|
||||
}
|
||||
|
||||
// ========== ДОПОЛНИТЕЛЬНЫЕ МОДЕЛИ ДЛЯ RealEmergencyApiService ==========
|
||||
|
||||
data class AlertResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val is_resolved: Boolean = false,
|
||||
val resolved_at: String?,
|
||||
val resolved_notes: String?,
|
||||
val notified_users_count: Int = 0,
|
||||
val responded_users_count: Int = 0,
|
||||
val created_at: String,
|
||||
val updated_at: String?,
|
||||
val user_name: String?,
|
||||
val user_phone: String?
|
||||
)
|
||||
|
||||
data class NearbyAlertResponse(
|
||||
val id: Int,
|
||||
val alert_type: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val distance_km: Double,
|
||||
val created_at: String,
|
||||
val responded_users_count: Int = 0
|
||||
)
|
||||
|
||||
data class EmergencyEventDetailsResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val status: String,
|
||||
val created_at: String,
|
||||
val updated_at: String?,
|
||||
val resolved_at: String?,
|
||||
val user: UserInfoResponse,
|
||||
val responses: List<ResponseResponse> = emptyList(),
|
||||
val notifications_sent: Int = 0,
|
||||
val websocket_notifications_sent: Int = 0,
|
||||
val push_notifications_sent: Int = 0,
|
||||
val contact_emergency_services: Boolean = true,
|
||||
val notify_emergency_contacts: Boolean = true
|
||||
)
|
||||
|
||||
data class ResponseCreateRequest(
|
||||
val response_type: String,
|
||||
val message: String? = null,
|
||||
val eta_minutes: Int? = null
|
||||
)
|
||||
|
||||
data class ResponseResponse(
|
||||
val id: Int,
|
||||
val alert_id: Int,
|
||||
val responder_id: Int,
|
||||
val response_type: String,
|
||||
val message: String?,
|
||||
val eta_minutes: Int?,
|
||||
val created_at: String,
|
||||
val responder_name: String?,
|
||||
val responder_phone: String?
|
||||
)
|
||||
|
||||
data class EmergencyStatsResponse(
|
||||
val total_alerts: Int = 0,
|
||||
val active_alerts: Int = 0,
|
||||
val resolved_alerts: Int = 0,
|
||||
val total_responders: Int = 0,
|
||||
val avg_response_time_minutes: Double = 0.0
|
||||
)
|
||||
|
||||
data class UserInfoResponse(
|
||||
val id: Int,
|
||||
val username: String,
|
||||
val full_name: String?,
|
||||
val phone: String?
|
||||
)
|
||||
@@ -0,0 +1,317 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.api.models
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
// ========== ОСНОВНЫЕ API МОДЕЛИ ==========
|
||||
|
||||
data class CreateEmergencyRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val alert_type: String = "general",
|
||||
val message: String? = null,
|
||||
val address: String? = null,
|
||||
val contact_emergency_services: Boolean = true,
|
||||
val notify_emergency_contacts: Boolean = true,
|
||||
val battery_level: Int? = null
|
||||
)
|
||||
|
||||
data class EmergencyEventResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val status: String,
|
||||
val is_resolved: Boolean,
|
||||
val created_at: String,
|
||||
val updated_at: String?,
|
||||
val resolved_at: String?,
|
||||
val user: ApiUserInfo?
|
||||
)
|
||||
|
||||
data class NearbyEventsResponse(
|
||||
val events: List<NearbyEmergencyEvent>,
|
||||
val total: Int,
|
||||
val radius_km: Double
|
||||
)
|
||||
|
||||
data class NearbyEmergencyEvent(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val distance_km: Double,
|
||||
val created_at: String,
|
||||
val user: ApiUserInfo?
|
||||
)
|
||||
|
||||
data class EmergencyEventDetailResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val status: String,
|
||||
val is_resolved: Boolean,
|
||||
val created_at: String,
|
||||
val updated_at: String?,
|
||||
val resolved_at: String?,
|
||||
val user: ApiUserInfo,
|
||||
val responses: List<EventResponse>
|
||||
)
|
||||
|
||||
data class EventResponseRequest(
|
||||
val response_type: String,
|
||||
val message: String? = null,
|
||||
val eta_minutes: Int? = null,
|
||||
val location_latitude: Double? = null,
|
||||
val location_longitude: Double? = null
|
||||
)
|
||||
|
||||
data class EventResponseResponse(
|
||||
val id: Int,
|
||||
val event_id: Int,
|
||||
val user_id: Int,
|
||||
val response_type: String,
|
||||
val message: String?,
|
||||
val eta_minutes: Int?,
|
||||
val location_latitude: Double?,
|
||||
val location_longitude: Double?,
|
||||
val created_at: String,
|
||||
val user: ApiUserInfo
|
||||
)
|
||||
|
||||
data class EventHistoryResponse(
|
||||
val events: List<EmergencyEventResponse>,
|
||||
val total: Int,
|
||||
val page: Int,
|
||||
val per_page: Int
|
||||
)
|
||||
|
||||
data class NearbyUsersResponse(
|
||||
val users: List<ApiUserInfo>,
|
||||
val total: Int,
|
||||
val radius_km: Double
|
||||
)
|
||||
|
||||
data class EventsStatsResponse(
|
||||
val total_events: Int,
|
||||
val active_events: Int,
|
||||
val resolved_events: Int,
|
||||
val my_events: Int,
|
||||
val my_responses: Int,
|
||||
val average_response_time_minutes: Double?
|
||||
)
|
||||
|
||||
// ========== ВСПОМОГАТЕЛЬНЫЕ МОДЕЛИ ==========
|
||||
|
||||
data class ApiUserInfo(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val email: String?,
|
||||
val phone: String?,
|
||||
val profile_image_url: String?
|
||||
)
|
||||
|
||||
data class EventResponse(
|
||||
val id: Int,
|
||||
val user_id: Int,
|
||||
val response_type: String,
|
||||
val message: String?,
|
||||
val eta_minutes: Int?,
|
||||
val created_at: String,
|
||||
val user: ApiUserInfo
|
||||
)
|
||||
|
||||
// ========== ДОПОЛНИТЕЛЬНЫЕ МОДЕЛИ (уже определены в EmergencyApiService.kt) ==========
|
||||
|
||||
data class CreateReportRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val report_type: String,
|
||||
val description: String,
|
||||
val address: String? = null,
|
||||
val is_anonymous: Boolean = false,
|
||||
val severity: Int = 3
|
||||
)
|
||||
|
||||
data class ReportResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int?,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val report_type: String,
|
||||
val description: String,
|
||||
val is_anonymous: Boolean,
|
||||
val severity: Int,
|
||||
val status: String = "pending",
|
||||
val created_at: String
|
||||
)
|
||||
|
||||
data class CreateSafetyCheckRequest(
|
||||
val message: String? = null,
|
||||
val location_latitude: Double? = null,
|
||||
val location_longitude: Double? = null
|
||||
)
|
||||
|
||||
data class SafetyCheckResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val message: String?,
|
||||
val location_latitude: Double?,
|
||||
val location_longitude: Double?,
|
||||
val created_at: String
|
||||
)
|
||||
|
||||
data class CreateAlertRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val alert_type: String = "general",
|
||||
val message: String? = null,
|
||||
val address: String? = null,
|
||||
val contact_emergency_services: Boolean = true,
|
||||
val notify_emergency_contacts: Boolean = true
|
||||
)
|
||||
|
||||
data class UpdateAlertRequest(
|
||||
val message: String? = null,
|
||||
val is_resolved: Boolean? = null
|
||||
)
|
||||
|
||||
data class WebSocketConnectionsResponse(
|
||||
val total_connections: Int,
|
||||
val active_connections: Int,
|
||||
val connections: List<ConnectionInfo>
|
||||
)
|
||||
|
||||
data class ConnectionInfo(
|
||||
val user_id: Int,
|
||||
val connected_at: String,
|
||||
val last_ping: String?
|
||||
)
|
||||
|
||||
data class UserWebSocketInfoResponse(
|
||||
val user_id: Int,
|
||||
val is_connected: Boolean,
|
||||
val connected_at: String?,
|
||||
val last_ping: String?
|
||||
)
|
||||
|
||||
data class WebSocketPingResponse(
|
||||
val total_pinged: Int,
|
||||
val responses: Int,
|
||||
val disconnected: Int
|
||||
)
|
||||
|
||||
data class WebSocketStatsResponse(
|
||||
val total_connections: Int,
|
||||
val active_connections: Int,
|
||||
val total_messages_sent: Int,
|
||||
val uptime_seconds: Int
|
||||
)
|
||||
|
||||
data class BroadcastResponse(
|
||||
val message_id: String,
|
||||
val recipients: Int,
|
||||
val delivered: Int
|
||||
)
|
||||
|
||||
// ========== ДОПОЛНИТЕЛЬНЫЕ МОДЕЛИ ДЛЯ RealEmergencyApiService ==========
|
||||
|
||||
data class AlertResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val is_resolved: Boolean = false,
|
||||
val resolved_at: String?,
|
||||
val resolved_notes: String?,
|
||||
val notified_users_count: Int = 0,
|
||||
val responded_users_count: Int = 0,
|
||||
val created_at: String,
|
||||
val updated_at: String?,
|
||||
val user_name: String?,
|
||||
val user_phone: String?
|
||||
)
|
||||
|
||||
data class NearbyAlertResponse(
|
||||
val id: Int,
|
||||
val alert_type: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val distance_km: Double,
|
||||
val created_at: String,
|
||||
val responded_users_count: Int = 0
|
||||
)
|
||||
|
||||
data class EmergencyEventDetailsResponse(
|
||||
val id: Int,
|
||||
val uuid: String,
|
||||
val user_id: Int,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val alert_type: String,
|
||||
val message: String?,
|
||||
val status: String,
|
||||
val created_at: String,
|
||||
val updated_at: String?,
|
||||
val resolved_at: String?,
|
||||
val user: UserInfoResponse,
|
||||
val responses: List<ResponseResponse> = emptyList(),
|
||||
val notifications_sent: Int = 0,
|
||||
val websocket_notifications_sent: Int = 0,
|
||||
val push_notifications_sent: Int = 0,
|
||||
val contact_emergency_services: Boolean = true,
|
||||
val notify_emergency_contacts: Boolean = true
|
||||
)
|
||||
|
||||
data class ResponseCreateRequest(
|
||||
val response_type: String,
|
||||
val message: String? = null,
|
||||
val eta_minutes: Int? = null
|
||||
)
|
||||
|
||||
data class ResponseResponse(
|
||||
val id: Int,
|
||||
val alert_id: Int,
|
||||
val responder_id: Int,
|
||||
val response_type: String,
|
||||
val message: String?,
|
||||
val eta_minutes: Int?,
|
||||
val created_at: String,
|
||||
val responder_name: String?,
|
||||
val responder_phone: String?
|
||||
)
|
||||
|
||||
data class EmergencyStatsResponse(
|
||||
val total_alerts: Int = 0,
|
||||
val active_alerts: Int = 0,
|
||||
val resolved_alerts: Int = 0,
|
||||
val total_responders: Int = 0,
|
||||
val avg_response_time_minutes: Double = 0.0
|
||||
)
|
||||
|
||||
data class UserInfoResponse(
|
||||
val id: Int,
|
||||
val username: String,
|
||||
val full_name: String?,
|
||||
val phone: String?
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.auth
|
||||
|
||||
interface AuthManager {
|
||||
suspend fun getToken(): String?
|
||||
suspend fun getCurrentUserId(): String?
|
||||
suspend fun isAuthenticated(): Boolean
|
||||
}
|
||||
|
||||
class AuthManagerImpl : AuthManager {
|
||||
override suspend fun getToken(): String? {
|
||||
// TODO: Implement proper token retrieval
|
||||
return "demo_token"
|
||||
}
|
||||
|
||||
override suspend fun getCurrentUserId(): String? {
|
||||
// TODO: Implement proper user ID retrieval
|
||||
return "demo_user_id"
|
||||
}
|
||||
|
||||
override suspend fun isAuthenticated(): Boolean {
|
||||
return getToken() != null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.dao
|
||||
|
||||
import androidx.room.*
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kr.smartsoltech.wellshe.emergency.data.entities.EmergencyEventEntity
|
||||
import kr.smartsoltech.wellshe.emergency.data.entities.EmergencyResponseEntity
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus
|
||||
|
||||
@Dao
|
||||
interface EmergencyDao {
|
||||
|
||||
@Query("SELECT * FROM emergency_events WHERE status = 'ACTIVE' ORDER BY createdAt DESC")
|
||||
fun getActiveEvents(): Flow<List<EmergencyEventEntity>>
|
||||
|
||||
@Query("SELECT * FROM emergency_events WHERE status = 'ACTIVE' ORDER BY createdAt DESC")
|
||||
fun observeActiveEvents(): Flow<List<EmergencyEventEntity>>
|
||||
|
||||
@Query("SELECT * FROM emergency_events ORDER BY createdAt DESC")
|
||||
fun observeEvents(): Flow<List<EmergencyEventEntity>>
|
||||
|
||||
@Query("SELECT * FROM emergency_events WHERE userId = :userId ORDER BY createdAt DESC LIMIT :limit")
|
||||
suspend fun getUserEvents(userId: String, limit: Int = 20): List<EmergencyEventEntity>
|
||||
|
||||
@Query("SELECT * FROM emergency_events WHERE id = :eventId")
|
||||
suspend fun getEventById(eventId: String): EmergencyEventEntity?
|
||||
|
||||
@Query("SELECT * FROM emergency_events WHERE isLocal = 1 AND syncedAt IS NULL")
|
||||
suspend fun getUnsyncedEvents(): List<EmergencyEventEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertEvent(event: EmergencyEventEntity)
|
||||
|
||||
@Update
|
||||
suspend fun updateEvent(event: EmergencyEventEntity)
|
||||
|
||||
@Query("UPDATE emergency_events SET syncedAt = :syncedAt, isLocal = 0 WHERE id = :localId")
|
||||
suspend fun markEventAsSynced(localId: String, syncedAt: Long)
|
||||
|
||||
@Query("UPDATE emergency_events SET status = :status WHERE id = :eventId")
|
||||
suspend fun updateEventStatus(eventId: String, status: EmergencyStatus)
|
||||
|
||||
@Query("DELETE FROM emergency_events WHERE status = 'EXPIRED' AND expiresAt < :currentTime")
|
||||
suspend fun deleteExpiredEvents(currentTime: Long = System.currentTimeMillis())
|
||||
|
||||
// Emergency Responses
|
||||
@Query("SELECT * FROM emergency_responses WHERE eventId = :eventId ORDER BY createdAt DESC")
|
||||
suspend fun getEventResponses(eventId: String): List<EmergencyResponseEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertResponse(response: EmergencyResponseEntity)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.Embedded
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.EmergencyType
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus
|
||||
import java.util.UUID
|
||||
|
||||
@Entity(tableName = "emergency_events")
|
||||
data class EmergencyEventEntity(
|
||||
@PrimaryKey
|
||||
val id: String = UUID.randomUUID().toString(),
|
||||
val userId: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val eventType: EmergencyType,
|
||||
val message: String?,
|
||||
val status: EmergencyStatus,
|
||||
val severity: Int,
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
val updatedAt: Long = System.currentTimeMillis(),
|
||||
val expiresAt: Long = System.currentTimeMillis() + (30 * 60 * 1000), // 30 минут
|
||||
val syncedAt: Long? = null,
|
||||
val isLocal: Boolean = true,
|
||||
val distanceMeters: Double? = null,
|
||||
@Embedded(prefix = "user_")
|
||||
val userInfo: UserInfo? = null,
|
||||
val nearbyUsersNotified: Int? = null,
|
||||
val responseCount: Int = 0
|
||||
)
|
||||
|
||||
data class UserInfo(
|
||||
val firstName: String,
|
||||
val age: Int?,
|
||||
val avatarUrl: String?
|
||||
)
|
||||
|
||||
@Entity(tableName = "emergency_responses")
|
||||
data class EmergencyResponseEntity(
|
||||
@PrimaryKey
|
||||
val id: String = UUID.randomUUID().toString(),
|
||||
val eventId: String,
|
||||
val responderId: String,
|
||||
val responseType: String,
|
||||
val message: String?,
|
||||
val estimatedArrival: Long?,
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
@Embedded(prefix = "responder_")
|
||||
val responderInfo: UserInfo? = null
|
||||
)
|
||||
@@ -0,0 +1,260 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.mappers
|
||||
|
||||
import kr.smartsoltech.wellshe.emergency.data.api.*
|
||||
import kr.smartsoltech.wellshe.emergency.data.entities.*
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.*
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.*
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class EmergencyMapper @Inject constructor() {
|
||||
|
||||
private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())
|
||||
|
||||
// API mappings
|
||||
fun toApiRequest(request: kr.smartsoltech.wellshe.emergency.domain.models.CreateEmergencyRequest): kr.smartsoltech.wellshe.emergency.data.api.CreateEmergencyRequest {
|
||||
return kr.smartsoltech.wellshe.emergency.data.api.CreateEmergencyRequest(
|
||||
latitude = request.latitude,
|
||||
longitude = request.longitude,
|
||||
alert_type = when(request.eventType) {
|
||||
EmergencyType.SOS -> "general"
|
||||
EmergencyType.MEDICAL -> "medical"
|
||||
EmergencyType.FIRE -> "fire"
|
||||
EmergencyType.ACCIDENT -> "accident"
|
||||
else -> "general"
|
||||
},
|
||||
message = request.message
|
||||
)
|
||||
}
|
||||
|
||||
fun toEmergencyEventResponse(response: kr.smartsoltech.wellshe.emergency.data.api.EmergencyEventResponse): kr.smartsoltech.wellshe.emergency.domain.models.EmergencyEventResponse {
|
||||
android.util.Log.d("EmergencyMapper", "Raw server response: id=${response.id}, uuid=${response.uuid}")
|
||||
|
||||
return kr.smartsoltech.wellshe.emergency.domain.models.EmergencyEventResponse(
|
||||
eventId = response.uuid, // Используем UUID как eventId
|
||||
status = if (response.is_resolved) "resolved" else "active",
|
||||
nearbyUsersNotified = 0, // TODO: добавить в API модель
|
||||
estimatedResponseTime = null,
|
||||
createdAt = response.created_at,
|
||||
expiresAt = (System.currentTimeMillis() + 1800000).toString() // 30 минут
|
||||
)
|
||||
}
|
||||
|
||||
fun toEmergencyEvent(apiEvent: kr.smartsoltech.wellshe.emergency.data.api.NearbyEmergencyEvent): EmergencyEvent {
|
||||
return EmergencyEvent(
|
||||
id = apiEvent.id.toString(),
|
||||
userId = "",
|
||||
latitude = apiEvent.latitude,
|
||||
longitude = apiEvent.longitude,
|
||||
eventType = mapAlertTypeToEmergencyType(apiEvent.alert_type),
|
||||
message = apiEvent.message ?: "",
|
||||
status = EmergencyStatus.ACTIVE,
|
||||
severity = 5,
|
||||
createdAt = parseDate(apiEvent.created_at),
|
||||
updatedAt = parseDate(apiEvent.created_at),
|
||||
expiresAt = parseDate(apiEvent.created_at) + (30 * 60 * 1000),
|
||||
distanceMeters = apiEvent.distance_km * 1000,
|
||||
responseCount = 0
|
||||
)
|
||||
}
|
||||
|
||||
fun toEmergencyEventDetail(response: kr.smartsoltech.wellshe.emergency.data.api.EmergencyEventDetailResponse): EmergencyEventDetail {
|
||||
return EmergencyEventDetail(
|
||||
id = response.uuid,
|
||||
userId = response.user_id.toString(),
|
||||
latitude = response.latitude,
|
||||
longitude = response.longitude,
|
||||
eventType = mapAlertTypeToEmergencyType(response.alert_type),
|
||||
message = response.message ?: "",
|
||||
status = mapAlertStatusToEmergencyStatus(response.status),
|
||||
severity = 5,
|
||||
createdAt = parseDate(response.created_at),
|
||||
updatedAt = parseDate(response.updated_at ?: response.created_at),
|
||||
expiresAt = parseDate(response.created_at) + (30 * 60 * 1000),
|
||||
responses = response.responses.map { toEventResponse(it) },
|
||||
metadata = emptyMap()
|
||||
)
|
||||
}
|
||||
|
||||
// Entity mappings
|
||||
fun toEmergencyEventEntity(request: kr.smartsoltech.wellshe.emergency.domain.models.CreateEmergencyRequest, userId: String): EmergencyEventEntity {
|
||||
return EmergencyEventEntity(
|
||||
userId = userId,
|
||||
latitude = request.latitude,
|
||||
longitude = request.longitude,
|
||||
eventType = request.eventType,
|
||||
message = request.message,
|
||||
status = EmergencyStatus.ACTIVE,
|
||||
severity = request.severity,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
expiresAt = System.currentTimeMillis() + (30 * 60 * 1000), // 30 minutes
|
||||
isLocal = true
|
||||
)
|
||||
}
|
||||
|
||||
fun toEmergencyEvent(entity: EmergencyEventEntity): EmergencyEvent {
|
||||
return EmergencyEvent(
|
||||
id = entity.id,
|
||||
userId = entity.userId,
|
||||
latitude = entity.latitude,
|
||||
longitude = entity.longitude,
|
||||
eventType = entity.eventType,
|
||||
message = entity.message,
|
||||
status = entity.status,
|
||||
severity = entity.severity,
|
||||
createdAt = entity.createdAt,
|
||||
updatedAt = entity.updatedAt,
|
||||
expiresAt = entity.expiresAt,
|
||||
distanceMeters = entity.distanceMeters,
|
||||
userInfo = entity.userInfo?.let {
|
||||
kr.smartsoltech.wellshe.emergency.domain.models.UserInfo(
|
||||
firstName = it.firstName,
|
||||
age = it.age,
|
||||
avatarUrl = it.avatarUrl
|
||||
)
|
||||
},
|
||||
responseCount = entity.responseCount,
|
||||
nearbyUsersNotified = entity.nearbyUsersNotified,
|
||||
isLocal = entity.isLocal
|
||||
)
|
||||
}
|
||||
|
||||
fun toCreateRequest(event: EmergencyEvent): kr.smartsoltech.wellshe.emergency.domain.models.CreateEmergencyRequest {
|
||||
return kr.smartsoltech.wellshe.emergency.domain.models.CreateEmergencyRequest(
|
||||
latitude = event.latitude,
|
||||
longitude = event.longitude,
|
||||
eventType = event.eventType,
|
||||
message = event.message,
|
||||
severity = event.severity
|
||||
)
|
||||
}
|
||||
|
||||
fun toEventResponseRequest(response: kr.smartsoltech.wellshe.emergency.domain.models.EventResponse): kr.smartsoltech.wellshe.emergency.data.api.EventResponseRequest {
|
||||
return kr.smartsoltech.wellshe.emergency.data.api.EventResponseRequest(
|
||||
response_type = response.responseType.name.lowercase(),
|
||||
message = response.message,
|
||||
eta_minutes = response.estimatedArrival?.let { (it / 60000).toInt() }
|
||||
)
|
||||
}
|
||||
|
||||
fun toEmergencyResponseEntity(response: kr.smartsoltech.wellshe.emergency.domain.models.EventResponse, eventId: String): EmergencyResponseEntity {
|
||||
return EmergencyResponseEntity(
|
||||
eventId = eventId,
|
||||
responderId = response.responderId,
|
||||
responseType = response.responseType.name,
|
||||
message = response.message,
|
||||
estimatedArrival = response.estimatedArrival,
|
||||
responderInfo = response.responderInfo?.let { domainUserInfo ->
|
||||
kr.smartsoltech.wellshe.emergency.data.entities.UserInfo(
|
||||
firstName = domainUserInfo.firstName,
|
||||
age = domainUserInfo.age,
|
||||
avatarUrl = domainUserInfo.avatarUrl
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fun toEventResponse(entity: EmergencyResponseEntity): kr.smartsoltech.wellshe.emergency.domain.models.EventResponse {
|
||||
return kr.smartsoltech.wellshe.emergency.domain.models.EventResponse(
|
||||
id = entity.id,
|
||||
eventId = entity.eventId,
|
||||
responderId = entity.responderId,
|
||||
responseType = ResponseType.valueOf(entity.responseType),
|
||||
message = entity.message,
|
||||
estimatedArrival = entity.estimatedArrival,
|
||||
createdAt = entity.createdAt,
|
||||
responderInfo = entity.responderInfo?.let { entityUserInfo ->
|
||||
kr.smartsoltech.wellshe.emergency.domain.models.UserInfo(
|
||||
firstName = entityUserInfo.firstName,
|
||||
age = entityUserInfo.age,
|
||||
avatarUrl = entityUserInfo.avatarUrl
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun toUserInfo(apiUserInfo: kr.smartsoltech.wellshe.emergency.data.api.ApiUserInfo): kr.smartsoltech.wellshe.emergency.domain.models.UserInfo {
|
||||
return kr.smartsoltech.wellshe.emergency.domain.models.UserInfo(
|
||||
firstName = apiUserInfo.name,
|
||||
age = null, // API не предоставляет возраст
|
||||
avatarUrl = apiUserInfo.profile_image_url
|
||||
)
|
||||
}
|
||||
|
||||
fun toNearbyUsers(response: kr.smartsoltech.wellshe.emergency.data.api.NearbyUsersResponse): List<kr.smartsoltech.wellshe.emergency.domain.models.NearbyUser> {
|
||||
return response.users.map { nearbyUser ->
|
||||
kr.smartsoltech.wellshe.emergency.domain.models.NearbyUser(
|
||||
userId = nearbyUser.id.toString(),
|
||||
firstName = nearbyUser.name,
|
||||
age = null,
|
||||
avatarUrl = nearbyUser.profile_image_url,
|
||||
distanceMeters = 0.0, // TODO: вычислить расстояние
|
||||
isOnline = true
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun toEventResponse(apiResponse: kr.smartsoltech.wellshe.emergency.data.api.EventResponse): kr.smartsoltech.wellshe.emergency.domain.models.EventResponse {
|
||||
return kr.smartsoltech.wellshe.emergency.domain.models.EventResponse(
|
||||
id = apiResponse.id.toString(),
|
||||
eventId = "",
|
||||
responderId = apiResponse.user_id.toString(),
|
||||
responseType = mapResponseType(apiResponse.response_type),
|
||||
message = apiResponse.message,
|
||||
estimatedArrival = apiResponse.eta_minutes?.let { it * 60 * 1000L },
|
||||
createdAt = parseDate(apiResponse.created_at),
|
||||
responderInfo = kr.smartsoltech.wellshe.emergency.domain.models.UserInfo(
|
||||
firstName = apiResponse.user.name,
|
||||
age = null,
|
||||
avatarUrl = apiResponse.user.profile_image_url
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun formatDate(timestamp: Long): String {
|
||||
return dateFormat.format(Date(timestamp))
|
||||
}
|
||||
|
||||
// Делаем методы публичными для использования в репозитории
|
||||
fun mapAlertTypeToEmergencyType(alertType: String): EmergencyType {
|
||||
return when(alertType) {
|
||||
"medical" -> EmergencyType.MEDICAL
|
||||
"fire" -> EmergencyType.FIRE
|
||||
"accident" -> EmergencyType.ACCIDENT
|
||||
"violence" -> EmergencyType.SOS
|
||||
"harassment" -> EmergencyType.SOS
|
||||
else -> EmergencyType.SOS
|
||||
}
|
||||
}
|
||||
|
||||
fun parseDate(dateString: String): Long {
|
||||
return try {
|
||||
dateFormat.parse(dateString)?.time ?: System.currentTimeMillis()
|
||||
} catch (e: Exception) {
|
||||
System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
|
||||
private fun mapAlertStatusToEmergencyStatus(status: String): EmergencyStatus {
|
||||
return when(status) {
|
||||
"active" -> EmergencyStatus.ACTIVE
|
||||
"resolved" -> EmergencyStatus.RESOLVED
|
||||
"cancelled" -> EmergencyStatus.CANCELLED
|
||||
else -> EmergencyStatus.ACTIVE
|
||||
}
|
||||
}
|
||||
|
||||
private fun mapResponseType(responseType: String): ResponseType {
|
||||
return when(responseType) {
|
||||
"help_on_way" -> ResponseType.ON_WAY
|
||||
"calling_emergency" -> ResponseType.CALLED_POLICE
|
||||
"safe_location" -> ResponseType.SAFE_NOW
|
||||
"cant_help" -> ResponseType.CANNOT_HELP
|
||||
else -> ResponseType.ON_WAY
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.models
|
||||
|
||||
enum class EmergencyType {
|
||||
SOS,
|
||||
HARASSMENT,
|
||||
STALKING,
|
||||
MEDICAL,
|
||||
FIRE,
|
||||
ACCIDENT,
|
||||
OTHER
|
||||
}
|
||||
|
||||
enum class EmergencyStatus {
|
||||
ACTIVE,
|
||||
HANDLED,
|
||||
CLOSED,
|
||||
EXPIRED,
|
||||
RESOLVED,
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
enum class ResponseType {
|
||||
ON_WAY,
|
||||
CALLED_POLICE,
|
||||
SAFE_NOW,
|
||||
CANNOT_HELP,
|
||||
HELP_ON_WAY,
|
||||
CONTACTED_AUTHORITIES,
|
||||
FALSE_ALARM
|
||||
}
|
||||
|
||||
enum class ConnectionStatus {
|
||||
CONNECTED,
|
||||
CONNECTING,
|
||||
DISCONNECTED,
|
||||
RECONNECTING
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.repository
|
||||
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kr.smartsoltech.wellshe.emergency.data.api.EmergencyApiService
|
||||
import kr.smartsoltech.wellshe.emergency.data.api.EventResponseRequest
|
||||
import kr.smartsoltech.wellshe.emergency.data.dao.EmergencyDao
|
||||
import kr.smartsoltech.wellshe.emergency.data.websocket.EmergencyWebSocketManager
|
||||
import kr.smartsoltech.wellshe.emergency.data.mappers.EmergencyMapper
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.*
|
||||
import kr.smartsoltech.wellshe.emergency.domain.repository.EmergencyRepository
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus
|
||||
import kr.smartsoltech.wellshe.emergency.data.auth.AuthManager
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class EmergencyRepositoryImpl @Inject constructor(
|
||||
private val apiService: EmergencyApiService,
|
||||
private val dao: EmergencyDao,
|
||||
private val webSocketManager: EmergencyWebSocketManager,
|
||||
private val mapper: EmergencyMapper,
|
||||
private val authManager: AuthManager
|
||||
) : EmergencyRepository {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "EmergencyRepository"
|
||||
}
|
||||
|
||||
override suspend fun createEmergencyEvent(request: CreateEmergencyRequest): Result<EmergencyEventResponse> {
|
||||
return try {
|
||||
Log.d(TAG, "Creating emergency event: ${request.eventType} at lat=${request.latitude}, lng=${request.longitude}")
|
||||
|
||||
val token = authManager.getToken()
|
||||
if (token.isNullOrEmpty()) {
|
||||
Log.e(TAG, "No auth token available for emergency request")
|
||||
return Result.failure(Exception("No auth token available"))
|
||||
}
|
||||
|
||||
Log.d(TAG, "Using auth token for emergency request: ${token.take(6)}...")
|
||||
|
||||
val apiRequest = mapper.toApiRequest(request)
|
||||
Log.d(TAG, "Mapped API request: $apiRequest")
|
||||
|
||||
Log.d(TAG, "Sending emergency event to server...")
|
||||
val response = apiService.createEmergencyEvent("Bearer $token", apiRequest)
|
||||
|
||||
Log.d(TAG, "Server response: code=${response.code()}, isSuccessful=${response.isSuccessful}")
|
||||
|
||||
if (response.isSuccessful) {
|
||||
val body = response.body()
|
||||
if (body != null) {
|
||||
Log.i(TAG, "Emergency event created successfully: ${body}")
|
||||
val mappedResponse = mapper.toEmergencyEventResponse(body)
|
||||
Log.d(TAG, "Mapped response: $mappedResponse")
|
||||
Result.success(mappedResponse)
|
||||
} else {
|
||||
Log.e(TAG, "Server response body is null")
|
||||
Result.failure(Exception("Server response body is null"))
|
||||
}
|
||||
} else {
|
||||
val errorBody = response.errorBody()?.string()
|
||||
Log.e(TAG, "API Error: ${response.code()}, message: ${response.message()}, body: $errorBody")
|
||||
Result.failure(Exception("API Error: ${response.code()} - ${response.message()}${if (errorBody != null) ": $errorBody" else ""}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Exception creating emergency event: ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getNearbyEvents(latitude: Double, longitude: Double, radius: Int): Result<List<EmergencyEvent>> {
|
||||
return try {
|
||||
val token = authManager.getToken() ?: return Result.failure(Exception("No auth token"))
|
||||
|
||||
val response = apiService.getNearbyEvents("Bearer $token", latitude, longitude, radius.toDouble())
|
||||
if (response.isSuccessful) {
|
||||
val body = response.body()!!
|
||||
val events = body.events.map { mapper.toEmergencyEvent(it) }
|
||||
Result.success(events)
|
||||
} else {
|
||||
Result.failure(Exception("API Error: ${response.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getNearbyUsers(latitude: Double, longitude: Double, radius: Int): Result<List<NearbyUser>> {
|
||||
return try {
|
||||
Log.d(TAG, "Getting nearby users at lat=$latitude, lng=$longitude, radius=${radius}m")
|
||||
|
||||
val token = authManager.getToken()
|
||||
if (token.isNullOrEmpty()) {
|
||||
Log.e(TAG, "No auth token available for nearby users request")
|
||||
return Result.failure(Exception("No auth token available"))
|
||||
}
|
||||
|
||||
val radiusKm = radius / 1000.0
|
||||
Log.d(TAG, "Sending nearby users request to server with radius_km=$radiusKm...")
|
||||
|
||||
val response = apiService.getNearbyUsers("Bearer $token", latitude, longitude, radiusKm)
|
||||
|
||||
Log.d(TAG, "Nearby users response: code=${response.code()}, isSuccessful=${response.isSuccessful}")
|
||||
|
||||
if (response.isSuccessful) {
|
||||
val body = response.body()
|
||||
if (body != null) {
|
||||
Log.i(TAG, "Found ${body.users.size} nearby users")
|
||||
val nearbyUsers = mapper.toNearbyUsers(body)
|
||||
Result.success(nearbyUsers)
|
||||
} else {
|
||||
Log.e(TAG, "Nearby users response body is null")
|
||||
Result.success(emptyList())
|
||||
}
|
||||
} else {
|
||||
val errorBody = response.errorBody()?.string()
|
||||
Log.e(TAG, "Nearby users API Error: ${response.code()}, message: ${response.message()}, body: $errorBody")
|
||||
Result.success(emptyList())
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Exception getting nearby users: ${e.message}", e)
|
||||
Result.success(emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getEventDetails(eventId: String): Result<EmergencyEventDetail> {
|
||||
return try {
|
||||
val token = authManager.getToken() ?: return Result.failure(Exception("No auth token"))
|
||||
|
||||
val response = apiService.getEventDetails("Bearer $token", eventId.toInt())
|
||||
if (response.isSuccessful) {
|
||||
val body = response.body()!!
|
||||
Result.success(mapper.toEmergencyEventDetail(body))
|
||||
} else {
|
||||
Result.failure(Exception("API Error: ${response.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun saveLocalEmergencyEvent(request: CreateEmergencyRequest): EmergencyEvent {
|
||||
val entity = mapper.toEmergencyEventEntity(request, getCurrentUserId())
|
||||
dao.insertEvent(entity)
|
||||
return mapper.toEmergencyEvent(entity)
|
||||
}
|
||||
|
||||
override suspend fun markEventAsSynced(localId: String, remoteId: String) {
|
||||
dao.markEventAsSynced(localId, System.currentTimeMillis())
|
||||
}
|
||||
|
||||
override suspend fun getUnsyncedEvents(): List<EmergencyEvent> {
|
||||
return dao.getUnsyncedEvents().map { mapper.toEmergencyEvent(it) }
|
||||
}
|
||||
|
||||
override suspend fun syncLocalEvents(): Result<Unit> {
|
||||
return try {
|
||||
val unsyncedEvents = getUnsyncedEvents()
|
||||
unsyncedEvents.forEach { event ->
|
||||
val request = mapper.toCreateRequest(event)
|
||||
createEmergencyEvent(request).fold(
|
||||
onSuccess = { response ->
|
||||
markEventAsSynced(event.id, response.eventId)
|
||||
},
|
||||
onFailure = { /* Keep local event for next sync attempt */ }
|
||||
)
|
||||
}
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateEventStatus(eventId: String, status: EmergencyStatus, note: String?): Result<Unit> {
|
||||
return try {
|
||||
val token = authManager.getToken() ?: return Result.failure(Exception("No auth token"))
|
||||
|
||||
val response = apiService.updateEventStatus("Bearer $token", eventId.toInt())
|
||||
if (response.isSuccessful) {
|
||||
dao.updateEventStatus(eventId, status)
|
||||
Result.success(Unit)
|
||||
} else {
|
||||
Result.failure(Exception("API Error: ${response.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun respondToEvent(eventId: String, response: EventResponse): Result<Unit> {
|
||||
return try {
|
||||
val token = authManager.getToken() ?: return Result.failure(Exception("No auth token"))
|
||||
val request = mapper.toEventResponseRequest(response)
|
||||
|
||||
val apiResponse = apiService.respondToEvent("Bearer $token", eventId.toInt(), request)
|
||||
if (apiResponse.isSuccessful) {
|
||||
val responseEntity = mapper.toEmergencyResponseEntity(response, eventId)
|
||||
dao.insertResponse(responseEntity)
|
||||
Result.success(Unit)
|
||||
} else {
|
||||
Result.failure(Exception("API Error: ${apiResponse.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getEventResponses(eventId: String): Result<List<EventResponse>> {
|
||||
return try {
|
||||
val responses = dao.getEventResponses(eventId)
|
||||
Result.success(responses.map { mapper.toEventResponse(it) })
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getUserEventHistory(limit: Int, offset: Int): Result<List<EmergencyEvent>> {
|
||||
return try {
|
||||
val token = authManager.getToken() ?: return Result.failure(Exception("No auth token"))
|
||||
|
||||
val response = apiService.getEventHistory("Bearer $token")
|
||||
if (response.isSuccessful) {
|
||||
val body = response.body()!!
|
||||
val events = body.events.map { historyEvent ->
|
||||
EmergencyEvent(
|
||||
id = historyEvent.uuid,
|
||||
userId = historyEvent.user_id.toString(),
|
||||
latitude = historyEvent.latitude,
|
||||
longitude = historyEvent.longitude,
|
||||
eventType = mapper.mapAlertTypeToEmergencyType(historyEvent.alert_type),
|
||||
message = historyEvent.message,
|
||||
status = if (historyEvent.is_resolved) EmergencyStatus.RESOLVED else EmergencyStatus.ACTIVE,
|
||||
severity = 5,
|
||||
createdAt = mapper.parseDate(historyEvent.created_at),
|
||||
updatedAt = mapper.parseDate(historyEvent.updated_at ?: historyEvent.created_at),
|
||||
expiresAt = mapper.parseDate(historyEvent.created_at) + (30 * 60 * 1000),
|
||||
responseCount = 0
|
||||
)
|
||||
}
|
||||
Result.success(events)
|
||||
} else {
|
||||
Result.failure(Exception("API Error: ${response.code()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getActiveEvents(): Flow<List<EmergencyEvent>> {
|
||||
return dao.observeActiveEvents().map { entities ->
|
||||
entities.map { mapper.toEmergencyEvent(it) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun getConnectionStatus(): Flow<ConnectionStatus> {
|
||||
return webSocketManager.connectionStatus
|
||||
}
|
||||
|
||||
override fun connectWebSocket(userId: String, token: String) {
|
||||
webSocketManager.connect(userId, token)
|
||||
}
|
||||
|
||||
override fun disconnectWebSocket() {
|
||||
webSocketManager.disconnect()
|
||||
}
|
||||
|
||||
override fun getEventResponses(): Flow<EventResponseNotification> {
|
||||
return webSocketManager.eventResponses
|
||||
}
|
||||
|
||||
override suspend fun getEmergencyStats(): Result<EventStats> {
|
||||
return try {
|
||||
Result.success(EventStats(
|
||||
totalEvents = 0,
|
||||
activeEvents = 0,
|
||||
resolvedEvents = 0,
|
||||
escalatedEvents = 0,
|
||||
cancelledEvents = 0,
|
||||
averageResponseTime = 0.0,
|
||||
period = "last_30_days"
|
||||
))
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Stub implementations for new methods
|
||||
override suspend fun createEmergencyReport(request: CreateReportRequest): Result<EmergencyReport> {
|
||||
return Result.failure(Exception("Not implemented"))
|
||||
}
|
||||
|
||||
override suspend fun getEmergencyReports(): Result<List<EmergencyReport>> {
|
||||
return Result.success(emptyList())
|
||||
}
|
||||
|
||||
override suspend fun getEmergencyReportsAdmin(): Result<List<EmergencyEvent>> {
|
||||
return Result.success(emptyList())
|
||||
}
|
||||
|
||||
override suspend fun createSafetyCheck(request: CreateSafetyCheckRequest): Result<SafetyCheck> {
|
||||
return Result.failure(Exception("Not implemented"))
|
||||
}
|
||||
|
||||
override suspend fun getSafetyChecks(): Result<List<SafetyCheck>> {
|
||||
return Result.success(emptyList())
|
||||
}
|
||||
|
||||
override suspend fun createAlert(latitude: Double, longitude: Double, alertType: String, message: String?): Result<EmergencyEventResponse> {
|
||||
return Result.failure(Exception("Not implemented"))
|
||||
}
|
||||
|
||||
override suspend fun updateAlert(alertId: String, message: String?, isResolved: Boolean?): Result<EmergencyEventResponse> {
|
||||
return Result.failure(Exception("Not implemented"))
|
||||
}
|
||||
|
||||
override suspend fun resolveAlert(alertId: String): Result<Unit> {
|
||||
return Result.failure(Exception("Not implemented"))
|
||||
}
|
||||
|
||||
override suspend fun getMyAlerts(): Result<List<EmergencyEvent>> {
|
||||
return Result.success(emptyList())
|
||||
}
|
||||
|
||||
override suspend fun getActiveAlerts(): Result<List<EmergencyEvent>> {
|
||||
return Result.success(emptyList())
|
||||
}
|
||||
|
||||
override suspend fun getAlertResponses(alertId: String): Result<List<EventResponse>> {
|
||||
return Result.success(emptyList())
|
||||
}
|
||||
|
||||
override suspend fun getWebSocketStats(): Result<WebSocketStats> {
|
||||
return Result.success(WebSocketStats(0, 0, 0, 0))
|
||||
}
|
||||
|
||||
override suspend fun getConnectionStats(): Result<ConnectionStats> {
|
||||
return Result.success(ConnectionStats(0, 0, emptyList()))
|
||||
}
|
||||
|
||||
override suspend fun pingWebSocketConnections(): Result<Unit> {
|
||||
return Result.success(Unit)
|
||||
}
|
||||
|
||||
override suspend fun broadcastTestMessage(message: String): Result<Unit> {
|
||||
return Result.success(Unit)
|
||||
}
|
||||
|
||||
override suspend fun getNearbyEventsForMap(latitude: Double, longitude: Double, radiusKm: Double): Result<List<MapEvent>> {
|
||||
return Result.success(emptyList())
|
||||
}
|
||||
|
||||
override suspend fun getEventsInRadius(latitude: Double, longitude: Double, radiusKm: Double): Result<List<EmergencyEvent>> {
|
||||
return Result.success(emptyList())
|
||||
}
|
||||
|
||||
private suspend fun getCurrentUserId(): String {
|
||||
return authManager.getCurrentUserId() ?: "anonymous"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package kr.smartsoltech.wellshe.emergency.data.websocket
|
||||
|
||||
import android.util.Log
|
||||
import com.google.gson.Gson
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import okhttp3.*
|
||||
import org.json.JSONObject
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
import kr.smartsoltech.wellshe.BuildConfig
|
||||
|
||||
@Singleton
|
||||
class EmergencyWebSocketManager @Inject constructor(
|
||||
private val okHttpClient: OkHttpClient,
|
||||
private val gson: Gson
|
||||
) {
|
||||
private var webSocket: WebSocket? = null
|
||||
private var reconnectJob: Job? = null
|
||||
private var currentUserId: String? = null
|
||||
private var authToken: String? = null
|
||||
private var triedWithTokenQuery: Boolean = false
|
||||
|
||||
private val _emergencyAlerts = MutableSharedFlow<EmergencyAlert>(
|
||||
replay = 0,
|
||||
extraBufferCapacity = 10,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST
|
||||
)
|
||||
val emergencyAlerts: SharedFlow<EmergencyAlert> = _emergencyAlerts.asSharedFlow()
|
||||
|
||||
private val _eventUpdates = MutableSharedFlow<EventUpdate>(
|
||||
replay = 0,
|
||||
extraBufferCapacity = 10,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST
|
||||
)
|
||||
val eventUpdates: SharedFlow<EventUpdate> = _eventUpdates.asSharedFlow()
|
||||
|
||||
private val _eventResponses = MutableSharedFlow<EventResponseNotification>(
|
||||
replay = 0,
|
||||
extraBufferCapacity = 10,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST
|
||||
)
|
||||
val eventResponses: SharedFlow<EventResponseNotification> = _eventResponses.asSharedFlow()
|
||||
|
||||
private val _connectionStatus = MutableStateFlow(ConnectionStatus.DISCONNECTED)
|
||||
val connectionStatus: StateFlow<ConnectionStatus> = _connectionStatus.asStateFlow()
|
||||
|
||||
fun connect(userId: String, token: String, useQueryToken: Boolean = false) {
|
||||
disconnect()
|
||||
|
||||
currentUserId = userId
|
||||
authToken = token
|
||||
triedWithTokenQuery = useQueryToken
|
||||
|
||||
// Safety: do not attempt to connect with placeholder/test tokens
|
||||
if (token.startsWith("temp_token_for_")) {
|
||||
Log.w("EmergencyWS", "Refusing to connect to WebSocket: placeholder token detected for user=$userId. Token: $token")
|
||||
_connectionStatus.value = ConnectionStatus.DISCONNECTED
|
||||
return
|
||||
}
|
||||
|
||||
val wsUrl = if (useQueryToken) {
|
||||
// token in query param (less secure) — used only as a debug fallback
|
||||
BuildConfig.EMERGENCY_WS_BASE + "emergency/ws/$userId?token=${token}"
|
||||
} else {
|
||||
BuildConfig.EMERGENCY_WS_BASE + "emergency/ws/$userId"
|
||||
}
|
||||
|
||||
// Log the websocket URL and a masked token for debugging 403 errors
|
||||
try {
|
||||
val maskedToken = if (token.length > 6) token.substring(0, 6) + "..." else "***"
|
||||
Log.d("EmergencyWS", "Connecting to WebSocket: $wsUrl , token=$maskedToken , useQueryToken=$useQueryToken")
|
||||
} catch (e: Exception) {
|
||||
Log.d("EmergencyWS", "Connecting to WebSocket (unable to mask token)")
|
||||
}
|
||||
|
||||
val requestBuilder = Request.Builder()
|
||||
.url(wsUrl)
|
||||
|
||||
if (!useQueryToken) {
|
||||
// prefer Authorization header; add Origin because some servers check it
|
||||
requestBuilder
|
||||
.addHeader("Authorization", "Bearer $token")
|
||||
.addHeader("Origin", BuildConfig.EMERGENCY_API_BASE.removeSuffix("/"))
|
||||
Log.d("EmergencyWS", "Using Authorization header for token (masked) and Origin header")
|
||||
} else {
|
||||
Log.d("EmergencyWS", "Using query parameter for token (masked)")
|
||||
}
|
||||
|
||||
val request = requestBuilder.build()
|
||||
|
||||
_connectionStatus.value = ConnectionStatus.CONNECTING
|
||||
webSocket = okHttpClient.newWebSocket(request, EmergencyWebSocketListener())
|
||||
}
|
||||
|
||||
fun disconnect() {
|
||||
reconnectJob?.cancel()
|
||||
webSocket?.close(1000, "Manual disconnect")
|
||||
webSocket = null
|
||||
_connectionStatus.value = ConnectionStatus.DISCONNECTED
|
||||
}
|
||||
|
||||
private fun scheduleReconnect() {
|
||||
if (currentUserId == null || authToken == null) return
|
||||
|
||||
reconnectJob?.cancel()
|
||||
reconnectJob = CoroutineScope(Dispatchers.IO).launch {
|
||||
var delay = 5000L
|
||||
while (_connectionStatus.value == ConnectionStatus.DISCONNECTED && isActive) {
|
||||
delay(delay)
|
||||
if (_connectionStatus.value == ConnectionStatus.DISCONNECTED) {
|
||||
Log.d("EmergencyWS", "Attempting to reconnect...")
|
||||
_connectionStatus.value = ConnectionStatus.RECONNECTING
|
||||
connect(currentUserId!!, authToken!!)
|
||||
delay = minOf(delay * 2, 30000L) // Exponential backoff, max 30s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private inner class EmergencyWebSocketListener : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
_connectionStatus.value = ConnectionStatus.CONNECTED
|
||||
Log.d("EmergencyWS", "WebSocket connected successfully")
|
||||
|
||||
// Reset reconnect delay on successful connection
|
||||
reconnectJob?.cancel()
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
try {
|
||||
val json = JSONObject(text)
|
||||
val messageType = json.getString("type")
|
||||
|
||||
when (messageType) {
|
||||
"emergency_alert" -> {
|
||||
val alert = gson.fromJson(text, EmergencyAlert::class.java)
|
||||
_emergencyAlerts.tryEmit(alert)
|
||||
Log.d("EmergencyWS", "Emergency alert received: ${'$'}{alert.eventId}")
|
||||
}
|
||||
"event_update" -> {
|
||||
val update = gson.fromJson(text, EventUpdate::class.java)
|
||||
_eventUpdates.tryEmit(update)
|
||||
Log.d("EmergencyWS", "Event update received: ${'$'}{update.eventId}")
|
||||
}
|
||||
"event_response" -> {
|
||||
val response = gson.fromJson(text, EventResponseNotification::class.java)
|
||||
_eventResponses.tryEmit(response)
|
||||
Log.d("EmergencyWS", "Event response received for: ${'$'}{response.eventId}")
|
||||
}
|
||||
"ping" -> {
|
||||
webSocket.send("pong")
|
||||
}
|
||||
else -> {
|
||||
Log.w("EmergencyWS", "Unknown message type: $messageType")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyWS", "Error parsing WebSocket message: $text", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
Log.e("EmergencyWS", "WebSocket connection failed", t)
|
||||
response?.let {
|
||||
try {
|
||||
Log.e("EmergencyWS", "WebSocket HTTP response: code=${it.code}, message=${it.message}")
|
||||
Log.e("EmergencyWS", "WebSocket response headers: ${it.headers}")
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyWS", "Failed to log response details", e)
|
||||
}
|
||||
}
|
||||
_connectionStatus.value = ConnectionStatus.DISCONNECTED
|
||||
// If server refused with 403 and we haven't tried token-in-query yet, try once (debug-only)
|
||||
try {
|
||||
if (response?.code == 403 && !triedWithTokenQuery && BuildConfig.DEBUG && currentUserId != null && authToken != null) {
|
||||
Log.d("EmergencyWS", "403 received — retrying WebSocket with token in query (debug-only)")
|
||||
// slight delay before retry
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
delay(500)
|
||||
connect(currentUserId!!, authToken!!, useQueryToken = true)
|
||||
}
|
||||
return
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyWS", "Error during 403 retry logic", e)
|
||||
}
|
||||
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
Log.d("EmergencyWS", "WebSocket closed: code=$code, reason=$reason")
|
||||
_connectionStatus.value = ConnectionStatus.DISCONNECTED
|
||||
|
||||
// Only attempt reconnect if it wasn't a manual disconnect
|
||||
if (code != 1000) {
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WebSocket message models
|
||||
data class EmergencyAlert(
|
||||
val type: String = "emergency_alert",
|
||||
val eventId: String,
|
||||
val distanceMeters: Int,
|
||||
val eventType: String,
|
||||
val severity: Int,
|
||||
val message: String,
|
||||
val userInfo: WsUserInfo,
|
||||
val createdAt: String
|
||||
)
|
||||
|
||||
data class EventUpdate(
|
||||
val type: String = "event_update",
|
||||
val eventId: String,
|
||||
val status: String,
|
||||
val updateMessage: String?
|
||||
)
|
||||
|
||||
data class EventResponseNotification(
|
||||
val type: String = "event_response",
|
||||
val eventId: String,
|
||||
val responder: WsUserInfo,
|
||||
val responseType: String,
|
||||
val message: String?,
|
||||
val estimatedArrival: String?
|
||||
)
|
||||
|
||||
data class WsUserInfo(
|
||||
val userId: String,
|
||||
val firstName: String,
|
||||
val age: Int?,
|
||||
val avatarUrl: String?
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
package kr.smartsoltech.wellshe.emergency.debug.stub
|
||||
|
||||
// Заглушка в main-источнике, чтобы не конфликтовать с реализацией в src/debug
|
||||
object AuthTesterStub {
|
||||
fun runFullTest(): Boolean {
|
||||
// no-op stub in a different package/name to avoid redeclaration in debug builds
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package kr.smartsoltech.wellshe.emergency.di
|
||||
|
||||
import android.content.Context
|
||||
import com.google.gson.Gson
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import okhttp3.OkHttpClient
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.gson.GsonConverterFactory
|
||||
import kr.smartsoltech.wellshe.emergency.data.api.EmergencyApiService
|
||||
import kr.smartsoltech.wellshe.emergency.data.dao.EmergencyDao
|
||||
import kr.smartsoltech.wellshe.emergency.data.mappers.EmergencyMapper
|
||||
import kr.smartsoltech.wellshe.emergency.data.repository.EmergencyRepositoryImpl
|
||||
import kr.smartsoltech.wellshe.emergency.data.auth.AuthManager
|
||||
import kr.smartsoltech.wellshe.emergency.data.auth.AuthManagerImpl
|
||||
import kr.smartsoltech.wellshe.emergency.data.websocket.EmergencyWebSocketManager
|
||||
import kr.smartsoltech.wellshe.emergency.domain.repository.EmergencyRepository
|
||||
import kr.smartsoltech.wellshe.emergency.domain.usecases.*
|
||||
import kr.smartsoltech.wellshe.emergency.utils.*
|
||||
import kr.smartsoltech.wellshe.data.AppDatabase
|
||||
import kr.smartsoltech.wellshe.data.storage.TokenManager
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.inject.Singleton
|
||||
|
||||
import kr.smartsoltech.wellshe.BuildConfig
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object EmergencyModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideEmergencyDao(database: AppDatabase): EmergencyDao = database.emergencyDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideOkHttpClient(): OkHttpClient {
|
||||
return OkHttpClient.Builder()
|
||||
.connectTimeout(30, TimeUnit.SECONDS)
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.writeTimeout(30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideEmergencyApiService(okHttpClient: OkHttpClient, gson: Gson): EmergencyApiService {
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(BuildConfig.EMERGENCY_API_BASE) // Emergency Service URL from BuildConfig
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(EmergencyApiService::class.java)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideEmergencyWebSocketManager(
|
||||
okHttpClient: OkHttpClient,
|
||||
gson: Gson
|
||||
): EmergencyWebSocketManager {
|
||||
return EmergencyWebSocketManager(okHttpClient, gson)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideEmergencyMapper(): EmergencyMapper = EmergencyMapper()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAuthManager(): AuthManager {
|
||||
return AuthManagerImpl()
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideEmergencyRepository(
|
||||
apiService: EmergencyApiService,
|
||||
dao: EmergencyDao,
|
||||
webSocketManager: EmergencyWebSocketManager,
|
||||
mapper: EmergencyMapper,
|
||||
authManager: AuthManager
|
||||
): EmergencyRepository {
|
||||
return EmergencyRepositoryImpl(apiService, dao, webSocketManager, mapper, authManager)
|
||||
}
|
||||
|
||||
// Use Cases
|
||||
@Provides
|
||||
fun provideCreateEmergencyEventUseCase(
|
||||
repository: EmergencyRepository,
|
||||
connectivityManager: ConnectivityManager,
|
||||
deviceInfoProvider: DeviceInfoProvider
|
||||
): CreateEmergencyEventUseCase {
|
||||
return CreateEmergencyEventUseCase(repository, connectivityManager, deviceInfoProvider)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideGetNearbyEventsUseCase(repository: EmergencyRepository): GetNearbyEventsUseCase {
|
||||
return GetNearbyEventsUseCase(repository)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideGetNearbyUsersUseCase(repository: EmergencyRepository): GetNearbyUsersUseCase {
|
||||
return GetNearbyUsersUseCase(repository)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideRespondToEventUseCase(repository: EmergencyRepository): RespondToEventUseCase {
|
||||
return RespondToEventUseCase(repository)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideUpdateEventStatusUseCase(repository: EmergencyRepository): UpdateEventStatusUseCase {
|
||||
return UpdateEventStatusUseCase(repository)
|
||||
}
|
||||
|
||||
@Provides
|
||||
fun provideSyncLocalEventsUseCase(repository: EmergencyRepository): SyncLocalEventsUseCase {
|
||||
return SyncLocalEventsUseCase(repository)
|
||||
}
|
||||
|
||||
// Utilities
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideLocationManager(@ApplicationContext context: Context): LocationManager {
|
||||
return LocationManager(context)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideConnectivityManager(@ApplicationContext context: Context): ConnectivityManager {
|
||||
return ConnectivityManager(context)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDeviceInfoProvider(@ApplicationContext context: Context): DeviceInfoProvider {
|
||||
return DeviceInfoProvider(context)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun providePermissionManager(@ApplicationContext context: Context): PermissionManager {
|
||||
return PermissionManager(context)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideEmergencyNotificationManager(@ApplicationContext context: Context): EmergencyNotificationManager {
|
||||
return EmergencyNotificationManager(context)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package kr.smartsoltech.wellshe.emergency.domain.models
|
||||
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.EmergencyType
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.ResponseType
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus
|
||||
|
||||
// Domain models
|
||||
data class EmergencyEvent(
|
||||
val id: String,
|
||||
val userId: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val eventType: EmergencyType,
|
||||
val message: String?,
|
||||
val status: EmergencyStatus,
|
||||
val severity: Int,
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long,
|
||||
val expiresAt: Long,
|
||||
val distanceMeters: Double? = null,
|
||||
val userInfo: UserInfo? = null,
|
||||
val responseCount: Int = 0,
|
||||
val nearbyUsersNotified: Int? = null,
|
||||
val isLocal: Boolean = false
|
||||
)
|
||||
|
||||
data class EmergencyEventDetail(
|
||||
val id: String,
|
||||
val userId: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val eventType: EmergencyType,
|
||||
val message: String,
|
||||
val status: EmergencyStatus,
|
||||
val severity: Int,
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long,
|
||||
val expiresAt: Long,
|
||||
val responses: List<EventResponse>,
|
||||
val metadata: Map<String, Any>
|
||||
)
|
||||
|
||||
data class EventResponse(
|
||||
val id: String,
|
||||
val eventId: String,
|
||||
val responderId: String,
|
||||
val responseType: ResponseType,
|
||||
val message: String?,
|
||||
val estimatedArrival: Long?,
|
||||
val createdAt: Long,
|
||||
val responderInfo: UserInfo?
|
||||
)
|
||||
|
||||
data class UserInfo(
|
||||
val firstName: String,
|
||||
val age: Int?,
|
||||
val avatarUrl: String?
|
||||
)
|
||||
|
||||
data class NearbyUser(
|
||||
val userId: String,
|
||||
val firstName: String,
|
||||
val age: Int?,
|
||||
val avatarUrl: String?,
|
||||
val distanceMeters: Double,
|
||||
val isOnline: Boolean = true
|
||||
)
|
||||
|
||||
data class CreateEmergencyRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val eventType: EmergencyType,
|
||||
val message: String?,
|
||||
val severity: Int,
|
||||
val metadata: Map<String, Any> = emptyMap()
|
||||
)
|
||||
|
||||
data class EmergencyEventResponse(
|
||||
val eventId: String,
|
||||
val status: String,
|
||||
val nearbyUsersNotified: Int,
|
||||
val estimatedResponseTime: String?,
|
||||
val createdAt: String,
|
||||
val expiresAt: String
|
||||
) {
|
||||
companion object {
|
||||
fun fromLocal(localEvent: EmergencyEvent): EmergencyEventResponse {
|
||||
return EmergencyEventResponse(
|
||||
eventId = localEvent.id,
|
||||
status = "pending_sync",
|
||||
nearbyUsersNotified = 0,
|
||||
estimatedResponseTime = null,
|
||||
createdAt = localEvent.createdAt.toString(),
|
||||
expiresAt = localEvent.expiresAt.toString()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Re-export WebSocket models for domain layer
|
||||
typealias EventResponseNotification = kr.smartsoltech.wellshe.emergency.data.websocket.EventResponseNotification
|
||||
|
||||
// Расширенные domain модели для новой функциональности
|
||||
|
||||
// 1. Управление жизненным циклом событий
|
||||
data class EventUpdateDomain(
|
||||
val message: String?,
|
||||
val priority: String?, // low, medium, high, critical
|
||||
val additionalInfo: Map<String, Any>? = null
|
||||
)
|
||||
|
||||
data class EventNote(
|
||||
val id: String,
|
||||
val eventId: String,
|
||||
val authorId: String,
|
||||
val content: String,
|
||||
val noteType: String, // public, private, system
|
||||
val createdAt: Long,
|
||||
val updatedAt: Long
|
||||
)
|
||||
|
||||
data class EventTimeline(
|
||||
val eventId: String,
|
||||
val timeline: List<TimelineEntry>
|
||||
)
|
||||
|
||||
data class TimelineEntry(
|
||||
val id: String,
|
||||
val timestamp: Long,
|
||||
val status: String,
|
||||
val message: String?,
|
||||
val userInfo: UserInfo?,
|
||||
val eventType: String = "status_change"
|
||||
)
|
||||
|
||||
// 2. Система взаимодействия участников
|
||||
data class EventParticipant(
|
||||
val eventId: String,
|
||||
val userId: String,
|
||||
val userInfo: UserInfo,
|
||||
val role: ParticipantRole, // creator, responder, observer, invited
|
||||
val joinedAt: Long,
|
||||
val status: ParticipantStatus // active, left, removed
|
||||
)
|
||||
|
||||
enum class ParticipantRole {
|
||||
CREATOR, RESPONDER, OBSERVER, INVITED
|
||||
}
|
||||
|
||||
enum class ParticipantStatus {
|
||||
ACTIVE, LEFT, REMOVED, PENDING
|
||||
}
|
||||
|
||||
data class LocationShare(
|
||||
val id: String,
|
||||
val eventId: String,
|
||||
val userId: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val timestamp: Long,
|
||||
val accuracy: Float?,
|
||||
val isRealTime: Boolean = false
|
||||
)
|
||||
|
||||
// 3. Система коммуникации
|
||||
data class EventMessageDomain(
|
||||
val id: String,
|
||||
val eventId: String,
|
||||
val senderId: String,
|
||||
val content: String,
|
||||
val messageType: MessageType, // text, location, image, system
|
||||
val timestamp: Long,
|
||||
val senderInfo: UserInfo?,
|
||||
val metadata: Map<String, Any> = emptyMap()
|
||||
)
|
||||
|
||||
enum class MessageType {
|
||||
TEXT, LOCATION, IMAGE, SYSTEM, BROADCAST
|
||||
}
|
||||
|
||||
data class BroadcastMessage(
|
||||
val id: String,
|
||||
val eventId: String,
|
||||
val senderId: String,
|
||||
val message: String,
|
||||
val timestamp: Long,
|
||||
val recipientCount: Int,
|
||||
val deliveredCount: Int,
|
||||
val payload: Map<String, Any> = emptyMap()
|
||||
)
|
||||
|
||||
// 4. Мониторинг и аналитика
|
||||
data class EventStats(
|
||||
val totalEvents: Int,
|
||||
val activeEvents: Int,
|
||||
val resolvedEvents: Int,
|
||||
val escalatedEvents: Int,
|
||||
val cancelledEvents: Int,
|
||||
val averageResponseTime: Double,
|
||||
val period: String
|
||||
)
|
||||
|
||||
data class EventHeatmap(
|
||||
val center: LocationData,
|
||||
val radiusKm: Double,
|
||||
val events: List<HeatmapEventPoint>,
|
||||
val period: String
|
||||
)
|
||||
|
||||
data class LocationData(
|
||||
val latitude: Double,
|
||||
val longitude: Double
|
||||
)
|
||||
|
||||
data class HeatmapEventPoint(
|
||||
val eventId: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val intensity: Double,
|
||||
val eventType: EmergencyType,
|
||||
val timestamp: Long
|
||||
)
|
||||
|
||||
data class ResponseTimeAnalytics(
|
||||
val averageResponseTime: Double,
|
||||
val medianResponseTime: Double,
|
||||
val distribution: List<ResponseTimeBucket>,
|
||||
val period: String,
|
||||
val eventType: EmergencyType?
|
||||
)
|
||||
|
||||
data class ResponseTimeBucket(
|
||||
val timeRangeMinutes: String,
|
||||
val eventCount: Int,
|
||||
val percentage: Double
|
||||
)
|
||||
|
||||
data class EventFeedback(
|
||||
val id: String,
|
||||
val eventId: String,
|
||||
val userId: String,
|
||||
val rating: Int, // 1-5
|
||||
val comments: String?,
|
||||
val createdAt: Long,
|
||||
val categories: List<String> = emptyList() // helpful, fast, professional, etc.
|
||||
)
|
||||
|
||||
// Расширенные типы приоритетов
|
||||
enum class EventPriority {
|
||||
LOW, MEDIUM, HIGH, CRITICAL
|
||||
}
|
||||
|
||||
// Расширенные статусы событий
|
||||
enum class ExtendedEventStatus {
|
||||
CREATED, ACTIVE, ESCALATED, RESOLVED, CANCELLED, EXPIRED
|
||||
}
|
||||
|
||||
// ========== НОВЫЕ DOMAIN МОДЕЛИ ДЛЯ 100% ФУНКЦИОНАЛЬНОСТИ ==========
|
||||
|
||||
// Reports
|
||||
data class EmergencyReport(
|
||||
val id: String,
|
||||
val userId: String?,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val address: String?,
|
||||
val reportType: String,
|
||||
val description: String,
|
||||
val isAnonymous: Boolean,
|
||||
val severity: Int,
|
||||
val status: String,
|
||||
val createdAt: Long
|
||||
)
|
||||
|
||||
data class CreateReportRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val reportType: String,
|
||||
val description: String,
|
||||
val address: String? = null,
|
||||
val isAnonymous: Boolean = false,
|
||||
val severity: Int = 3
|
||||
)
|
||||
|
||||
// Safety Check
|
||||
data class SafetyCheck(
|
||||
val id: String,
|
||||
val userId: String,
|
||||
val message: String?,
|
||||
val latitude: Double?,
|
||||
val longitude: Double?,
|
||||
val createdAt: Long
|
||||
)
|
||||
|
||||
data class CreateSafetyCheckRequest(
|
||||
val message: String? = null,
|
||||
val latitude: Double? = null,
|
||||
val longitude: Double? = null
|
||||
)
|
||||
|
||||
// WebSocket Management
|
||||
data class WebSocketStats(
|
||||
val totalConnections: Int,
|
||||
val activeConnections: Int,
|
||||
val totalMessagesSent: Int,
|
||||
val uptimeSeconds: Int
|
||||
)
|
||||
|
||||
data class ConnectionStats(
|
||||
val totalConnections: Int,
|
||||
val activeConnections: Int,
|
||||
val connections: List<UserConnection>
|
||||
)
|
||||
|
||||
data class UserConnection(
|
||||
val userId: String,
|
||||
val connectedAt: Long,
|
||||
val lastPing: Long?
|
||||
)
|
||||
|
||||
// Map-related models
|
||||
data class MapEvent(
|
||||
val id: String,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val eventType: EmergencyType,
|
||||
val severity: Int,
|
||||
val createdAt: Long,
|
||||
val status: EmergencyStatus,
|
||||
val distance: Double? = null,
|
||||
val title: String,
|
||||
val description: String?
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
package kr.smartsoltech.wellshe.emergency.domain.repository
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.*
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus
|
||||
|
||||
interface EmergencyRepository {
|
||||
|
||||
// Emergency Events
|
||||
suspend fun createEmergencyEvent(request: CreateEmergencyRequest): Result<EmergencyEventResponse>
|
||||
suspend fun getNearbyEvents(latitude: Double, longitude: Double, radius: Int): Result<List<EmergencyEvent>>
|
||||
suspend fun getNearbyUsers(latitude: Double, longitude: Double, radius: Int): Result<List<NearbyUser>>
|
||||
suspend fun getEventDetails(eventId: String): Result<EmergencyEventDetail>
|
||||
suspend fun updateEventStatus(eventId: String, status: EmergencyStatus, note: String?): Result<Unit>
|
||||
suspend fun getUserEventHistory(limit: Int, offset: Int): Result<List<EmergencyEvent>>
|
||||
|
||||
// Local Events
|
||||
suspend fun saveLocalEmergencyEvent(request: CreateEmergencyRequest): EmergencyEvent
|
||||
suspend fun markEventAsSynced(localId: String, remoteId: String)
|
||||
suspend fun getUnsyncedEvents(): List<EmergencyEvent>
|
||||
suspend fun syncLocalEvents(): Result<Unit>
|
||||
|
||||
// Event Responses
|
||||
suspend fun respondToEvent(eventId: String, response: EventResponse): Result<Unit>
|
||||
suspend fun getEventResponses(eventId: String): Result<List<EventResponse>>
|
||||
|
||||
// Real-time streams
|
||||
fun getActiveEvents(): Flow<List<EmergencyEvent>>
|
||||
fun getEventResponses(): Flow<EventResponseNotification>
|
||||
|
||||
// Connection management
|
||||
fun connectWebSocket(userId: String, token: String)
|
||||
fun disconnectWebSocket()
|
||||
fun getConnectionStatus(): Flow<ConnectionStatus>
|
||||
|
||||
// Упрощенный набор методов, соответствующих реальному API
|
||||
suspend fun getEmergencyStats(): Result<EventStats>
|
||||
|
||||
// ========== НОВЫЕ МЕТОДЫ ДЛЯ 100% ФУНКЦИОНАЛЬНОСТИ ==========
|
||||
|
||||
// Reports Management
|
||||
suspend fun createEmergencyReport(request: CreateReportRequest): Result<EmergencyReport>
|
||||
suspend fun getEmergencyReports(): Result<List<EmergencyReport>>
|
||||
suspend fun getEmergencyReportsAdmin(): Result<List<EmergencyEvent>>
|
||||
|
||||
// Safety Check
|
||||
suspend fun createSafetyCheck(request: CreateSafetyCheckRequest): Result<SafetyCheck>
|
||||
suspend fun getSafetyChecks(): Result<List<SafetyCheck>>
|
||||
|
||||
// Enhanced Alert Management
|
||||
suspend fun createAlert(latitude: Double, longitude: Double, alertType: String, message: String?): Result<EmergencyEventResponse>
|
||||
suspend fun updateAlert(alertId: String, message: String?, isResolved: Boolean?): Result<EmergencyEventResponse>
|
||||
suspend fun resolveAlert(alertId: String): Result<Unit>
|
||||
suspend fun getMyAlerts(): Result<List<EmergencyEvent>>
|
||||
suspend fun getActiveAlerts(): Result<List<EmergencyEvent>>
|
||||
suspend fun getAlertResponses(alertId: String): Result<List<EventResponse>>
|
||||
|
||||
// WebSocket Management
|
||||
suspend fun getWebSocketStats(): Result<WebSocketStats>
|
||||
suspend fun getConnectionStats(): Result<ConnectionStats>
|
||||
suspend fun pingWebSocketConnections(): Result<Unit>
|
||||
suspend fun broadcastTestMessage(message: String): Result<Unit>
|
||||
|
||||
// Map and Location
|
||||
suspend fun getNearbyEventsForMap(latitude: Double, longitude: Double, radiusKm: Double = 10.0): Result<List<MapEvent>>
|
||||
suspend fun getEventsInRadius(latitude: Double, longitude: Double, radiusKm: Double = 1.0): Result<List<EmergencyEvent>>
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package kr.smartsoltech.wellshe.emergency.domain.usecases
|
||||
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.*
|
||||
import kr.smartsoltech.wellshe.emergency.domain.repository.EmergencyRepository
|
||||
import kr.smartsoltech.wellshe.emergency.utils.ConnectivityManager
|
||||
import kr.smartsoltech.wellshe.emergency.utils.DeviceInfoProvider
|
||||
import javax.inject.Inject
|
||||
|
||||
class CreateEmergencyEventUseCase @Inject constructor(
|
||||
private val repository: EmergencyRepository,
|
||||
private val connectivityManager: ConnectivityManager,
|
||||
private val deviceInfoProvider: DeviceInfoProvider
|
||||
) {
|
||||
suspend operator fun invoke(request: CreateEmergencyRequest): Result<EmergencyEventResponse> {
|
||||
return try {
|
||||
// Check connectivity
|
||||
if (!connectivityManager.isNetworkAvailable()) {
|
||||
// Save locally if no connection
|
||||
val localEvent = repository.saveLocalEmergencyEvent(request)
|
||||
return Result.success(EmergencyEventResponse.fromLocal(localEvent))
|
||||
}
|
||||
|
||||
// Try to create remote event
|
||||
repository.createEmergencyEvent(request)
|
||||
} catch (e: Exception) {
|
||||
// Fallback to local storage
|
||||
val localEvent = repository.saveLocalEmergencyEvent(request)
|
||||
Result.success(EmergencyEventResponse.fromLocal(localEvent))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package kr.smartsoltech.wellshe.emergency.domain.usecases
|
||||
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.*
|
||||
import kr.smartsoltech.wellshe.emergency.domain.repository.EmergencyRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
class GetNearbyEventsUseCase @Inject constructor(
|
||||
private val repository: EmergencyRepository
|
||||
) {
|
||||
suspend operator fun invoke(
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
radius: Int
|
||||
): Result<List<EmergencyEvent>> {
|
||||
return repository.getNearbyEvents(latitude, longitude, radius)
|
||||
}
|
||||
}
|
||||
|
||||
class GetNearbyUsersUseCase @Inject constructor(
|
||||
private val repository: EmergencyRepository
|
||||
) {
|
||||
suspend operator fun invoke(
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
radius: Int
|
||||
): Result<List<NearbyUser>> {
|
||||
return repository.getNearbyUsers(latitude, longitude, radius)
|
||||
}
|
||||
}
|
||||
|
||||
class RespondToEventUseCase @Inject constructor(
|
||||
private val repository: EmergencyRepository
|
||||
) {
|
||||
suspend operator fun invoke(
|
||||
eventId: String,
|
||||
response: EventResponse
|
||||
): Result<Unit> {
|
||||
return repository.respondToEvent(eventId, response)
|
||||
}
|
||||
}
|
||||
|
||||
class UpdateEventStatusUseCase @Inject constructor(
|
||||
private val repository: EmergencyRepository
|
||||
) {
|
||||
suspend operator fun invoke(
|
||||
eventId: String,
|
||||
status: kr.smartsoltech.wellshe.emergency.data.models.EmergencyStatus,
|
||||
note: String?
|
||||
): Result<Unit> {
|
||||
return repository.updateEventStatus(eventId, status, note)
|
||||
}
|
||||
}
|
||||
|
||||
class SyncLocalEventsUseCase @Inject constructor(
|
||||
private val repository: EmergencyRepository
|
||||
) {
|
||||
suspend operator fun invoke(): Result<Unit> {
|
||||
return repository.syncLocalEvents()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package kr.smartsoltech.wellshe.emergency.domain.usecases
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.*
|
||||
import kr.smartsoltech.wellshe.emergency.domain.repository.EmergencyRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
class ObserveEmergencyAlertsUseCase @Inject constructor(
|
||||
private val repository: EmergencyRepository
|
||||
) {
|
||||
operator fun invoke(): Flow<List<EmergencyEvent>> {
|
||||
return repository.getActiveEvents()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,824 @@
|
||||
package kr.smartsoltech.wellshe.emergency.presentation.screens
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.compose.animation.core.*
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material.icons.automirrored.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import kr.smartsoltech.wellshe.BuildConfig
|
||||
import kr.smartsoltech.wellshe.emergency.debug.AuthTester
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.EmergencyEvent
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.EmergencyType
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.ResponseType
|
||||
import kr.smartsoltech.wellshe.emergency.presentation.viewmodels.EmergencyViewModel
|
||||
import kr.smartsoltech.wellshe.emergency.presentation.viewmodels.EmergencyUiState
|
||||
import com.google.accompanist.permissions.*
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.core.content.ContextCompat
|
||||
import android.content.pm.PackageManager
|
||||
|
||||
@OptIn(ExperimentalPermissionsApi::class)
|
||||
@Composable
|
||||
fun EmergencyScreen(
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: EmergencyViewModel = hiltViewModel(),
|
||||
onNavigateToMap: () -> Unit = {},
|
||||
onNavigateToHistory: () -> Unit = {}
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val uiState by viewModel.uiState.collectAsState(initial = EmergencyUiState())
|
||||
val emergencyEvents by viewModel.emergencyEvents.collectAsState(initial = emptyList())
|
||||
val connectionStatus by viewModel.connectionStatus.collectAsState(initial = kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus.DISCONNECTED)
|
||||
|
||||
// Запрашиваем только foreground-пермишены здесь; background location требует отдельного UX/потока
|
||||
val locationPermissions = rememberMultiplePermissionsState(
|
||||
listOf(
|
||||
android.Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
android.Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
)
|
||||
)
|
||||
|
||||
val powerManager = context.getSystemService(PowerManager::class.java)
|
||||
val isIgnoringBatteryOptimizations = powerManager?.isIgnoringBatteryOptimizations(context.packageName) == true
|
||||
|
||||
LaunchedEffect(locationPermissions.allPermissionsGranted) {
|
||||
viewModel.onPermissionsResult(locationPermissions.allPermissionsGranted)
|
||||
}
|
||||
|
||||
val openAppSettings: () -> Unit = {
|
||||
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
|
||||
data = Uri.fromParts("package", context.packageName, null)
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
}
|
||||
context.startActivity(intent)
|
||||
}
|
||||
|
||||
// Sync permissions state on start and when returning to the screen (e.g., user changed them in system settings)
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
|
||||
// Initial check
|
||||
LaunchedEffect(Unit) {
|
||||
val hasLocationNow = ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
android.Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
android.Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
viewModel.onPermissionsResult(hasLocationNow)
|
||||
}
|
||||
|
||||
// Observe resume to re-check permissions if user returned from system settings
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) {
|
||||
val hasLocationNow = ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
android.Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
android.Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
viewModel.onPermissionsResult(hasLocationNow)
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
|
||||
EmergencyScreenContent(
|
||||
modifier = modifier,
|
||||
uiState = uiState,
|
||||
emergencyEvents = emergencyEvents,
|
||||
connectionStatus = connectionStatus,
|
||||
onSOSClick = { viewModel.createSOS() },
|
||||
onCustomAlert = { type, message, severity ->
|
||||
viewModel.createCustomAlert(type, message, severity)
|
||||
},
|
||||
onEventRespond = { eventId, responseType ->
|
||||
viewModel.respondToEvent(eventId, responseType)
|
||||
},
|
||||
onRefresh = { viewModel.refreshNearbyEvents() },
|
||||
onClearSOSNotifications = { viewModel.clearSOSNotifications() },
|
||||
onNavigateToMap = onNavigateToMap,
|
||||
onNavigateToHistory = onNavigateToHistory,
|
||||
onRequestPermissions = {
|
||||
if (locationPermissions.shouldShowRationale || !locationPermissions.allPermissionsGranted) {
|
||||
locationPermissions.launchMultiplePermissionRequest()
|
||||
} else {
|
||||
openAppSettings()
|
||||
}
|
||||
},
|
||||
onRequestBatteryOptimization = {
|
||||
val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
|
||||
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
context.startActivity(intent)
|
||||
},
|
||||
isIgnoringBatteryOptimizations = isIgnoringBatteryOptimizations,
|
||||
onClearSuccess = { viewModel.clearSuccessMessage() },
|
||||
onClearError = { viewModel.clearErrorMessage() }
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmergencyScreenContent(
|
||||
modifier: Modifier = Modifier,
|
||||
uiState: EmergencyUiState,
|
||||
emergencyEvents: List<EmergencyEvent>,
|
||||
connectionStatus: kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus,
|
||||
onSOSClick: () -> Unit,
|
||||
onCustomAlert: (EmergencyType, String?, Int) -> Unit,
|
||||
onEventRespond: (String, ResponseType) -> Unit,
|
||||
onRefresh: () -> Unit,
|
||||
onClearSOSNotifications: () -> Unit,
|
||||
onNavigateToMap: () -> Unit,
|
||||
onNavigateToHistory: () -> Unit,
|
||||
onRequestPermissions: () -> Unit,
|
||||
onRequestBatteryOptimization: () -> Unit,
|
||||
isIgnoringBatteryOptimizations: Boolean,
|
||||
onClearSuccess: () -> Unit,
|
||||
onClearError: () -> Unit
|
||||
) {
|
||||
// Вычисляем состояние разрешений и логируем ВНЕ LazyColumn — внутри лямбды контента LazyColumn
|
||||
// нельзя вызывать composition locals, поэтому LocalContext.current нужно вызывать здесь.
|
||||
val localContext = LocalContext.current
|
||||
val hasLocationNow = ContextCompat.checkSelfPermission(
|
||||
localContext,
|
||||
android.Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
|
||||
localContext,
|
||||
android.Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
val effectivePermissionsGranted = uiState.permissionsGranted || hasLocationNow
|
||||
|
||||
// Debug log to show why UI may still require permissions
|
||||
Log.d(
|
||||
"EmergencyScreen",
|
||||
"ui.permissionsGranted=${uiState.permissionsGranted}, hasLocationNow=$hasLocationNow, effectivePermissionsGranted=$effectivePermissionsGranted"
|
||||
)
|
||||
Log.i(
|
||||
"EmergencyScreen",
|
||||
"effectivePermissionsGranted=$effectivePermissionsGranted (uiState.permissionsGranted=${uiState.permissionsGranted}, hasLocationNow=$hasLocationNow)"
|
||||
)
|
||||
|
||||
// Extra visibility in logs when permissions are missing
|
||||
if (!effectivePermissionsGranted) {
|
||||
Log.w(
|
||||
"EmergencyScreen",
|
||||
"Permissions not granted — PermissionRequestCard will be shown. Check app/system settings or request flow."
|
||||
)
|
||||
}
|
||||
|
||||
// Вынесем scope сюда — вызов rememberCoroutineScope() должен происходить в контексте @Composable, но не внутри LazyListScope (контента LazyColumn)
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
LazyColumn(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
// Connection Status Indicator
|
||||
item {
|
||||
ConnectionStatusIndicator(connectionStatus)
|
||||
}
|
||||
|
||||
if (!effectivePermissionsGranted) {
|
||||
item {
|
||||
PermissionRequestCard(onRequestPermissions)
|
||||
}
|
||||
}
|
||||
// Battery Optimization Request
|
||||
if (!isIgnoringBatteryOptimizations) {
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Для корректной работы SOS и фоновых событий отключите оптимизацию батареи для приложения",
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
fontSize = 14.sp
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Button(onClick = onRequestBatteryOptimization, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Отключить оптимизацию батареи")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SOS Button - главный элемент
|
||||
item {
|
||||
SOSButton(
|
||||
isPressed = uiState.sosButtonPressed,
|
||||
isLoading = uiState.isCreatingEmergency,
|
||||
enabled = effectivePermissionsGranted,
|
||||
onClick = onSOSClick
|
||||
)
|
||||
}
|
||||
|
||||
// Quick Actions
|
||||
item {
|
||||
QuickActionsRow(
|
||||
onMapClick = onNavigateToMap,
|
||||
onHistoryClick = onNavigateToHistory,
|
||||
onRefresh = onRefresh,
|
||||
onClearNotifications = onClearSOSNotifications,
|
||||
isLoading = uiState.isLoadingNearbyEvents
|
||||
)
|
||||
}
|
||||
|
||||
// Custom Alert Options
|
||||
item {
|
||||
CustomAlertSection(
|
||||
enabled = effectivePermissionsGranted && !uiState.isCreatingEmergency,
|
||||
onCustomAlert = onCustomAlert
|
||||
)
|
||||
}
|
||||
|
||||
// Active Emergency Events
|
||||
if (emergencyEvents.isNotEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
text = "🚨 Экстренные ситуации рядом (${emergencyEvents.size})",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
|
||||
items(emergencyEvents, key = { it.id }) { event ->
|
||||
EmergencyEventCard(
|
||||
event = event,
|
||||
onRespond = { responseType -> onEventRespond(event.id, responseType) }
|
||||
)
|
||||
}
|
||||
} else if (!uiState.isLoadingNearbyEvents) {
|
||||
item {
|
||||
EmptyStateCard()
|
||||
}
|
||||
}
|
||||
|
||||
// Loading indicator
|
||||
if (uiState.isLoadingNearbyEvents) {
|
||||
item {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Debug: кнопка запуска теста правильной аутентификации и WebSocket
|
||||
if (BuildConfig.DEBUG) {
|
||||
item {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch {
|
||||
try {
|
||||
val result = AuthTester.runFullTest(localContext)
|
||||
Log.i("EmergencyScreen", "AuthTester.runFullTest result=$result")
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyScreen", "AuthTester error: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
}, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("DEBUG: Run auth & WS test")
|
||||
}
|
||||
|
||||
OutlinedButton(onClick = onClearSOSNotifications, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("DEBUG: Clear SOS notifications")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle UI Effects
|
||||
HandleUIEffects(uiState, onClearSuccess, onClearError)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SOSButton(
|
||||
isPressed: Boolean,
|
||||
isLoading: Boolean,
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val scale by animateFloatAsState(
|
||||
targetValue = if (isPressed) 0.95f else 1f,
|
||||
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
|
||||
label = "sosButtonScale"
|
||||
)
|
||||
|
||||
val glowAnimation by rememberInfiniteTransition(label = "sosGlow").animateFloat(
|
||||
initialValue = 0.8f,
|
||||
targetValue = 1f,
|
||||
animationSpec = infiniteRepeatable(
|
||||
animation = tween(1000),
|
||||
repeatMode = RepeatMode.Reverse
|
||||
),
|
||||
label = "sosGlowAlpha"
|
||||
)
|
||||
|
||||
Button(
|
||||
onClick = onClick,
|
||||
enabled = enabled && !isLoading,
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.height(140.dp)
|
||||
.scale(scale),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = if (isPressed) Color(0xFFB71C1C) else Color.Red,
|
||||
contentColor = Color.White,
|
||||
disabledContainerColor = Color.Gray
|
||||
),
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
elevation = ButtonDefaults.buttonElevation(
|
||||
defaultElevation = if (isPressed) 4.dp else 12.dp
|
||||
)
|
||||
) {
|
||||
if (isLoading) {
|
||||
CircularProgressIndicator(
|
||||
color = Color.White,
|
||||
modifier = Modifier.size(48.dp),
|
||||
strokeWidth = 4.dp
|
||||
)
|
||||
} else {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Warning,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(64.dp),
|
||||
tint = Color.White.copy(alpha = if (enabled) glowAnimation else 0.5f)
|
||||
)
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(
|
||||
text = "SOS",
|
||||
fontSize = 36.sp,
|
||||
fontWeight = FontWeight.ExtraBold,
|
||||
letterSpacing = 4.sp
|
||||
)
|
||||
Text(
|
||||
text = if (enabled) "Нажмите для экстренного вызова" else "Необходимы разрешения",
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
color = Color.White.copy(alpha = 0.9f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ConnectionStatusIndicator(
|
||||
status: kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val (color, text, icon) = when (status) {
|
||||
kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus.CONNECTED ->
|
||||
Triple(Color.Green, "Подключено", Icons.Default.Wifi)
|
||||
kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus.CONNECTING ->
|
||||
Triple(Color(0xFFFF9800), "Подключение...", Icons.Default.WifiFind)
|
||||
kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus.DISCONNECTED ->
|
||||
Triple(Color.Red, "Отключено", Icons.Default.WifiOff)
|
||||
kr.smartsoltech.wellshe.emergency.data.models.ConnectionStatus.RECONNECTING ->
|
||||
Triple(Color(0xFFFF9800), "Переподключение...", Icons.Default.Refresh)
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = color.copy(alpha = 0.1f)
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
tint = color,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Real-time: $text",
|
||||
color = color,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun PermissionRequestCard(
|
||||
onRequestPermissions: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp)
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.LocationOff,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Требуются разрешения",
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "Для работы экстренных сигналов необходим доступ к геолокации",
|
||||
fontSize = 14.sp,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
)
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Button(
|
||||
onClick = onRequestPermissions,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text("Предоставить разрешения")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun QuickActionsRow(
|
||||
onMapClick: () -> Unit,
|
||||
onHistoryClick: () -> Unit,
|
||||
onRefresh: () -> Unit,
|
||||
onClearNotifications: () -> Unit = {},
|
||||
isLoading: Boolean,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
QuickActionButton(
|
||||
icon = Icons.Default.Map,
|
||||
text = "Карта",
|
||||
onClick = onMapClick,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
QuickActionButton(
|
||||
icon = Icons.Default.History,
|
||||
text = "История",
|
||||
onClick = onHistoryClick,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
QuickActionButton(
|
||||
icon = if (isLoading) Icons.Default.Refresh else Icons.Default.Refresh,
|
||||
text = "Обновить",
|
||||
onClick = onRefresh,
|
||||
modifier = Modifier.weight(1f),
|
||||
enabled = !isLoading
|
||||
)
|
||||
QuickActionButton(
|
||||
icon = Icons.Default.Clear,
|
||||
text = "Очистить SOS",
|
||||
onClick = onClearNotifications,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun QuickActionButton(
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
text: String,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
modifier = modifier.height(56.dp)
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Text(
|
||||
text = text,
|
||||
fontSize = 10.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CustomAlertSection(
|
||||
enabled: Boolean,
|
||||
onCustomAlert: (EmergencyType, String?, Int) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "Другие типы сигналов",
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 16.sp
|
||||
)
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
CustomAlertButton(
|
||||
text = "Преследование",
|
||||
icon = Icons.AutoMirrored.Filled.DirectionsRun,
|
||||
color = Color(0xFFFF5722),
|
||||
enabled = enabled,
|
||||
onClick = { onCustomAlert(EmergencyType.STALKING, "Меня преследуют", 4) },
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
CustomAlertButton(
|
||||
text = "Домогательство",
|
||||
icon = Icons.Default.Block,
|
||||
color = Color(0xFFE91E63),
|
||||
enabled = enabled,
|
||||
onClick = { onCustomAlert(EmergencyType.HARASSMENT, "Домогательство", 3) },
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CustomAlertButton(
|
||||
text: String,
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
color: Color,
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
modifier = modifier.height(72.dp),
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
contentColor = color
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(24.dp),
|
||||
tint = if (enabled) color else Color.Gray
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = text,
|
||||
fontSize = 11.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
color = if (enabled) color else Color.Gray
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EmergencyEventCard(
|
||||
event: EmergencyEvent,
|
||||
onRespond: (ResponseType) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.1f)
|
||||
),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.Top
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = when (event.eventType) {
|
||||
EmergencyType.SOS -> Icons.Default.Warning
|
||||
EmergencyType.HARASSMENT -> Icons.Default.Block
|
||||
EmergencyType.STALKING -> Icons.AutoMirrored.Filled.DirectionsRun
|
||||
EmergencyType.MEDICAL -> Icons.Default.LocalHospital
|
||||
EmergencyType.FIRE -> Icons.Default.Whatshot
|
||||
EmergencyType.ACCIDENT -> Icons.Default.CarCrash
|
||||
EmergencyType.OTHER -> Icons.AutoMirrored.Filled.Help
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = Color.Red,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = event.eventType.name,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = Color.Red
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
|
||||
event.userInfo?.let { userInfo ->
|
||||
Text(
|
||||
text = "${userInfo.firstName}${userInfo.age?.let { ", $it лет" } ?: ""}",
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
}
|
||||
|
||||
if (!event.message.isNullOrBlank()) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = event.message,
|
||||
fontSize = 14.sp,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
event.distanceMeters?.let { distance ->
|
||||
Text(
|
||||
text = "${distance.toInt()}м",
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(event.createdAt)),
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Button(
|
||||
onClick = { onRespond(ResponseType.ON_WAY) },
|
||||
modifier = Modifier.weight(1f),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Directions,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Помочь", fontSize = 12.sp)
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = { onRespond(ResponseType.CALLED_POLICE) },
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Phone,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("112", fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EmptyStateCard(
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Security,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(48.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text(
|
||||
text = "Все спокойно",
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 18.sp
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "В данный момент нет активных экстренных ситуаций в вашем районе",
|
||||
textAlign = TextAlign.Center,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun HandleUIEffects(
|
||||
uiState: EmergencyUiState,
|
||||
onClearSuccess: () -> Unit,
|
||||
onClearError: () -> Unit
|
||||
) {
|
||||
LaunchedEffect(uiState.showSuccessMessage) {
|
||||
if (uiState.showSuccessMessage && !uiState.successMessage.isNullOrBlank()) {
|
||||
// Show success message
|
||||
onClearSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(uiState.errorMessage) {
|
||||
if (!uiState.errorMessage.isNullOrBlank()) {
|
||||
// Show error message
|
||||
onClearError()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package kr.smartsoltech.wellshe.emergency.presentation.viewmodels
|
||||
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.launch
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.*
|
||||
import kr.smartsoltech.wellshe.emergency.domain.usecases.*
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.*
|
||||
import kr.smartsoltech.wellshe.emergency.utils.PermissionManager
|
||||
import kr.smartsoltech.wellshe.emergency.utils.EmergencyNotificationManager
|
||||
import kr.smartsoltech.wellshe.emergency.domain.repository.EmergencyRepository
|
||||
import kr.smartsoltech.wellshe.data.storage.TokenManager
|
||||
import kr.smartsoltech.wellshe.data.local.AuthTokenRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class EmergencyViewModel @Inject constructor(
|
||||
private val createEmergencyUseCase: CreateEmergencyEventUseCase,
|
||||
private val getNearbyEventsUseCase: GetNearbyEventsUseCase,
|
||||
private val respondToEventUseCase: RespondToEventUseCase,
|
||||
private val observeEmergencyAlertsUseCase: ObserveEmergencyAlertsUseCase,
|
||||
private val repository: EmergencyRepository,
|
||||
private val permissionManager: PermissionManager,
|
||||
private val notificationManager: EmergencyNotificationManager,
|
||||
private val tokenManager: TokenManager,
|
||||
private val authTokenRepository: AuthTokenRepository
|
||||
) : ViewModel() {
|
||||
|
||||
private val _uiState = MutableStateFlow(EmergencyUiState())
|
||||
val uiState: StateFlow<EmergencyUiState> = _uiState.asStateFlow()
|
||||
|
||||
private val _emergencyEvents = MutableStateFlow<List<EmergencyEvent>>(emptyList())
|
||||
val emergencyEvents: StateFlow<List<EmergencyEvent>> = _emergencyEvents.asStateFlow()
|
||||
|
||||
val connectionStatus = repository.getConnectionStatus()
|
||||
|
||||
init {
|
||||
initializeEmergencyModule()
|
||||
}
|
||||
|
||||
private fun initializeEmergencyModule() {
|
||||
viewModelScope.launch {
|
||||
// Проверить разрешения
|
||||
checkRequiredPermissions()
|
||||
|
||||
// Попытка получить реальный токен и подключиться по WebSocket
|
||||
// Предпочитаем TokenManager (свежий in-memory токен), затем DataStore-backed auth token
|
||||
val dsToken = authTokenRepository.authToken.firstOrNull()
|
||||
val tmToken = tokenManager.getAccessToken()
|
||||
|
||||
// Если в DataStore остался временный плейсхолдер вроде "temp_token_for_...", игнорируем его
|
||||
// Игнорируем placeholder в обоих хранилищах
|
||||
val effectiveTmToken = if (!tmToken.isNullOrEmpty() && !tmToken.startsWith("temp_token_for_")) tmToken else null
|
||||
val effectiveDsToken = if (!dsToken.isNullOrEmpty() && !dsToken.startsWith("temp_token_for_")) dsToken else null
|
||||
|
||||
if (tmToken != null && tmToken.startsWith("temp_token_for_")) {
|
||||
Log.w("EmergencyVM", "TokenManager contains placeholder token; ignoring for WS connect: $tmToken")
|
||||
}
|
||||
if (dsToken != null && dsToken.startsWith("temp_token_for_")) {
|
||||
Log.w("EmergencyVM", "DataStore contains placeholder token; ignoring for WS connect: $dsToken")
|
||||
}
|
||||
|
||||
val token = effectiveTmToken ?: effectiveDsToken
|
||||
|
||||
if (!token.isNullOrEmpty()) {
|
||||
Log.d("EmergencyVM", "Connecting WebSocket with masked token: ${token.take(6)}... (source=${if (!tmToken.isNullOrEmpty()) "TokenManager" else "DataStore"})")
|
||||
repository.connectWebSocket("current_user_id", token)
|
||||
} else {
|
||||
Log.d("EmergencyVM", "No access token available — пропускаем авто-подключение WebSocket")
|
||||
}
|
||||
|
||||
// Подписаться на алерты
|
||||
observeEmergencyAlerts()
|
||||
|
||||
// Загрузить ближайшие события
|
||||
refreshNearbyEvents()
|
||||
|
||||
// Синхронизировать локальные события
|
||||
syncLocalEvents()
|
||||
}
|
||||
}
|
||||
|
||||
fun createSOS(message: String? = null) {
|
||||
viewModelScope.launch {
|
||||
if (!permissionManager.hasLocationPermission()) {
|
||||
_uiState.value = _uiState.value.copy(
|
||||
errorMessage = "Необходимо разрешение на геолокацию"
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
_uiState.value = _uiState.value.copy(
|
||||
isCreatingEmergency = true,
|
||||
sosButtonPressed = true,
|
||||
errorMessage = null
|
||||
)
|
||||
|
||||
Log.d("EmergencyVM", "Calling createEmergencyUseCase...")
|
||||
|
||||
// Создаем правильный объект CreateEmergencyRequest
|
||||
val request = CreateEmergencyRequest(
|
||||
latitude = 0.0, // TODO: получить реальные координаты
|
||||
longitude = 0.0,
|
||||
eventType = EmergencyType.SOS,
|
||||
message = message,
|
||||
severity = 5
|
||||
)
|
||||
|
||||
createEmergencyUseCase(request).fold(
|
||||
onSuccess = { response ->
|
||||
Log.i("EmergencyVM", "SOS created successfully: eventId=${response.eventId}, nearbyUsers=${response.nearbyUsersNotified}")
|
||||
|
||||
_uiState.value = _uiState.value.copy(
|
||||
isCreatingEmergency = false,
|
||||
sosButtonPressed = false,
|
||||
lastEmergencyId = response.eventId,
|
||||
showSuccessMessage = true,
|
||||
successMessage = "SOS отправлен! Уведомлено ${response.nearbyUsersNotified} пользователей"
|
||||
)
|
||||
|
||||
// Показать уведомление
|
||||
try {
|
||||
viewModelScope.launch {
|
||||
notificationManager.showSOSCreatedNotification(response)
|
||||
}
|
||||
Log.d("EmergencyVM", "SOS notification shown")
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyVM", "Error showing SOS notification: ${e.message}", e)
|
||||
}
|
||||
|
||||
// Обновить список событий
|
||||
Log.d("EmergencyVM", "Refreshing nearby events after SOS creation")
|
||||
refreshNearbyEvents()
|
||||
},
|
||||
onFailure = { error ->
|
||||
Log.e("EmergencyVM", "Failed to create SOS: ${error.message}", error)
|
||||
|
||||
val userFriendlyMessage = when {
|
||||
error.message?.contains("геолокац") == true -> "Не удалось получить вашу геолокацию"
|
||||
error.message?.contains("auth token") == true -> "Ошибка авторизации. Попробуйте войти заново"
|
||||
error.message?.contains("API Error: 401") == true -> "Сессия истекла. Необходимо войти заново"
|
||||
error.message?.contains("API Error: 403") == true -> "Доступ запрещён. Проверьте права доступа"
|
||||
error.message?.contains("API Error: 500") == true -> "Ошибка сервера. Попробуйте позже"
|
||||
error.message?.contains("network") == true -> "Проблемы с сетью. Проверьте подключение к интернету"
|
||||
else -> "Ошибка отправки SOS: ${error.message}"
|
||||
}
|
||||
|
||||
_uiState.value = _uiState.value.copy(
|
||||
isCreatingEmergency = false,
|
||||
sosButtonPressed = false,
|
||||
errorMessage = userFriendlyMessage
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun createCustomAlert(eventType: EmergencyType, message: String?, severity: Int) {
|
||||
viewModelScope.launch {
|
||||
if (!permissionManager.hasLocationPermission()) {
|
||||
_uiState.value = _uiState.value.copy(
|
||||
errorMessage = "Необходимо разрешение на геолокацию"
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
_uiState.value = _uiState.value.copy(isCreatingEmergency = true)
|
||||
|
||||
val request = CreateEmergencyRequest(
|
||||
latitude = 0.0, // TODO: получить реальные координаты
|
||||
longitude = 0.0,
|
||||
eventType = eventType,
|
||||
message = message,
|
||||
severity = severity
|
||||
)
|
||||
|
||||
createEmergencyUseCase(request).fold(
|
||||
onSuccess = { response ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
isCreatingEmergency = false,
|
||||
showSuccessMessage = true,
|
||||
successMessage = "Сигнал ${eventType.name} отправлен"
|
||||
)
|
||||
refreshNearbyEvents()
|
||||
},
|
||||
onFailure = { error ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
isCreatingEmergency = false,
|
||||
errorMessage = error.message
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun respondToEvent(eventId: String, responseType: ResponseType = ResponseType.ON_WAY, message: String? = null) {
|
||||
viewModelScope.launch {
|
||||
val response = EventResponse(
|
||||
id = "",
|
||||
eventId = eventId,
|
||||
responderId = "current_user", // TODO: получить реальный ID
|
||||
responseType = responseType,
|
||||
message = message,
|
||||
estimatedArrival = null,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
responderInfo = null
|
||||
)
|
||||
|
||||
respondToEventUseCase(eventId, response).fold(
|
||||
onSuccess = {
|
||||
_uiState.value = _uiState.value.copy(
|
||||
showSuccessMessage = true,
|
||||
successMessage = "Ваш ответ отправлен"
|
||||
)
|
||||
},
|
||||
onFailure = { error ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
errorMessage = "Ошибка отправки ответа: ${error.message}"
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshNearbyEvents() {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = _uiState.value.copy(isLoadingNearbyEvents = true)
|
||||
|
||||
// TODO: получить реальные координаты пользователя
|
||||
getNearbyEventsUseCase(0.0, 0.0, 1000).fold(
|
||||
onSuccess = { events ->
|
||||
_emergencyEvents.value = events
|
||||
_uiState.value = _uiState.value.copy(isLoadingNearbyEvents = false)
|
||||
},
|
||||
onFailure = { error ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
isLoadingNearbyEvents = false,
|
||||
errorMessage = "Ошибка загрузки событий: ${error.message}"
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun observeEmergencyAlerts() {
|
||||
viewModelScope.launch {
|
||||
observeEmergencyAlertsUseCase().collect { events ->
|
||||
_emergencyEvents.value = events
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkRequiredPermissions() {
|
||||
val hasLocation = permissionManager.hasLocationPermission()
|
||||
val hasNotifications = permissionManager.hasNotificationPermission()
|
||||
// For enabling SOS we require location permissions (foreground). Notification permission is optional.
|
||||
val permissionsGranted = hasLocation
|
||||
|
||||
// Log for debugging why UI may show permissions required
|
||||
try {
|
||||
Log.d("EmergencyVM", "Permissions check — location=$hasLocation, notifications=$hasNotifications -> ui.permissionsGranted=$permissionsGranted")
|
||||
} catch (_: Exception) {
|
||||
// ignore logging errors
|
||||
}
|
||||
|
||||
_uiState.value = _uiState.value.copy(permissionsGranted = permissionsGranted)
|
||||
}
|
||||
|
||||
private fun syncLocalEvents() {
|
||||
viewModelScope.launch {
|
||||
repository.syncLocalEvents()
|
||||
}
|
||||
}
|
||||
|
||||
fun clearSuccessMessage() {
|
||||
_uiState.value = _uiState.value.copy(
|
||||
showSuccessMessage = false,
|
||||
successMessage = null
|
||||
)
|
||||
}
|
||||
|
||||
fun clearErrorMessage() {
|
||||
_uiState.value = _uiState.value.copy(errorMessage = null)
|
||||
}
|
||||
|
||||
// Метод для ручной очистки SOS уведомлений
|
||||
fun clearSOSNotifications() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
notificationManager.clearSOSNotifications()
|
||||
Log.d("EmergencyVM", "SOS notifications cleared successfully")
|
||||
|
||||
_uiState.value = _uiState.value.copy(
|
||||
showSuccessMessage = true,
|
||||
successMessage = "SOS уведомления очищены"
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyVM", "Error clearing SOS notifications: ${e.message}", e)
|
||||
_uiState.value = _uiState.value.copy(
|
||||
errorMessage = "Ошибка при очистке уведомлений: ${e.message}"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Метод для очистки всех экстренных уведомлений
|
||||
fun clearAllEmergencyNotifications() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
notificationManager.cancelAllEmergencyNotifications()
|
||||
Log.d("EmergencyVM", "All emergency notifications cleared successfully")
|
||||
|
||||
_uiState.value = _uiState.value.copy(
|
||||
showSuccessMessage = true,
|
||||
successMessage = "Все экстренные уведомления очищены"
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyVM", "Error clearing all emergency notifications: ${e.message}", e)
|
||||
_uiState.value = _uiState.value.copy(
|
||||
errorMessage = "Ошибка при очистке всех уведомлений: ${e.message}"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onPermissionsResult(granted: Boolean) {
|
||||
_uiState.value = _uiState.value.copy(permissionsGranted = granted)
|
||||
}
|
||||
}
|
||||
|
||||
data class EmergencyUiState(
|
||||
val isCreatingEmergency: Boolean = false,
|
||||
val sosButtonPressed: Boolean = false,
|
||||
val lastEmergencyId: String? = null,
|
||||
val showSuccessMessage: Boolean = false,
|
||||
val successMessage: String? = null,
|
||||
val errorMessage: String? = null,
|
||||
val isLoadingNearbyEvents: Boolean = false,
|
||||
val permissionsGranted: Boolean = false
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
package kr.smartsoltech.wellshe.emergency.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.Build
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class ConnectivityManager @Inject constructor(
|
||||
@ApplicationContext private val context: Context
|
||||
) {
|
||||
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
|
||||
fun isNetworkAvailable(): Boolean {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
val network = connectivityManager.activeNetwork ?: return false
|
||||
val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
|
||||
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val networkInfo = connectivityManager.activeNetworkInfo
|
||||
networkInfo?.isConnected == true
|
||||
}
|
||||
}
|
||||
|
||||
fun getNetworkType(): String {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
val network = connectivityManager.activeNetwork ?: return "none"
|
||||
val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return "none"
|
||||
|
||||
return when {
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "wifi"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "cellular"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "ethernet"
|
||||
else -> "other"
|
||||
}
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val networkInfo = connectivityManager.activeNetworkInfo
|
||||
return networkInfo?.typeName?.lowercase() ?: "none"
|
||||
}
|
||||
}
|
||||
|
||||
fun isWifiConnected(): Boolean {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
val network = connectivityManager.activeNetwork ?: return false
|
||||
val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
|
||||
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val networkInfo = connectivityManager.activeNetworkInfo
|
||||
return networkInfo?.type == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package kr.smartsoltech.wellshe.emergency.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kr.smartsoltech.wellshe.BuildConfig
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class DeviceInfoProvider @Inject constructor(
|
||||
@ApplicationContext private val context: Context
|
||||
) {
|
||||
|
||||
fun getBatteryLevel(): Int {
|
||||
val batteryIntent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
val level = batteryIntent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
|
||||
val scale = batteryIntent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
|
||||
|
||||
return if (level != -1 && scale != -1) {
|
||||
(level * 100 / scale.toFloat()).toInt()
|
||||
} else {
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
fun getAppVersion(): String {
|
||||
return try {
|
||||
BuildConfig.VERSION_NAME
|
||||
} catch (e: Exception) {
|
||||
"unknown"
|
||||
}
|
||||
}
|
||||
|
||||
fun getDeviceInfo(): Map<String, String> {
|
||||
return mapOf(
|
||||
"model" to Build.MODEL,
|
||||
"manufacturer" to Build.MANUFACTURER,
|
||||
"android_version" to Build.VERSION.RELEASE,
|
||||
"sdk_int" to Build.VERSION.SDK_INT.toString(),
|
||||
"device" to Build.DEVICE,
|
||||
"product" to Build.PRODUCT
|
||||
)
|
||||
}
|
||||
|
||||
fun isLowPowerMode(): Boolean {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
val powerManager = context.getSystemService(Context.POWER_SERVICE) as android.os.PowerManager
|
||||
powerManager.isPowerSaveMode
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package kr.smartsoltech.wellshe.emergency.utils
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.EventResponse
|
||||
import kr.smartsoltech.wellshe.emergency.data.models.ResponseType
|
||||
|
||||
class EmergencyActionReceiver : BroadcastReceiver() {
|
||||
|
||||
private val receiverScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val eventId = intent.getStringExtra("event_id")
|
||||
val userName = intent.getStringExtra("user_name")
|
||||
|
||||
Log.d("EmergencyActionReceiver", "Received action: ${intent.action} for event: $eventId")
|
||||
|
||||
when (intent.action) {
|
||||
"HELP_ACTION" -> {
|
||||
handleHelpAction(context, eventId, userName)
|
||||
}
|
||||
"CALL_POLICE_ACTION" -> {
|
||||
handleCallPoliceAction(context, eventId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleHelpAction(context: Context, eventId: String?, userName: String?) {
|
||||
if (eventId.isNullOrEmpty()) {
|
||||
Log.e("EmergencyActionReceiver", "Event ID is null or empty for help action")
|
||||
return
|
||||
}
|
||||
|
||||
receiverScope.launch {
|
||||
try {
|
||||
// Получаем репозиторий через Application context
|
||||
val appContext = context.applicationContext as kr.smartsoltech.wellshe.WellSheApplication
|
||||
val emergencyRepository = appContext.emergencyRepository
|
||||
|
||||
// Создаем правильный объект EventResponse для отправки ответа на событие
|
||||
val response = EventResponse(
|
||||
id = "",
|
||||
eventId = eventId,
|
||||
responderId = "current_user", // TODO: получить реальный ID пользователя
|
||||
responseType = ResponseType.ON_WAY,
|
||||
message = "Иду на помощь",
|
||||
estimatedArrival = null,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
responderInfo = null
|
||||
)
|
||||
|
||||
// Отправляем ответ на событие
|
||||
emergencyRepository.respondToEvent(eventId, response)
|
||||
|
||||
Log.i("EmergencyActionReceiver", "Help response sent for event: $eventId")
|
||||
|
||||
// Показываем уведомление об успешном ответе
|
||||
showResponseConfirmation(context, "Ваш ответ отправлен! Вы идете на помощь ${userName ?: "пользователю"}")
|
||||
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyActionReceiver", "Failed to send help response for event: $eventId", e)
|
||||
showResponseConfirmation(context, "Ошибка отправки ответа: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleCallPoliceAction(context: Context, eventId: String?) {
|
||||
if (eventId.isNullOrEmpty()) {
|
||||
Log.e("EmergencyActionReceiver", "Event ID is null or empty for police call action")
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// Номер экстренных служб (можно настроить в зависимости от страны)
|
||||
val emergencyNumber = "102" // Полиция в России
|
||||
|
||||
val callIntent = Intent(Intent.ACTION_CALL).apply {
|
||||
data = Uri.parse("tel:$emergencyNumber")
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
}
|
||||
|
||||
context.startActivity(callIntent)
|
||||
|
||||
Log.i("EmergencyActionReceiver", "Emergency call initiated for event: $eventId")
|
||||
|
||||
// Отправляем информацию о том, что была вызвана полиция
|
||||
receiverScope.launch {
|
||||
try {
|
||||
// Получаем репозиторий через Application context
|
||||
val appContext = context.applicationContext as kr.smartsoltech.wellshe.WellSheApplication
|
||||
val emergencyRepository = appContext.emergencyRepository
|
||||
|
||||
val response = EventResponse(
|
||||
id = "",
|
||||
eventId = eventId,
|
||||
responderId = "current_user", // TODO: получить реальный ID пользователя
|
||||
responseType = ResponseType.CALLED_POLICE,
|
||||
message = "Вызвана полиция",
|
||||
estimatedArrival = null,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
responderInfo = null
|
||||
)
|
||||
|
||||
emergencyRepository.respondToEvent(eventId, response)
|
||||
showResponseConfirmation(context, "Полиция вызвана")
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyActionReceiver", "Failed to send police call response", e)
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e: SecurityException) {
|
||||
Log.e("EmergencyActionReceiver", "Permission denied for making phone calls", e)
|
||||
showResponseConfirmation(context, "Нет разрешения для совершения звонков")
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyActionReceiver", "Failed to initiate emergency call", e)
|
||||
showResponseConfirmation(context, "Ошибка при попытке вызвать полицию: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun showResponseConfirmation(context: Context, message: String) {
|
||||
// Можно показать Toast или отдельное уведомление
|
||||
try {
|
||||
android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||
} catch (e: Exception) {
|
||||
Log.e("EmergencyActionReceiver", "Failed to show response confirmation", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
package kr.smartsoltech.wellshe.emergency.utils
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.media.AudioAttributes
|
||||
import android.media.RingtoneManager
|
||||
import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import android.content.pm.PackageManager
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kr.smartsoltech.wellshe.R
|
||||
import kr.smartsoltech.wellshe.emergency.data.websocket.EmergencyAlert
|
||||
import kr.smartsoltech.wellshe.emergency.domain.models.EmergencyEventResponse
|
||||
import kr.smartsoltech.wellshe.MainActivity
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class EmergencyNotificationManager @Inject constructor(
|
||||
@ApplicationContext private val context: Context
|
||||
) {
|
||||
companion object {
|
||||
const val EMERGENCY_CHANNEL_ID = "emergency_alerts"
|
||||
const val SOS_CHANNEL_ID = "sos_notifications"
|
||||
const val GENERAL_CHANNEL_ID = "general_emergency"
|
||||
|
||||
// Группировка уведомлений
|
||||
const val EMERGENCY_GROUP_KEY = "emergency_group"
|
||||
const val SOS_GROUP_KEY = "sos_group"
|
||||
|
||||
const val NOTIFICATION_ID_EMERGENCY_ALERT = 1001
|
||||
const val NOTIFICATION_ID_SOS_CREATED = 1002
|
||||
const val NOTIFICATION_ID_SOS_SUMMARY = 1003
|
||||
const val NOTIFICATION_ID_EMERGENCY_SUMMARY = 1004
|
||||
|
||||
// Время жизни SOS уведомлений
|
||||
private const val SOS_NOTIFICATION_LIFETIME_MS = 10 * 60 * 1000L // 10 минут
|
||||
private const val AUTO_CLEANUP_INTERVAL_MS = 2 * 60 * 1000L // Проверка каждые 2 минуты
|
||||
}
|
||||
|
||||
private val notificationManager = NotificationManagerCompat.from(context)
|
||||
private val mutex = Mutex()
|
||||
|
||||
// CoroutineScope для фоновых задач
|
||||
private val notificationScope = CoroutineScope(SupervisorJob())
|
||||
|
||||
// Хранение активных SOS событий для группировки
|
||||
private val activeSosEvents = mutableMapOf<String, SOSEventInfo>()
|
||||
|
||||
data class SOSEventInfo(
|
||||
val eventId: String,
|
||||
val response: EmergencyEventResponse,
|
||||
val timestamp: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
init {
|
||||
createNotificationChannels()
|
||||
startAutomaticCleanup()
|
||||
}
|
||||
|
||||
// Автоматическая очистка старых SOS уведомлений
|
||||
private fun startAutomaticCleanup() {
|
||||
notificationScope.launch {
|
||||
while (true) {
|
||||
delay(AUTO_CLEANUP_INTERVAL_MS)
|
||||
cleanupOldSOSNotifications()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun cleanupOldSOSNotifications() {
|
||||
mutex.withLock {
|
||||
val currentTime = System.currentTimeMillis()
|
||||
val expiredEvents = activeSosEvents.filter {
|
||||
currentTime - it.value.timestamp > SOS_NOTIFICATION_LIFETIME_MS
|
||||
}
|
||||
|
||||
if (expiredEvents.isNotEmpty()) {
|
||||
expiredEvents.forEach { (eventId, _) ->
|
||||
activeSosEvents.remove(eventId)
|
||||
// Отменяем индивидуальное уведомление
|
||||
notificationManager.cancel(eventId.hashCode())
|
||||
}
|
||||
|
||||
// Обновляем группированное уведомление или убираем его если событий больше нет
|
||||
when (activeSosEvents.size) {
|
||||
0 -> {
|
||||
notificationManager.cancel(NOTIFICATION_ID_SOS_CREATED)
|
||||
notificationManager.cancel(NOTIFICATION_ID_SOS_SUMMARY)
|
||||
}
|
||||
1 -> {
|
||||
// Показываем одиночное уведомление вместо группы
|
||||
val singleEvent = activeSosEvents.values.first()
|
||||
showSingleSOSNotification(singleEvent.response)
|
||||
notificationManager.cancel(NOTIFICATION_ID_SOS_SUMMARY)
|
||||
}
|
||||
else -> {
|
||||
// Обновляем группированное уведомление
|
||||
showGroupedSOSNotification()
|
||||
}
|
||||
}
|
||||
|
||||
android.util.Log.d("EmergencyNotificationManager",
|
||||
"Cleaned up ${expiredEvents.size} expired SOS notifications. " +
|
||||
"Active events remaining: ${activeSosEvents.size}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createNotificationChannels() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val emergencyChannel = NotificationChannel(
|
||||
EMERGENCY_CHANNEL_ID,
|
||||
"Экстренные уведомления",
|
||||
NotificationManager.IMPORTANCE_HIGH
|
||||
).apply {
|
||||
description = "Критически важные уведомления об экстренных ситуациях"
|
||||
enableLights(true)
|
||||
lightColor = Color.RED
|
||||
enableVibration(true)
|
||||
vibrationPattern = longArrayOf(0, 1000, 500, 1000, 500, 1000)
|
||||
setSound(
|
||||
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM),
|
||||
AudioAttributes.Builder()
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.setUsage(AudioAttributes.USAGE_ALARM)
|
||||
.build()
|
||||
)
|
||||
}
|
||||
|
||||
val sosChannel = NotificationChannel(
|
||||
SOS_CHANNEL_ID,
|
||||
"SOS уведомления",
|
||||
NotificationManager.IMPORTANCE_DEFAULT
|
||||
).apply {
|
||||
description = "Подтверждения отправки SOS сигналов"
|
||||
enableLights(true)
|
||||
lightColor = Color.BLUE
|
||||
}
|
||||
|
||||
val generalChannel = NotificationChannel(
|
||||
GENERAL_CHANNEL_ID,
|
||||
"Общие уведомления",
|
||||
NotificationManager.IMPORTANCE_DEFAULT
|
||||
).apply {
|
||||
description = "Общие уведомления модуля безопасности"
|
||||
}
|
||||
|
||||
val systemNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
systemNotificationManager.createNotificationChannel(emergencyChannel)
|
||||
systemNotificationManager.createNotificationChannel(sosChannel)
|
||||
systemNotificationManager.createNotificationChannel(generalChannel)
|
||||
}
|
||||
}
|
||||
|
||||
fun showCriticalEmergencyAlert(alert: EmergencyAlert) {
|
||||
val intent = Intent(context, MainActivity::class.java).apply {
|
||||
putExtra("navigate_to", "emergency")
|
||||
putExtra("emergency_event_id", alert.eventId)
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
alert.eventId.hashCode(),
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
|
||||
val notification = NotificationCompat.Builder(context, EMERGENCY_CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_emergency_24)
|
||||
.setContentTitle("🚨 ЭКСТРЕННАЯ СИТУАЦИЯ")
|
||||
.setContentText("${alert.userInfo.firstName} нуждается в помощи (${alert.distanceMeters}м)")
|
||||
.setStyle(
|
||||
NotificationCompat.BigTextStyle()
|
||||
.bigText("${alert.userInfo.firstName} (${alert.userInfo.age ?: "неизвестен"} лет) сообщает: ${alert.message}\n\nРасстояние: ${alert.distanceMeters}м\nУровень опасности: ${alert.severity}/5")
|
||||
)
|
||||
.setPriority(NotificationCompat.PRIORITY_MAX)
|
||||
.setCategory(NotificationCompat.CATEGORY_ALARM)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
|
||||
.setVibrate(longArrayOf(0, 1000, 500, 1000, 500, 1000))
|
||||
.setLights(Color.RED, 1000, 500)
|
||||
.setGroup(EMERGENCY_GROUP_KEY)
|
||||
.addAction(createHelpAction(alert.eventId, alert.userInfo.firstName))
|
||||
.addAction(createCallPoliceAction(alert.eventId))
|
||||
.build()
|
||||
|
||||
notificationManager.notify(alert.eventId.hashCode(), notification)
|
||||
}
|
||||
|
||||
suspend fun showSOSCreatedNotification(response: EmergencyEventResponse) {
|
||||
mutex.withLock {
|
||||
// Добавляем новое SOS событие
|
||||
activeSosEvents[response.eventId] = SOSEventInfo(response.eventId, response)
|
||||
|
||||
// Очищаем старые события (старше 5 минут)
|
||||
val fiveMinutesAgo = System.currentTimeMillis() - 5 * 60 * 1000
|
||||
activeSosEvents.entries.removeAll { it.value.timestamp < fiveMinutesAgo }
|
||||
|
||||
when (activeSosEvents.size) {
|
||||
1 -> showSingleSOSNotification(response)
|
||||
else -> showGroupedSOSNotification()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun showSingleSOSNotification(response: EmergencyEventResponse) {
|
||||
val intent = Intent(context, MainActivity::class.java).apply {
|
||||
putExtra("navigate_to", "emergency")
|
||||
putExtra("emergency_event_id", response.eventId)
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
response.eventId.hashCode(),
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val notification = NotificationCompat.Builder(context, SOS_CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_check_circle_24)
|
||||
.setContentTitle("✅ SOS отправлен")
|
||||
.setContentText("Уведомлено ${response.nearbyUsersNotified} пользователей поблизости")
|
||||
.setStyle(
|
||||
NotificationCompat.BigTextStyle()
|
||||
.bigText("Ваш SOS сигнал успешно отправлен!\n\nУведомлено пользователей: ${response.nearbyUsersNotified}\nВремя ответа: ${response.estimatedResponseTime ?: "неизвестно"}\n\nИдентификатор: ${response.eventId}")
|
||||
)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setColor(Color.GREEN)
|
||||
.setGroup(SOS_GROUP_KEY)
|
||||
.build()
|
||||
|
||||
notificationManager.notify(NOTIFICATION_ID_SOS_CREATED, notification)
|
||||
}
|
||||
|
||||
private fun showGroupedSOSNotification() {
|
||||
val totalEvents = activeSosEvents.size
|
||||
val totalNotifiedUsers = activeSosEvents.values.sumOf { it.response.nearbyUsersNotified }
|
||||
|
||||
val intent = Intent(context, MainActivity::class.java).apply {
|
||||
putExtra("navigate_to", "emergency")
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
NOTIFICATION_ID_SOS_SUMMARY,
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
// Создаем индивидуальные уведомления для группировки
|
||||
activeSosEvents.values.forEachIndexed { index, sosEvent ->
|
||||
val individualNotification = NotificationCompat.Builder(context, SOS_CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_check_circle_24)
|
||||
.setContentTitle("SOS #${index + 1}")
|
||||
.setContentText("Уведомлено ${sosEvent.response.nearbyUsersNotified} пользователей")
|
||||
.setGroup(SOS_GROUP_KEY)
|
||||
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
|
||||
.build()
|
||||
|
||||
notificationManager.notify(sosEvent.eventId.hashCode(), individualNotification)
|
||||
}
|
||||
|
||||
// Создаем summary уведомление
|
||||
val inboxStyle = NotificationCompat.InboxStyle()
|
||||
.setBigContentTitle("✅ Отправлено $totalEvents SOS сигналов")
|
||||
.setSummaryText("Всего уведомлено $totalNotifiedUsers пользователей")
|
||||
|
||||
activeSosEvents.values.forEach { sosEvent ->
|
||||
inboxStyle.addLine("SOS ${sosEvent.eventId.take(8)}: ${sosEvent.response.nearbyUsersNotified} уведомлений")
|
||||
}
|
||||
|
||||
val summaryNotification = NotificationCompat.Builder(context, SOS_CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_check_circle_24)
|
||||
.setContentTitle("✅ Отправлено $totalEvents SOS сигналов")
|
||||
.setContentText("Всего уведомлено $totalNotifiedUsers пользователей поблизости")
|
||||
.setStyle(inboxStyle)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setColor(Color.GREEN)
|
||||
.setGroup(SOS_GROUP_KEY)
|
||||
.setGroupSummary(true)
|
||||
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
|
||||
.build()
|
||||
|
||||
notificationManager.notify(NOTIFICATION_ID_SOS_SUMMARY, summaryNotification)
|
||||
}
|
||||
|
||||
// Метод для показа группированных emergency уведомлений
|
||||
fun showGroupedEmergencyAlert(alerts: List<EmergencyAlert>) {
|
||||
if (alerts.isEmpty()) return
|
||||
|
||||
val intent = Intent(context, MainActivity::class.java).apply {
|
||||
putExtra("navigate_to", "emergency")
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
NOTIFICATION_ID_EMERGENCY_SUMMARY,
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
|
||||
if (alerts.size == 1) {
|
||||
showCriticalEmergencyAlert(alerts.first())
|
||||
return
|
||||
}
|
||||
|
||||
// Создаем индивидуальные уведомления для группировки
|
||||
alerts.forEach { alert ->
|
||||
val individualNotification = NotificationCompat.Builder(context, EMERGENCY_CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_emergency_24)
|
||||
.setContentTitle("🚨 ${alert.userInfo.firstName}")
|
||||
.setContentText("${alert.distanceMeters}м - ${alert.message}")
|
||||
.setGroup(EMERGENCY_GROUP_KEY)
|
||||
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
|
||||
.build()
|
||||
|
||||
notificationManager.notify(alert.eventId.hashCode(), individualNotification)
|
||||
}
|
||||
|
||||
// Создаем summary уведомление
|
||||
val inboxStyle = NotificationCompat.InboxStyle()
|
||||
.setBigContentTitle("🚨 ${alerts.size} экстренных ситуаций")
|
||||
.setSummaryText("Нажмите для просмотра всех событий")
|
||||
|
||||
alerts.take(5).forEach { alert ->
|
||||
inboxStyle.addLine("${alert.userInfo.firstName} (${alert.distanceMeters}м): ${alert.message}")
|
||||
}
|
||||
|
||||
if (alerts.size > 5) {
|
||||
inboxStyle.addLine("И еще ${alerts.size - 5} событий...")
|
||||
}
|
||||
|
||||
val summaryNotification = NotificationCompat.Builder(context, EMERGENCY_CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_emergency_24)
|
||||
.setContentTitle("🚨 ${alerts.size} экстренных ситуаций")
|
||||
.setContentText("Несколько человек нуждаются в помощи поблизости")
|
||||
.setStyle(inboxStyle)
|
||||
.setPriority(NotificationCompat.PRIORITY_MAX)
|
||||
.setCategory(NotificationCompat.CATEGORY_ALARM)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
|
||||
.setVibrate(longArrayOf(0, 1000, 500, 1000, 500, 1000))
|
||||
.setLights(Color.RED, 1000, 500)
|
||||
.setGroup(EMERGENCY_GROUP_KEY)
|
||||
.setGroupSummary(true)
|
||||
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
|
||||
.build()
|
||||
|
||||
notificationManager.notify(NOTIFICATION_ID_EMERGENCY_SUMMARY, summaryNotification)
|
||||
}
|
||||
|
||||
// Метод для очистки группированных SOS уведомлений
|
||||
suspend fun clearSOSNotifications() {
|
||||
mutex.withLock {
|
||||
activeSosEvents.clear()
|
||||
notificationManager.cancel(NOTIFICATION_ID_SOS_CREATED)
|
||||
notificationManager.cancel(NOTIFICATION_ID_SOS_SUMMARY)
|
||||
}
|
||||
}
|
||||
|
||||
private fun createHelpAction(eventId: String, userName: String): NotificationCompat.Action {
|
||||
val intent = Intent(context, EmergencyActionReceiver::class.java).apply {
|
||||
action = "HELP_ACTION"
|
||||
putExtra("event_id", eventId)
|
||||
putExtra("user_name", userName)
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
eventId.hashCode(),
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
return NotificationCompat.Action.Builder(
|
||||
R.drawable.ic_directions_24,
|
||||
"Помочь",
|
||||
pendingIntent
|
||||
).build()
|
||||
}
|
||||
|
||||
private fun createCallPoliceAction(eventId: String): NotificationCompat.Action {
|
||||
val intent = Intent(context, EmergencyActionReceiver::class.java).apply {
|
||||
action = "CALL_POLICE_ACTION"
|
||||
putExtra("event_id", eventId)
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
("police_" + eventId).hashCode(),
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
return NotificationCompat.Action.Builder(
|
||||
R.drawable.ic_phone_24,
|
||||
"Вызвать полицию",
|
||||
pendingIntent
|
||||
).build()
|
||||
}
|
||||
|
||||
fun cancelNotification(notificationId: Int) {
|
||||
notificationManager.cancel(notificationId)
|
||||
}
|
||||
|
||||
fun cancelAllEmergencyNotifications() {
|
||||
notificationManager.cancelAll()
|
||||
}
|
||||
|
||||
// Получить информацию об активных SOS событиях
|
||||
suspend fun getActiveSOSEventsInfo(): List<SOSEventInfo> {
|
||||
return mutex.withLock {
|
||||
activeSosEvents.values.toList()
|
||||
}
|
||||
}
|
||||
|
||||
// Получить количество активных SOS событий
|
||||
suspend fun getActiveSOSEventsCount(): Int {
|
||||
return mutex.withLock {
|
||||
activeSosEvents.size
|
||||
}
|
||||
}
|
||||
|
||||
// Принудительная очистка всех индивидуальных SOS уведомлений
|
||||
suspend fun clearAllSOSIndividualNotifications() {
|
||||
mutex.withLock {
|
||||
activeSosEvents.keys.forEach { eventId ->
|
||||
notificationManager.cancel(eventId.hashCode())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Обновить существующие групповые SOS уведомления
|
||||
suspend fun refreshSOSNotifications() {
|
||||
mutex.withLock {
|
||||
// Сначала очищаем старые события
|
||||
val currentTime = System.currentTimeMillis()
|
||||
activeSosEvents.entries.removeAll {
|
||||
currentTime - it.value.timestamp > SOS_NOTIFICATION_LIFETIME_MS
|
||||
}
|
||||
|
||||
// Затем показываем актуальные уведомления
|
||||
when (activeSosEvents.size) {
|
||||
0 -> {
|
||||
notificationManager.cancel(NOTIFICATION_ID_SOS_CREATED)
|
||||
notificationManager.cancel(NOTIFICATION_ID_SOS_SUMMARY)
|
||||
}
|
||||
1 -> {
|
||||
val singleEvent = activeSosEvents.values.first()
|
||||
showSingleSOSNotification(singleEvent.response)
|
||||
notificationManager.cancel(NOTIFICATION_ID_SOS_SUMMARY)
|
||||
}
|
||||
else -> showGroupedSOSNotification()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка разрешений на уведомления
|
||||
fun areNotificationsEnabled(): Boolean {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val channel = notificationManager.getNotificationChannel(EMERGENCY_CHANNEL_ID)
|
||||
channel != null && channel.importance != NotificationManager.IMPORTANCE_NONE
|
||||
} else {
|
||||
// Для версий ниже Oreo проверяем общее разрешение на уведомления
|
||||
val pm = context.packageManager
|
||||
val appOps = pm.getApplicationEnabledSetting(context.packageName)
|
||||
appOps == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package kr.smartsoltech.wellshe.emergency.utils
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.Location
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import androidx.core.app.ActivityCompat
|
||||
import com.google.android.gms.location.*
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
@Singleton
|
||||
class LocationManager @Inject constructor(
|
||||
@ApplicationContext private val context: Context
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "LocationManager"
|
||||
}
|
||||
|
||||
private val fusedLocationClient: FusedLocationProviderClient by lazy {
|
||||
LocationServices.getFusedLocationProviderClient(context)
|
||||
}
|
||||
|
||||
suspend fun getCurrentLocation(): Location? {
|
||||
return getCurrentLocationWithTimeout(8000) // 8 seconds default
|
||||
}
|
||||
|
||||
suspend fun getCurrentLocationWithTimeout(timeoutMs: Long): Location? {
|
||||
if (!hasLocationPermission()) {
|
||||
Log.e(TAG, "Location permission not granted")
|
||||
throw SecurityException("Location permission not granted")
|
||||
}
|
||||
|
||||
Log.d(TAG, "Requesting location with timeout ${timeoutMs}ms")
|
||||
|
||||
// Сначала попытаемся получить последнюю известную локацию
|
||||
val lastKnownLocation = getLastKnownLocation()
|
||||
Log.d(TAG, "Last known location: $lastKnownLocation")
|
||||
|
||||
// Попробуем получить свежую локацию
|
||||
val freshLocation = try {
|
||||
withTimeoutOrNull(timeoutMs) {
|
||||
requestFreshLocation()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error getting fresh location: ${e.message}", e)
|
||||
null
|
||||
}
|
||||
|
||||
return when {
|
||||
freshLocation != null -> {
|
||||
Log.d(TAG, "Got fresh location: lat=${freshLocation.latitude}, lng=${freshLocation.longitude}")
|
||||
freshLocation
|
||||
}
|
||||
lastKnownLocation != null -> {
|
||||
Log.d(TAG, "Using last known location: lat=${lastKnownLocation.latitude}, lng=${lastKnownLocation.longitude}")
|
||||
lastKnownLocation
|
||||
}
|
||||
else -> {
|
||||
Log.e(TAG, "No location available")
|
||||
throw Exception("Не удалось получить геолокацию. Проверьте настройки GPS и попробуйте снова.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getLastKnownLocation(): Location? {
|
||||
return try {
|
||||
suspendCancellableCoroutine { continuation ->
|
||||
fusedLocationClient.lastLocation
|
||||
.addOnSuccessListener { location ->
|
||||
continuation.resume(location)
|
||||
}
|
||||
.addOnFailureListener { exception ->
|
||||
Log.e(TAG, "Failed to get last known location", exception)
|
||||
continuation.resume(null)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Exception getting last known location", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun requestFreshLocation(): Location? {
|
||||
return suspendCancellableCoroutine { continuation ->
|
||||
val locationRequest = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 1000)
|
||||
.setMaxUpdates(1)
|
||||
.build()
|
||||
|
||||
val locationCallback = object : LocationCallback() {
|
||||
override fun onLocationResult(result: LocationResult) {
|
||||
val location = result.lastLocation
|
||||
if (location != null && !continuation.isCompleted) {
|
||||
Log.d(TAG, "Fresh location received: ${location.latitude}, ${location.longitude}")
|
||||
continuation.resume(location)
|
||||
fusedLocationClient.removeLocationUpdates(this)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLocationAvailability(availability: LocationAvailability) {
|
||||
if (!availability.isLocationAvailable && !continuation.isCompleted) {
|
||||
Log.d(TAG, "Location not available from provider")
|
||||
continuation.resume(null)
|
||||
fusedLocationClient.removeLocationUpdates(this)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Log.d(TAG, "Starting location updates")
|
||||
fusedLocationClient.requestLocationUpdates(
|
||||
locationRequest,
|
||||
locationCallback,
|
||||
Looper.getMainLooper()
|
||||
)
|
||||
|
||||
continuation.invokeOnCancellation {
|
||||
Log.d(TAG, "Location request cancelled")
|
||||
fusedLocationClient.removeLocationUpdates(locationCallback)
|
||||
}
|
||||
} catch (e: SecurityException) {
|
||||
Log.e(TAG, "Security exception requesting location", e)
|
||||
continuation.resumeWithException(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun hasLocationPermission(): Boolean {
|
||||
return ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED ||
|
||||
ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
|
||||
val results = FloatArray(1)
|
||||
Location.distanceBetween(lat1, lon1, lat2, lon2, results)
|
||||
return results[0].toDouble()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package kr.smartsoltech.wellshe.emergency.utils
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.core.app.ActivityCompat
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class PermissionManager @Inject constructor(
|
||||
@ApplicationContext private val context: Context
|
||||
) {
|
||||
|
||||
fun hasLocationPermission(): Boolean {
|
||||
return ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED ||
|
||||
ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
fun hasNotificationPermission(): Boolean {
|
||||
return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
|
||||
ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.POST_NOTIFICATIONS
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
} else {
|
||||
true // Notifications are allowed by default on older versions
|
||||
}
|
||||
}
|
||||
|
||||
fun hasPhonePermission(): Boolean {
|
||||
return ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.CALL_PHONE
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
fun getAllRequiredPermissions(): List<String> {
|
||||
val permissions = mutableListOf(
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
)
|
||||
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
|
||||
permissions.add(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
|
||||
return permissions
|
||||
}
|
||||
|
||||
fun getMissingPermissions(): List<String> {
|
||||
return getAllRequiredPermissions().filter { permission ->
|
||||
ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
}
|
||||
|
||||
fun hasAllRequiredPermissions(): Boolean {
|
||||
return getMissingPermissions().isEmpty()
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,8 @@ abstract class JournalDatabase : RoomDatabase() {
|
||||
context.applicationContext,
|
||||
JournalDatabase::class.java,
|
||||
"journal_database"
|
||||
).build()
|
||||
).fallbackToDestructiveMigration()
|
||||
.build()
|
||||
INSTANCE = instance
|
||||
instance
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package kr.smartsoltech.wellshe.model.auth
|
||||
|
||||
/**
|
||||
* Модель для запроса авторизации
|
||||
*/
|
||||
data class AuthRequest(
|
||||
val username: String? = null,
|
||||
val email: String? = null,
|
||||
val password: String
|
||||
)
|
||||
|
||||
// Создаем типоним для совместимости
|
||||
typealias LoginRequest = AuthRequest
|
||||
|
||||
/**
|
||||
* Модель для запроса регистрации
|
||||
*/
|
||||
data class RegisterRequest(
|
||||
val email: String,
|
||||
val username: String,
|
||||
val password: String,
|
||||
val first_name: String,
|
||||
val last_name: String,
|
||||
val phone: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель для запроса обновления токена
|
||||
*/
|
||||
data class TokenRefreshRequest(
|
||||
val refresh_token: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель для запроса выхода из системы
|
||||
*/
|
||||
data class LogoutRequest(
|
||||
val refresh_token: String? = null
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
package kr.smartsoltech.wellshe.model.auth
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
/**
|
||||
* Базовая модель ответа от API
|
||||
*/
|
||||
sealed class ApiResponse<T>
|
||||
|
||||
/**
|
||||
* Успешный ответ от API
|
||||
*/
|
||||
data class SuccessResponse<T>(
|
||||
val status: String,
|
||||
val data: T,
|
||||
val message: String? = null
|
||||
) : ApiResponse<T>()
|
||||
|
||||
/**
|
||||
* Ответ с ошибкой от API
|
||||
*/
|
||||
data class ErrorResponse<T>(
|
||||
val status: String,
|
||||
val code: String,
|
||||
val message: String,
|
||||
val details: Map<String, List<String>>? = null
|
||||
) : ApiResponse<T>()
|
||||
|
||||
/**
|
||||
* Модель ответа при успешной авторизации
|
||||
*/
|
||||
data class AuthTokenResponse(
|
||||
@SerializedName("access_token") val accessToken: String,
|
||||
@SerializedName("refresh_token") val refreshToken: String,
|
||||
@SerializedName("token_type") val tokenType: String,
|
||||
@SerializedName("expires_in") val expiresIn: Int
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель ответа при обновлении токена
|
||||
*/
|
||||
data class TokenRefreshResponse(
|
||||
@SerializedName("access_token") val accessToken: String,
|
||||
@SerializedName("token_type") val tokenType: String,
|
||||
@SerializedName("expires_in") val expiresIn: Int
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель ответа при регистрации
|
||||
*/
|
||||
data class RegisterResponse(
|
||||
@SerializedName("user_id") val userId: String,
|
||||
val username: String,
|
||||
val email: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Типонимы для обеспечения совместимости с кодом
|
||||
*/
|
||||
typealias AuthResponse = AuthTokenResponse
|
||||
typealias TokenResponse = TokenRefreshResponse
|
||||
@@ -0,0 +1,11 @@
|
||||
package kr.smartsoltech.wellshe.model.auth
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
/**
|
||||
* Модель прямого ответа авторизации от сервера, без обертки data
|
||||
*/
|
||||
data class DirectAuthResponse(
|
||||
@SerializedName("access_token") val accessToken: String,
|
||||
@SerializedName("token_type") val tokenType: String
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
package kr.smartsoltech.wellshe.model.auth
|
||||
|
||||
// Файл больше не используется
|
||||
// Типонимы перенесены в AuthResponse.kt
|
||||
@@ -0,0 +1,39 @@
|
||||
package kr.smartsoltech.wellshe.model.auth
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
/**
|
||||
* Базовая обертка для ответа API
|
||||
*/
|
||||
open class BaseResponseWrapper(
|
||||
val status: String = "success",
|
||||
val message: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* Обертка для ответа регистрации
|
||||
*/
|
||||
class RegisterResponseWrapper(
|
||||
@SerializedName("data") val data: RegisterResponse
|
||||
) : BaseResponseWrapper()
|
||||
|
||||
/**
|
||||
* Обертка для ответа авторизации
|
||||
*/
|
||||
class AuthTokenResponseWrapper(
|
||||
@SerializedName("data") val data: AuthTokenResponse
|
||||
) : BaseResponseWrapper()
|
||||
|
||||
/**
|
||||
* Обертка для ответа обновления токена
|
||||
*/
|
||||
class TokenRefreshResponseWrapper(
|
||||
@SerializedName("data") val data: TokenRefreshResponse
|
||||
) : BaseResponseWrapper()
|
||||
|
||||
/**
|
||||
* Обертка для ответа с профилем пользователя
|
||||
*/
|
||||
class UserProfileResponseWrapper(
|
||||
@SerializedName("data") val data: UserProfile
|
||||
) : BaseResponseWrapper()
|
||||
@@ -0,0 +1,4 @@
|
||||
package kr.smartsoltech.wellshe.model.auth
|
||||
|
||||
// Файл больше не используется
|
||||
// Все классы и типонимы перенесены в AuthResponse.kt
|
||||
@@ -0,0 +1,33 @@
|
||||
package kr.smartsoltech.wellshe.model.auth
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
/**
|
||||
* Модель данных профиля пользователя
|
||||
*/
|
||||
data class UserProfile(
|
||||
val id: Long = 0,
|
||||
val username: String = "",
|
||||
val email: String = "",
|
||||
@SerializedName("first_name") val firstName: String = "",
|
||||
@SerializedName("last_name") val lastName: String = "",
|
||||
val phone: String = "",
|
||||
@SerializedName("user_id") val userId: String = "",
|
||||
@SerializedName("created_at") val createdAt: String = "",
|
||||
@SerializedName("is_verified") val isVerified: Boolean = false,
|
||||
|
||||
// Дополнительные поля для экрана редактирования профиля
|
||||
val bio: String? = null,
|
||||
@SerializedName("date_of_birth") val date_of_birth: String? = null,
|
||||
|
||||
// Экстренные контакты
|
||||
@SerializedName("emergency_contact_1_name") val emergency_contact_1_name: String? = null,
|
||||
@SerializedName("emergency_contact_1_phone") val emergency_contact_1_phone: String? = null,
|
||||
@SerializedName("emergency_contact_2_name") val emergency_contact_2_name: String? = null,
|
||||
@SerializedName("emergency_contact_2_phone") val emergency_contact_2_phone: String? = null,
|
||||
|
||||
// Настройки уведомлений и доступа
|
||||
@SerializedName("emergency_notifications_enabled") val emergency_notifications_enabled: Boolean? = false,
|
||||
@SerializedName("location_sharing_enabled") val location_sharing_enabled: Boolean? = false,
|
||||
@SerializedName("push_notifications_enabled") val push_notifications_enabled: Boolean? = false
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
package kr.smartsoltech.wellshe.model.emergency
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
/**
|
||||
* Модель для запроса создания экстренного оповещения
|
||||
*/
|
||||
data class EmergencyAlertRequest(
|
||||
val location: LocationData,
|
||||
val message: String? = null,
|
||||
@SerializedName("battery_level") val batteryLevel: Int? = null,
|
||||
@SerializedName("contact_ids") val contactIds: List<String>? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель данных о местоположении
|
||||
*/
|
||||
data class LocationData(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val accuracy: Float? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель для запроса обновления местоположения в активном оповещении
|
||||
*/
|
||||
data class LocationUpdateRequest(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val accuracy: Float? = null,
|
||||
@SerializedName("battery_level") val batteryLevel: Int? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель для запроса отмены экстренного оповещения
|
||||
*/
|
||||
data class AlertCancelRequest(
|
||||
val reason: String? = null,
|
||||
val details: String? = null
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
package kr.smartsoltech.wellshe.model.emergency
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
|
||||
/**
|
||||
* Модель ответа при создании экстренного оповещения
|
||||
*/
|
||||
data class EmergencyAlertResponse(
|
||||
@SerializedName("alert_id") val alertId: String,
|
||||
@SerializedName("created_at") val createdAt: String,
|
||||
val status: String,
|
||||
val message: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель контакта с информацией о статусе уведомления
|
||||
*/
|
||||
data class NotifiedContact(
|
||||
@SerializedName("contact_id") val contactId: String,
|
||||
val status: String,
|
||||
@SerializedName("notified_at") val notifiedAt: String?
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель информации о местоположении с датой обновления
|
||||
*/
|
||||
data class LocationStatus(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
@SerializedName("updated_at") val updatedAt: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель детального статуса экстренного оповещения
|
||||
*/
|
||||
data class EmergencyAlertStatus(
|
||||
@SerializedName("alert_id") val alertId: String,
|
||||
@SerializedName("created_at") val createdAt: String,
|
||||
val status: String,
|
||||
val location: LocationStatus,
|
||||
@SerializedName("notified_contacts") val notifiedContacts: List<NotifiedContact>,
|
||||
@SerializedName("emergency_services_notified") val emergencyServicesNotified: Boolean,
|
||||
@SerializedName("emergency_services_notified_at") val emergencyServicesNotifiedAt: String?
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель ответа при обновлении местоположения
|
||||
*/
|
||||
data class LocationUpdateResponse(
|
||||
@SerializedName("updated_at") val updatedAt: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Модель ответа при отмене экстренного оповещения
|
||||
*/
|
||||
data class AlertCancelResponse(
|
||||
@SerializedName("alert_id") val alertId: String,
|
||||
@SerializedName("cancelled_at") val cancelledAt: String,
|
||||
val status: String
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
package kr.smartsoltech.wellshe.model.emergency
|
||||
|
||||
import com.google.gson.annotations.SerializedName
|
||||
import kr.smartsoltech.wellshe.model.auth.BaseResponseWrapper
|
||||
|
||||
/**
|
||||
* Обертка для ответа при создании экстренного оповещения
|
||||
*/
|
||||
class EmergencyAlertResponseWrapper(
|
||||
@SerializedName("data") val data: EmergencyAlertResponse
|
||||
) : BaseResponseWrapper()
|
||||
|
||||
/**
|
||||
* Обертка для ответа при получении статуса экстренного оповещения
|
||||
*/
|
||||
class EmergencyAlertStatusWrapper(
|
||||
@SerializedName("data") val data: EmergencyAlertStatus
|
||||
) : BaseResponseWrapper()
|
||||
|
||||
/**
|
||||
* Обертка для ответа при обновлении местоположения
|
||||
*/
|
||||
class LocationUpdateResponseWrapper(
|
||||
@SerializedName("data") val data: LocationUpdateResponse
|
||||
) : BaseResponseWrapper()
|
||||
|
||||
/**
|
||||
* Обертка для ответа при отмене экстренного оповещения
|
||||
*/
|
||||
class AlertCancelResponseWrapper(
|
||||
@SerializedName("data") val data: AlertCancelResponse
|
||||
) : BaseResponseWrapper()
|
||||
@@ -0,0 +1,202 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth
|
||||
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kr.smartsoltech.wellshe.data.local.AuthTokenRepository
|
||||
import kr.smartsoltech.wellshe.domain.auth.GetUserProfileUseCase
|
||||
import kr.smartsoltech.wellshe.domain.auth.LoginUseCase
|
||||
import kr.smartsoltech.wellshe.domain.auth.LogoutUseCase
|
||||
import kr.smartsoltech.wellshe.domain.auth.RegisterUseCase
|
||||
import kr.smartsoltech.wellshe.model.auth.AuthTokenResponseWrapper
|
||||
import kr.smartsoltech.wellshe.model.auth.UserProfile
|
||||
import kr.smartsoltech.wellshe.util.Result
|
||||
import kr.smartsoltech.wellshe.data.storage.TokenManager
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* ViewModel для управления авторизацией и профилем пользователя
|
||||
*/
|
||||
@HiltViewModel
|
||||
class AuthViewModel @Inject constructor(
|
||||
private val loginUseCase: LoginUseCase,
|
||||
private val registerUseCase: RegisterUseCase,
|
||||
private val logoutUseCase: LogoutUseCase,
|
||||
private val getUserProfileUseCase: GetUserProfileUseCase,
|
||||
private val authTokenRepository: AuthTokenRepository,
|
||||
private val tokenManager: TokenManager
|
||||
) : ViewModel() {
|
||||
|
||||
private val _authState = MutableLiveData<AuthState>()
|
||||
val authState: LiveData<AuthState> = _authState
|
||||
|
||||
private val _userProfile = MutableLiveData<UserProfile?>()
|
||||
val userProfile: LiveData<UserProfile?> = _userProfile
|
||||
|
||||
private val _isLoading = MutableLiveData(false)
|
||||
val isLoading: LiveData<Boolean> = _isLoading
|
||||
|
||||
init {
|
||||
// Проверяем наличие сохраненных данных для автоматического входа
|
||||
checkSavedCredentials()
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка и использование сохраненных учетных данных для автоматического входа
|
||||
*/
|
||||
private fun checkSavedCredentials() {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val hasAuthData = authTokenRepository.hasAuthData.first()
|
||||
if (hasAuthData) {
|
||||
val email = authTokenRepository.savedEmail.first() ?: return@launch
|
||||
val password = authTokenRepository.savedPassword.first() ?: return@launch
|
||||
login(email, password, true)
|
||||
} else {
|
||||
_authState.value = AuthState.NotAuthenticated
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_authState.value = AuthState.NotAuthenticated
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Вход в систему с помощью email или username
|
||||
*/
|
||||
fun login(identifier: String, password: String, isEmail: Boolean) {
|
||||
_isLoading.value = true
|
||||
_authState.value = AuthState.Authenticating
|
||||
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
Log.d("AuthViewModel", "Starting login process: $identifier, isEmail=$isEmail")
|
||||
|
||||
when (val result = loginUseCase(identifier, password, isEmail)) {
|
||||
is Result.Success -> {
|
||||
// Получаем данные авторизации из результата use case — токены уже сохранены в TokenManager
|
||||
Log.d("AuthViewModel", "Login Success: tokens saved to TokenManager")
|
||||
|
||||
// Устанавливаем состояние авторизации как успешное
|
||||
_authState.value = AuthState.Authenticated
|
||||
|
||||
// Сохраняем учетные данные для автологина (email/password)
|
||||
authTokenRepository.saveAuthCredentials(identifier, password)
|
||||
|
||||
// Сохраняем реальный access token в DataStore для долговременного хранения
|
||||
try {
|
||||
val realToken = tokenManager.getAccessToken()
|
||||
if (!realToken.isNullOrEmpty()) {
|
||||
authTokenRepository.saveAuthToken(realToken)
|
||||
Log.d("AuthViewModel", "Saved real access token to DataStore (masked=${realToken.take(6)}...)")
|
||||
} else {
|
||||
Log.w("AuthViewModel", "TokenManager did not contain access token after login")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("AuthViewModel", "Failed to persist access token: ${e.message}", e)
|
||||
}
|
||||
|
||||
// Загружаем профиль после успешной авторизации
|
||||
fetchUserProfile()
|
||||
}
|
||||
is Result.Error -> {
|
||||
Log.e("AuthViewModel", "Login Error: ${result.exception.message}")
|
||||
_authState.value = AuthState.AuthError(result.exception.message ?: "Ошибка авторизации")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("AuthViewModel", "Unhandled exception in login: ${e.message}", e)
|
||||
_authState.value = AuthState.AuthError("Непредвиденная ошибка: ${e.message}")
|
||||
} finally {
|
||||
_isLoading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрация нового пользователя
|
||||
*/
|
||||
fun register(email: String, username: String, password: String, firstName: String, lastName: String, phone: String) {
|
||||
_isLoading.value = true
|
||||
_authState.value = AuthState.Registering
|
||||
|
||||
viewModelScope.launch {
|
||||
when (val result = registerUseCase(email, username, password, firstName, lastName, phone)) {
|
||||
is Result.Success -> {
|
||||
_authState.value = AuthState.RegistrationSuccess
|
||||
}
|
||||
is Result.Error -> {
|
||||
_authState.value = AuthState.RegistrationError(result.exception.message ?: "Ошибка регистрации")
|
||||
}
|
||||
}
|
||||
_isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выход из системы
|
||||
*/
|
||||
fun logout() {
|
||||
_isLoading.value = true
|
||||
|
||||
viewModelScope.launch {
|
||||
when (val result = logoutUseCase()) {
|
||||
is Result.Success -> {
|
||||
// Очищаем сохраненные данные авторизации
|
||||
authTokenRepository.clearAuthData()
|
||||
_authState.value = AuthState.NotAuthenticated
|
||||
_userProfile.value = null
|
||||
}
|
||||
is Result.Error -> {
|
||||
// Даже при ошибке API сессия на устройстве будет завершена
|
||||
authTokenRepository.clearAuthData()
|
||||
_authState.value = AuthState.NotAuthenticated
|
||||
_userProfile.value = null
|
||||
}
|
||||
}
|
||||
_isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Загрузка профиля пользователя
|
||||
*/
|
||||
fun fetchUserProfile() {
|
||||
_isLoading.value = true
|
||||
|
||||
viewModelScope.launch {
|
||||
when (val result = getUserProfileUseCase()) {
|
||||
is Result.Success -> {
|
||||
_userProfile.value = result.data
|
||||
}
|
||||
is Result.Error -> {
|
||||
// Ошибка может означать, что токен недействителен
|
||||
if (result.exception.message?.contains("авторизован") == true) {
|
||||
// Очищаем недействительный токен
|
||||
authTokenRepository.clearAuthData()
|
||||
_authState.value = AuthState.NotAuthenticated
|
||||
}
|
||||
}
|
||||
}
|
||||
_isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Состояния процесса авторизации
|
||||
*/
|
||||
sealed class AuthState {
|
||||
object NotAuthenticated : AuthState()
|
||||
object Authenticating : AuthState()
|
||||
object Authenticated : AuthState()
|
||||
object Registering : AuthState()
|
||||
object RegistrationSuccess : AuthState()
|
||||
data class AuthError(val message: String) : AuthState()
|
||||
data class RegistrationError(val message: String) : AuthState()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Toast
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import kr.smartsoltech.wellshe.R
|
||||
import kr.smartsoltech.wellshe.databinding.FragmentLoginBinding
|
||||
import kr.smartsoltech.wellshe.di.ViewModelFactory
|
||||
import kr.smartsoltech.wellshe.util.isValidEmail
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Фрагмент для входа пользователя в систему
|
||||
*/
|
||||
class LoginFragment : Fragment() {
|
||||
|
||||
private var _binding: FragmentLoginBinding? = null
|
||||
private val binding get() = _binding!!
|
||||
|
||||
@Inject
|
||||
lateinit var viewModelFactory: ViewModelFactory
|
||||
|
||||
private lateinit var viewModel: AuthViewModel
|
||||
|
||||
override fun onCreateView(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View {
|
||||
_binding = FragmentLoginBinding.inflate(inflater, container, false)
|
||||
return binding.root
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
|
||||
// Получаем ViewModel через DI
|
||||
viewModel = ViewModelProvider(requireActivity(), viewModelFactory)[AuthViewModel::class.java]
|
||||
|
||||
setupListeners()
|
||||
observeViewModel()
|
||||
}
|
||||
|
||||
private fun setupListeners() {
|
||||
// Валидация ввода в реальном времени
|
||||
binding.etEmailUsername.addTextChangedListener {
|
||||
validateForm()
|
||||
}
|
||||
|
||||
binding.etPassword.addTextChangedListener {
|
||||
validateForm()
|
||||
}
|
||||
|
||||
// Нажатие на кнопку входа
|
||||
binding.btnLogin.setOnClickListener {
|
||||
val identifier = binding.etEmailUsername.text.toString()
|
||||
val password = binding.etPassword.text.toString()
|
||||
|
||||
// Определяем, это email или username
|
||||
val isEmail = identifier.isValidEmail()
|
||||
|
||||
viewModel.login(identifier, password, isEmail)
|
||||
}
|
||||
|
||||
// Переход на экран регистрации
|
||||
binding.btnRegister.setOnClickListener {
|
||||
findNavController().navigate(R.id.action_loginFragment_to_registerFragment)
|
||||
}
|
||||
}
|
||||
|
||||
private fun observeViewModel() {
|
||||
// Наблюдаем за состоянием авторизации
|
||||
viewModel.authState.observe(viewLifecycleOwner) { state ->
|
||||
when (state) {
|
||||
is AuthViewModel.AuthState.Authenticating -> {
|
||||
// Показываем индикатор загрузки
|
||||
binding.progressBar.visibility = View.VISIBLE
|
||||
binding.btnLogin.isEnabled = false
|
||||
}
|
||||
is AuthViewModel.AuthState.Authenticated -> {
|
||||
// Переходим на главный экран
|
||||
findNavController().navigate(R.id.action_loginFragment_to_mainFragment)
|
||||
}
|
||||
is AuthViewModel.AuthState.AuthError -> {
|
||||
// Показываем ошибку
|
||||
Toast.makeText(requireContext(), state.message, Toast.LENGTH_LONG).show()
|
||||
binding.progressBar.visibility = View.GONE
|
||||
binding.btnLogin.isEnabled = true
|
||||
}
|
||||
else -> {
|
||||
// Сбрасываем состояние UI
|
||||
binding.progressBar.visibility = View.GONE
|
||||
binding.btnLogin.isEnabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Наблюдаем за состоянием загрузки
|
||||
viewModel.isLoading.observe(viewLifecycleOwner) { isLoading ->
|
||||
binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
|
||||
binding.btnLogin.isEnabled = !isLoading
|
||||
}
|
||||
}
|
||||
|
||||
private fun validateForm() {
|
||||
val identifier = binding.etEmailUsername.text.toString()
|
||||
val password = binding.etPassword.text.toString()
|
||||
|
||||
binding.btnLogin.isEnabled = identifier.isNotEmpty() && password.length >= 8
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
_binding = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Toast
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import kr.smartsoltech.wellshe.R
|
||||
import kr.smartsoltech.wellshe.databinding.FragmentRegisterBinding
|
||||
import kr.smartsoltech.wellshe.di.ViewModelFactory
|
||||
import kr.smartsoltech.wellshe.util.isValidEmail
|
||||
import kr.smartsoltech.wellshe.util.isValidPassword
|
||||
import kr.smartsoltech.wellshe.util.isValidPhone
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Фрагмент для регистрации нового пользователя
|
||||
*/
|
||||
class RegisterFragment : Fragment() {
|
||||
|
||||
private var _binding: FragmentRegisterBinding? = null
|
||||
private val binding get() = _binding!!
|
||||
|
||||
@Inject
|
||||
lateinit var viewModelFactory: ViewModelFactory
|
||||
|
||||
private lateinit var viewModel: AuthViewModel
|
||||
|
||||
override fun onCreateView(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View {
|
||||
_binding = FragmentRegisterBinding.inflate(inflater, container, false)
|
||||
return binding.root
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
|
||||
// Получаем ViewModel через DI
|
||||
viewModel = ViewModelProvider(requireActivity(), viewModelFactory)[AuthViewModel::class.java]
|
||||
|
||||
setupListeners()
|
||||
observeViewModel()
|
||||
}
|
||||
|
||||
private fun setupListeners() {
|
||||
// Добавляем валидацию в реальном времени для всех полей формы
|
||||
binding.etEmail.addTextChangedListener { validateForm() }
|
||||
binding.etUsername.addTextChangedListener { validateForm() }
|
||||
binding.etPassword.addTextChangedListener { validateForm() }
|
||||
binding.etConfirmPassword.addTextChangedListener { validateForm() }
|
||||
binding.etFirstName.addTextChangedListener { validateForm() }
|
||||
binding.etLastName.addTextChangedListener { validateForm() }
|
||||
binding.etPhone.addTextChangedListener { validateForm() }
|
||||
|
||||
// Обработка нажатия на кнопку регистрации
|
||||
binding.btnRegister.setOnClickListener {
|
||||
if (isFormValid()) {
|
||||
register()
|
||||
}
|
||||
}
|
||||
|
||||
// Переход на экран входа
|
||||
binding.btnBackToLogin.setOnClickListener {
|
||||
findNavController().popBackStack()
|
||||
}
|
||||
}
|
||||
|
||||
private fun register() {
|
||||
val email = binding.etEmail.text?.toString() ?: ""
|
||||
val username = binding.etUsername.text?.toString() ?: ""
|
||||
val password = binding.etPassword.text?.toString() ?: ""
|
||||
val firstName = binding.etFirstName.text?.toString() ?: ""
|
||||
val lastName = binding.etLastName.text?.toString() ?: ""
|
||||
val phone = binding.etPhone.text?.toString() ?: ""
|
||||
|
||||
viewModel.register(email, username, password, firstName, lastName, phone)
|
||||
}
|
||||
|
||||
private fun observeViewModel() {
|
||||
// Наблюдаем за состоянием регистрации
|
||||
viewModel.authState.observe(viewLifecycleOwner) { state ->
|
||||
when (state) {
|
||||
is AuthViewModel.AuthState.Registering -> {
|
||||
binding.progressBar.visibility = View.VISIBLE
|
||||
binding.btnRegister.isEnabled = false
|
||||
}
|
||||
is AuthViewModel.AuthState.RegistrationSuccess -> {
|
||||
Toast.makeText(
|
||||
requireContext(),
|
||||
"Регистрация успешна. Пожалуйста, войдите в систему.",
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
findNavController().popBackStack()
|
||||
}
|
||||
is AuthViewModel.AuthState.RegistrationError -> {
|
||||
Toast.makeText(requireContext(), state.message, Toast.LENGTH_LONG).show()
|
||||
binding.progressBar.visibility = View.GONE
|
||||
binding.btnRegister.isEnabled = true
|
||||
}
|
||||
else -> {
|
||||
binding.progressBar.visibility = View.GONE
|
||||
binding.btnRegister.isEnabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Наблюдаем за состоянием загрузки
|
||||
viewModel.isLoading.observe(viewLifecycleOwner) { isLoading ->
|
||||
binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
|
||||
binding.btnRegister.isEnabled = !isLoading
|
||||
}
|
||||
}
|
||||
|
||||
private fun isFormValid(): Boolean {
|
||||
val email = binding.etEmail.text?.toString() ?: ""
|
||||
val username = binding.etUsername.text?.toString() ?: ""
|
||||
val password = binding.etPassword.text?.toString() ?: ""
|
||||
val confirmPassword = binding.etConfirmPassword.text?.toString() ?: ""
|
||||
val firstName = binding.etFirstName.text?.toString() ?: ""
|
||||
val lastName = binding.etLastName.text?.toString() ?: ""
|
||||
val phone = binding.etPhone.text?.toString() ?: ""
|
||||
|
||||
var isValid = true
|
||||
|
||||
// Проверка email
|
||||
if (!email.isValidEmail()) {
|
||||
binding.tilEmail.error = "Введите корректный email"
|
||||
isValid = false
|
||||
} else {
|
||||
binding.tilEmail.error = null
|
||||
}
|
||||
|
||||
// Проверка имени пользователя
|
||||
if (username.length < 3) {
|
||||
binding.tilUsername.error = "Имя пользователя должно быть не менее 3 символов"
|
||||
isValid = false
|
||||
} else {
|
||||
binding.tilUsername.error = null
|
||||
}
|
||||
|
||||
// Проверка пароля
|
||||
if (!password.isValidPassword()) {
|
||||
binding.tilPassword.error = "Пароль должен содержать не менее 8 символов, включая цифру, заглавную букву и специальный символ"
|
||||
isValid = false
|
||||
} else {
|
||||
binding.tilPassword.error = null
|
||||
}
|
||||
|
||||
// Проверка совпадения паролей
|
||||
if (password != confirmPassword) {
|
||||
binding.tilConfirmPassword.error = "Пароли не совпадают"
|
||||
isValid = false
|
||||
} else {
|
||||
binding.tilConfirmPassword.error = null
|
||||
}
|
||||
|
||||
// Проверка имени и фамилии
|
||||
if (firstName.isEmpty()) {
|
||||
binding.tilFirstName.error = "Введите имя"
|
||||
isValid = false
|
||||
} else {
|
||||
binding.tilFirstName.error = null
|
||||
}
|
||||
|
||||
if (lastName.isEmpty()) {
|
||||
binding.tilLastName.error = "Введите фамилию"
|
||||
isValid = false
|
||||
} else {
|
||||
binding.tilLastName.error = null
|
||||
}
|
||||
|
||||
// Проверка телефона
|
||||
if (!phone.isValidPhone()) {
|
||||
binding.tilPhone.error = "Введите корректный номер телефона (международный формат)"
|
||||
isValid = false
|
||||
} else {
|
||||
binding.tilPhone.error = null
|
||||
}
|
||||
|
||||
return isValid
|
||||
}
|
||||
|
||||
private fun validateForm() {
|
||||
// Простая проверка для активации/деактивации кнопки
|
||||
val allFieldsFilled = binding.etEmail.text?.isNotEmpty() == true &&
|
||||
binding.etUsername.text?.isNotEmpty() == true &&
|
||||
binding.etPassword.text?.isNotEmpty() == true &&
|
||||
binding.etConfirmPassword.text?.isNotEmpty() == true &&
|
||||
binding.etFirstName.text?.isNotEmpty() == true &&
|
||||
binding.etLastName.text?.isNotEmpty() == true &&
|
||||
binding.etPhone.text?.isNotEmpty() == true
|
||||
|
||||
binding.btnRegister.isEnabled = allFieldsFilled
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
_binding = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth
|
||||
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kr.smartsoltech.wellshe.data.model.ServerStatus
|
||||
import kr.smartsoltech.wellshe.data.network.RetrofitProvider
|
||||
import kr.smartsoltech.wellshe.data.preferences.ServerPreferences
|
||||
import kr.smartsoltech.wellshe.data.repository.ServerHealthRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class ServerSettingsViewModel @Inject constructor(
|
||||
private val serverPreferences: ServerPreferences,
|
||||
private val retrofitProvider: RetrofitProvider,
|
||||
private val serverHealthRepository: ServerHealthRepository
|
||||
) : ViewModel() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ServerSettingsViewModel"
|
||||
}
|
||||
|
||||
private val _serverUrl = MutableStateFlow("")
|
||||
val serverUrl: StateFlow<String> = _serverUrl
|
||||
|
||||
private val _suggestedServers = MutableStateFlow<List<String>>(emptyList())
|
||||
val suggestedServers: StateFlow<List<String>> = _suggestedServers
|
||||
|
||||
private val _serverStatuses = MutableStateFlow<Map<String, ServerStatus>>(emptyMap())
|
||||
val serverStatuses: StateFlow<Map<String, ServerStatus>> = _serverStatuses
|
||||
|
||||
private val _isCheckingHealth = MutableStateFlow(false)
|
||||
val isCheckingHealth: StateFlow<Boolean> = _isCheckingHealth
|
||||
|
||||
init {
|
||||
Log.d(TAG, "ServerSettingsViewModel initialized")
|
||||
loadServerUrl()
|
||||
loadSuggestedServers()
|
||||
checkServersHealth()
|
||||
}
|
||||
|
||||
private fun loadServerUrl() {
|
||||
viewModelScope.launch {
|
||||
_serverUrl.value = serverPreferences.getServerUrl()
|
||||
Log.d(TAG, "Loaded server URL: ${_serverUrl.value}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadSuggestedServers() {
|
||||
viewModelScope.launch {
|
||||
_suggestedServers.value = serverPreferences.getSuggestedServers()
|
||||
Log.d(TAG, "Loaded suggested servers: ${_suggestedServers.value}")
|
||||
}
|
||||
}
|
||||
|
||||
fun saveServerUrl(url: String) {
|
||||
viewModelScope.launch {
|
||||
val trimmedUrl = url.trim()
|
||||
Log.d(TAG, "Saving server URL: $trimmedUrl")
|
||||
serverPreferences.setServerUrl(trimmedUrl)
|
||||
_serverUrl.value = trimmedUrl
|
||||
// Пересоздаем Retrofit с новым URL
|
||||
retrofitProvider.recreateRetrofit()
|
||||
Log.d(TAG, "Server URL saved and Retrofit recreated")
|
||||
}
|
||||
}
|
||||
|
||||
fun getCurrentApiBaseUrl(): String {
|
||||
return serverPreferences.getApiBaseUrl()
|
||||
}
|
||||
|
||||
fun checkServersHealth() {
|
||||
if (_isCheckingHealth.value) {
|
||||
Log.d(TAG, "Health check already in progress, skipping")
|
||||
return
|
||||
}
|
||||
|
||||
Log.d(TAG, "Starting health check for all servers")
|
||||
_isCheckingHealth.value = true
|
||||
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val servers = _suggestedServers.value
|
||||
Log.d(TAG, "Checking health for servers: $servers")
|
||||
|
||||
val healthResults = serverHealthRepository.checkMultipleServers(servers)
|
||||
|
||||
val statusMap = healthResults.associateBy { it.url }
|
||||
_serverStatuses.value = statusMap
|
||||
|
||||
Log.d(TAG, "Health check completed. Results: ${statusMap.values.map { "${it.url}: ${it.status}" }}")
|
||||
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error during health check", e)
|
||||
} finally {
|
||||
_isCheckingHealth.value = false
|
||||
Log.d(TAG, "Health check finished")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getServerStatus(url: String): ServerStatus? {
|
||||
return _serverStatuses.value[url]
|
||||
}
|
||||
|
||||
fun refreshServerHealth() {
|
||||
Log.d(TAG, "Manual refresh of server health requested")
|
||||
checkServersHealth()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth.compose
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.compose.runtime.livedata.observeAsState
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import kr.smartsoltech.wellshe.ui.auth.AuthViewModel
|
||||
import kr.smartsoltech.wellshe.ui.auth.ServerSettingsViewModel
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun LoginScreen(
|
||||
onNavigateToRegister: () -> Unit,
|
||||
onLoginSuccess: () -> Unit,
|
||||
viewModel: AuthViewModel = hiltViewModel(),
|
||||
serverSettingsViewModel: ServerSettingsViewModel = hiltViewModel()
|
||||
) {
|
||||
val authState by viewModel.authState.observeAsState()
|
||||
val isLoading by viewModel.isLoading.observeAsState()
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
val serverUrl by serverSettingsViewModel.serverUrl.collectAsStateWithLifecycle()
|
||||
|
||||
var username by remember { mutableStateOf("") }
|
||||
var password by remember { mutableStateOf("") }
|
||||
var passwordVisible by remember { mutableStateOf(false) }
|
||||
var isFormValid by remember { mutableStateOf(false) }
|
||||
var showServerSettings by remember { mutableStateOf(false) }
|
||||
|
||||
// FocusRequester для переключения фокуса между полями
|
||||
val passwordFocusRequester = remember { FocusRequester() }
|
||||
|
||||
LaunchedEffect(username, password) {
|
||||
isFormValid = username.isNotEmpty() && password.isNotEmpty()
|
||||
}
|
||||
|
||||
LaunchedEffect(authState) {
|
||||
if (authState is AuthViewModel.AuthState.Authenticated) {
|
||||
onLoginSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
// Функция для выполнения входа
|
||||
val performLogin = {
|
||||
if (isFormValid && isLoading != true) {
|
||||
keyboardController?.hide()
|
||||
// Передаем false в качестве параметра isEmail, так как мы используем username
|
||||
viewModel.login(username, password, false)
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { },
|
||||
navigationIcon = {
|
||||
IconButton(
|
||||
onClick = { showServerSettings = true }
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Settings,
|
||||
contentDescription = "Настройки сервера"
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { paddingValues ->
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues)
|
||||
.padding(16.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "WellShe",
|
||||
style = MaterialTheme.typography.headlineLarge
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = { username = it },
|
||||
label = { Text("Имя пользователя") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
imeAction = ImeAction.Next
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onNext = { passwordFocusRequester.requestFocus() }
|
||||
)
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text("Пароль") },
|
||||
singleLine = true,
|
||||
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(passwordFocusRequester),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onDone = {
|
||||
performLogin()
|
||||
}
|
||||
),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||
Icon(
|
||||
imageVector = if (passwordVisible) Icons.Filled.Visibility else Icons.Filled.VisibilityOff,
|
||||
contentDescription = if (passwordVisible) "Скрыть пароль" else "Показать пароль"
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
Button(
|
||||
onClick = { performLogin() },
|
||||
enabled = isFormValid && isLoading != true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(50.dp)
|
||||
) {
|
||||
if (isLoading == true) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(24.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimary
|
||||
)
|
||||
} else {
|
||||
Text("Войти")
|
||||
}
|
||||
}
|
||||
|
||||
TextButton(onClick = onNavigateToRegister) {
|
||||
Text("Создать новый аккаунт")
|
||||
}
|
||||
|
||||
// Показываем текущий сервер
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(12.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "Сервер:",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Text(
|
||||
text = serverUrl.ifEmpty { "Загрузка..." },
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (authState is AuthViewModel.AuthState.AuthError) {
|
||||
Text(
|
||||
text = (authState as AuthViewModel.AuthState.AuthError).message,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Диалог настроек сервера
|
||||
if (showServerSettings) {
|
||||
ServerSettingsDialog(
|
||||
onDismiss = { showServerSettings = false },
|
||||
onSave = { newUrl ->
|
||||
serverSettingsViewModel.saveServerUrl(newUrl)
|
||||
showServerSettings = false
|
||||
},
|
||||
currentServerUrl = serverUrl
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth.compose
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.livedata.observeAsState
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import kr.smartsoltech.wellshe.ui.auth.AuthViewModel
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
fun RegisterScreen(
|
||||
onNavigateBack: () -> Unit,
|
||||
onRegisterSuccess: (email: String, password: String) -> Unit,
|
||||
viewModel: AuthViewModel = hiltViewModel()
|
||||
) {
|
||||
val authState by viewModel.authState.observeAsState()
|
||||
val isLoading by viewModel.isLoading.observeAsState()
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
val scrollState = rememberScrollState()
|
||||
|
||||
var email by remember { mutableStateOf("") }
|
||||
var username by remember { mutableStateOf("") }
|
||||
var password by remember { mutableStateOf("") }
|
||||
var confirmPassword by remember { mutableStateOf("") }
|
||||
var fullName by remember { mutableStateOf("") }
|
||||
var phone by remember { mutableStateOf("") }
|
||||
|
||||
var passwordVisible by remember { mutableStateOf(false) }
|
||||
var confirmPasswordVisible by remember { mutableStateOf(false) }
|
||||
|
||||
var isFormValid by remember { mutableStateOf(false) }
|
||||
var passwordsMatch by remember { mutableStateOf(true) }
|
||||
|
||||
// FocusRequesters для полей формы
|
||||
val usernameFocusRequester = remember { FocusRequester() }
|
||||
val passwordFocusRequester = remember { FocusRequester() }
|
||||
val confirmPasswordFocusRequester = remember { FocusRequester() }
|
||||
val fullNameFocusRequester = remember { FocusRequester() }
|
||||
val phoneFocusRequester = remember { FocusRequester() }
|
||||
|
||||
// Валидация формы
|
||||
LaunchedEffect(email, username, password, confirmPassword, fullName, phone) {
|
||||
passwordsMatch = password == confirmPassword
|
||||
isFormValid = email.isNotBlank() && username.isNotBlank() &&
|
||||
password.isNotBlank() && confirmPassword.isNotBlank() &&
|
||||
fullName.isNotBlank() && phone.isNotBlank() &&
|
||||
passwordsMatch &&
|
||||
password.length >= 8 // Минимальная длина пароля
|
||||
}
|
||||
|
||||
// Обработка состояния авторизации
|
||||
LaunchedEffect(authState) {
|
||||
if (authState is AuthViewModel.AuthState.RegistrationSuccess) {
|
||||
// При успешной регистрации сразу выполняем вход с теми же данными
|
||||
onRegisterSuccess(email, password)
|
||||
}
|
||||
}
|
||||
|
||||
// Функция для выполнения регистрации
|
||||
val performRegister = {
|
||||
if (isFormValid && isLoading != true) {
|
||||
keyboardController?.hide()
|
||||
// Разделяем полное имя на имя и фамилию для сервера
|
||||
val nameParts = fullName.trim().split(" ", limit = 2)
|
||||
val firstName = nameParts[0]
|
||||
val lastName = if (nameParts.size > 1) nameParts[1] else ""
|
||||
|
||||
viewModel.register(email, username, password, firstName, lastName, phone)
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold { paddingValues ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues)
|
||||
.padding(16.dp)
|
||||
.verticalScroll(scrollState),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "Регистрация",
|
||||
style = MaterialTheme.typography.headlineLarge
|
||||
)
|
||||
|
||||
// Поле Email
|
||||
OutlinedTextField(
|
||||
value = email,
|
||||
onValueChange = { email = it },
|
||||
label = { Text("Email") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Email,
|
||||
imeAction = ImeAction.Next
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onNext = { usernameFocusRequester.requestFocus() }
|
||||
)
|
||||
)
|
||||
|
||||
// Поле Username
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = { username = it },
|
||||
label = { Text("Имя пользователя") },
|
||||
singleLine = true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(usernameFocusRequester),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
imeAction = ImeAction.Next
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onNext = { passwordFocusRequester.requestFocus() }
|
||||
)
|
||||
)
|
||||
|
||||
// Поле Password
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text("Пароль") },
|
||||
singleLine = true,
|
||||
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(passwordFocusRequester),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Next
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onNext = { confirmPasswordFocusRequester.requestFocus() }
|
||||
),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||
Icon(
|
||||
imageVector = if (passwordVisible) Icons.Filled.Visibility else Icons.Filled.VisibilityOff,
|
||||
contentDescription = if (passwordVisible) "Скрыть пароль" else "Показать пароль"
|
||||
)
|
||||
}
|
||||
},
|
||||
isError = password.isNotEmpty() && password.length < 8
|
||||
)
|
||||
|
||||
if (password.isNotEmpty() && password.length < 8) {
|
||||
Text(
|
||||
text = "Пароль должен содержать минимум 8 символов",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.align(Alignment.Start)
|
||||
)
|
||||
}
|
||||
|
||||
// Поле для подтверждения пароля
|
||||
OutlinedTextField(
|
||||
value = confirmPassword,
|
||||
onValueChange = { confirmPassword = it },
|
||||
label = { Text("Подтвердите пароль") },
|
||||
singleLine = true,
|
||||
visualTransformation = if (confirmPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(confirmPasswordFocusRequester),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Next
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onNext = { fullNameFocusRequester.requestFocus() }
|
||||
),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = { confirmPasswordVisible = !confirmPasswordVisible }) {
|
||||
Icon(
|
||||
imageVector = if (confirmPasswordVisible) Icons.Filled.Visibility else Icons.Filled.VisibilityOff,
|
||||
contentDescription = if (confirmPasswordVisible) "Скрыть пароль" else "Показать пароль"
|
||||
)
|
||||
}
|
||||
},
|
||||
isError = confirmPassword.isNotEmpty() && !passwordsMatch
|
||||
)
|
||||
|
||||
if (confirmPassword.isNotEmpty() && !passwordsMatch) {
|
||||
Text(
|
||||
text = "Пароли не совпадают",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.align(Alignment.Start)
|
||||
)
|
||||
}
|
||||
|
||||
// Поле для полного имени
|
||||
OutlinedTextField(
|
||||
value = fullName,
|
||||
onValueChange = { fullName = it },
|
||||
label = { Text("Полное имя") },
|
||||
singleLine = true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(fullNameFocusRequester),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
imeAction = ImeAction.Next
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onNext = { phoneFocusRequester.requestFocus() }
|
||||
)
|
||||
)
|
||||
|
||||
// Поле для телефона
|
||||
OutlinedTextField(
|
||||
value = phone,
|
||||
onValueChange = { phone = it },
|
||||
label = { Text("Номер телефона") },
|
||||
singleLine = true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(phoneFocusRequester),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Phone,
|
||||
imeAction = ImeAction.Done
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onDone = {
|
||||
performRegister()
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
// Кнопка регистрации
|
||||
Button(
|
||||
onClick = { performRegister() },
|
||||
enabled = isFormValid && isLoading != true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(50.dp)
|
||||
) {
|
||||
if (isLoading == true) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(24.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimary
|
||||
)
|
||||
} else {
|
||||
Text("Зарегистрироваться")
|
||||
}
|
||||
}
|
||||
|
||||
// Кнопка возврата к экрану входа
|
||||
TextButton(onClick = onNavigateBack) {
|
||||
Text("Уже есть аккаунт? Войти")
|
||||
}
|
||||
|
||||
// Отображение ошибки
|
||||
if (authState is AuthViewModel.AuthState.RegistrationError) {
|
||||
Text(
|
||||
text = (authState as AuthViewModel.AuthState.RegistrationError).message,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth.compose
|
||||
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import kr.smartsoltech.wellshe.ui.auth.ServerSettingsViewModel
|
||||
|
||||
@Composable
|
||||
fun ServerSettingsDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (String) -> Unit,
|
||||
currentServerUrl: String,
|
||||
viewModel: ServerSettingsViewModel = hiltViewModel()
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
|
||||
val suggestedServers by viewModel.suggestedServers.collectAsState()
|
||||
val serverStatuses by viewModel.serverStatuses.collectAsState()
|
||||
val isCheckingHealth by viewModel.isCheckingHealth.collectAsState()
|
||||
|
||||
var serverUrl by remember { mutableStateOf(currentServerUrl) }
|
||||
|
||||
// Валидация URL
|
||||
val isValid = remember(serverUrl) {
|
||||
serverUrl.isNotBlank() &&
|
||||
(serverUrl.startsWith("http://") || serverUrl.startsWith("https://"))
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
// Заголовок с кнопкой обновления
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = "Настройки сервера",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
IconButton(
|
||||
onClick = { viewModel.refreshServerHealth() },
|
||||
enabled = !isCheckingHealth
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Refresh,
|
||||
contentDescription = "Обновить статус серверов"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = "Текущий сервер:",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
Text(
|
||||
text = currentServerUrl,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
// Заголовок предустановленных серверов
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = "Предустановленные серверы:",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
if (isCheckingHealth) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
||||
) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(12.dp),
|
||||
strokeWidth = 1.dp
|
||||
)
|
||||
Text(
|
||||
text = "Проверка...",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Список предустановленных серверов
|
||||
LazyColumn(
|
||||
modifier = Modifier.heightIn(max = 200.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp)
|
||||
) {
|
||||
items(suggestedServers) { server ->
|
||||
ServerStatusRow(
|
||||
server = server,
|
||||
serverStatus = serverStatuses[server],
|
||||
isChecking = isCheckingHealth,
|
||||
isSelected = server == serverUrl,
|
||||
onClick = {
|
||||
serverUrl = server
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
// Поле для ввода пользовательского URL
|
||||
Column {
|
||||
Text(
|
||||
text = "Или введите свой URL:",
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = serverUrl,
|
||||
onValueChange = { serverUrl = it },
|
||||
label = { Text("URL сервера") },
|
||||
placeholder = { Text("http://192.168.1.100:8000") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||
isError = serverUrl.isNotBlank() && !isValid,
|
||||
supportingText = {
|
||||
if (serverUrl.isNotBlank() && !isValid) {
|
||||
Text(
|
||||
text = "URL должен начинаться с http:// или https://",
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Кнопки
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text("Отмена")
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
if (isValid) {
|
||||
onSave(serverUrl.trim())
|
||||
Toast.makeText(
|
||||
context,
|
||||
"✅ Сервер изменён!\nСтарый: $currentServerUrl\nНовый: ${serverUrl.trim()}",
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
}
|
||||
},
|
||||
enabled = isValid,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text("Сохранить")
|
||||
}
|
||||
}
|
||||
|
||||
// Легенда статусов
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "Статусы серверов:",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
val statuses = listOf(
|
||||
"🟢 < 10мс - Отлично",
|
||||
"🟡 10-200мс - Хорошо",
|
||||
"🟠 200-600мс - Медленно",
|
||||
"🔴 600мс+ - Очень медленно",
|
||||
"⚫ Недоступен"
|
||||
)
|
||||
|
||||
statuses.forEach { status ->
|
||||
Text(
|
||||
text = status,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth.compose
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
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.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import kr.smartsoltech.wellshe.data.model.HealthStatus
|
||||
import kr.smartsoltech.wellshe.data.model.ServerStatus
|
||||
|
||||
@Composable
|
||||
fun ServerStatusIndicator(
|
||||
serverStatus: ServerStatus?,
|
||||
isChecking: Boolean = false
|
||||
) {
|
||||
if (isChecking) {
|
||||
// Показываем индикатор загрузки
|
||||
Box(
|
||||
modifier = Modifier.size(12.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(10.dp),
|
||||
strokeWidth = 1.dp,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
} else if (serverStatus != null) {
|
||||
// Показываем цветной индикатор
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(12.dp)
|
||||
.clip(CircleShape)
|
||||
.background(getStatusColor(serverStatus.status))
|
||||
)
|
||||
} else {
|
||||
// Показываем серый индикатор если статус неизвестен
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(12.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color.Gray)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ServerStatusRow(
|
||||
server: String,
|
||||
serverStatus: ServerStatus?,
|
||||
isChecking: Boolean,
|
||||
isSelected: Boolean,
|
||||
onClick: () -> Unit
|
||||
) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 2.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = if (isSelected) {
|
||||
MaterialTheme.colorScheme.primaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surface
|
||||
}
|
||||
),
|
||||
onClick = onClick
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(12.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = server,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
|
||||
)
|
||||
|
||||
if (serverStatus != null && !isChecking) {
|
||||
Text(
|
||||
text = getStatusText(serverStatus),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 10.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
ServerStatusIndicator(
|
||||
serverStatus = serverStatus,
|
||||
isChecking = isChecking
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getStatusColor(status: HealthStatus): Color {
|
||||
return when (status) {
|
||||
HealthStatus.EXCELLENT -> Color(0xFF4CAF50) // Зеленый
|
||||
HealthStatus.GOOD -> Color(0xFFFFC107) // Желтый
|
||||
HealthStatus.POOR -> Color(0xFFFF9800) // Оранжевый
|
||||
HealthStatus.BAD -> Color(0xFFF44336) // Красный
|
||||
HealthStatus.OFFLINE -> Color(0xFF9E9E9E) // Серый
|
||||
}
|
||||
}
|
||||
|
||||
private fun getStatusText(serverStatus: ServerStatus): String {
|
||||
return if (serverStatus.isHealthy) {
|
||||
"${serverStatus.pingMs}ms • ${getStatusLabel(serverStatus.status)}"
|
||||
} else {
|
||||
serverStatus.error ?: "Недоступен"
|
||||
}
|
||||
}
|
||||
|
||||
private fun getStatusLabel(status: HealthStatus): String {
|
||||
return when (status) {
|
||||
HealthStatus.EXCELLENT -> "Отлично"
|
||||
HealthStatus.GOOD -> "Хорошо"
|
||||
HealthStatus.POOR -> "Медленно"
|
||||
HealthStatus.BAD -> "Очень медленно"
|
||||
HealthStatus.OFFLINE -> "Недоступен"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package kr.smartsoltech.wellshe.ui.auth.compose
|
||||
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kr.smartsoltech.wellshe.data.model.HealthStatus
|
||||
import kr.smartsoltech.wellshe.data.model.ServerStatus
|
||||
|
||||
@Preview(showBackground = true)
|
||||
@Composable
|
||||
fun ServerStatusIndicatorPreview() {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Text("Индикаторы статуса серверов:", style = MaterialTheme.typography.headlineSmall)
|
||||
|
||||
// Отличный статус
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
ServerStatusIndicator(
|
||||
serverStatus = ServerStatus(
|
||||
url = "http://example.com",
|
||||
isHealthy = true,
|
||||
pingMs = 5,
|
||||
status = HealthStatus.EXCELLENT
|
||||
)
|
||||
)
|
||||
Text("Отлично (5мс)")
|
||||
}
|
||||
|
||||
// Хороший статус
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
ServerStatusIndicator(
|
||||
serverStatus = ServerStatus(
|
||||
url = "http://example.com",
|
||||
isHealthy = true,
|
||||
pingMs = 100,
|
||||
status = HealthStatus.GOOD
|
||||
)
|
||||
)
|
||||
Text("Хорошо (100мс)")
|
||||
}
|
||||
|
||||
// Медленный статус
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
ServerStatusIndicator(
|
||||
serverStatus = ServerStatus(
|
||||
url = "http://example.com",
|
||||
isHealthy = true,
|
||||
pingMs = 400,
|
||||
status = HealthStatus.POOR
|
||||
)
|
||||
)
|
||||
Text("Медленно (400мс)")
|
||||
}
|
||||
|
||||
// Очень медленный статус
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
ServerStatusIndicator(
|
||||
serverStatus = ServerStatus(
|
||||
url = "http://example.com",
|
||||
isHealthy = false,
|
||||
pingMs = 800,
|
||||
status = HealthStatus.BAD
|
||||
)
|
||||
)
|
||||
Text("Очень медленно (800мс)")
|
||||
}
|
||||
|
||||
// Недоступен
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
ServerStatusIndicator(
|
||||
serverStatus = ServerStatus(
|
||||
url = "http://example.com",
|
||||
isHealthy = false,
|
||||
pingMs = 5000,
|
||||
status = HealthStatus.OFFLINE,
|
||||
error = "Connection failed"
|
||||
)
|
||||
)
|
||||
Text("Недоступен")
|
||||
}
|
||||
|
||||
// Проверяется
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
ServerStatusIndicator(
|
||||
serverStatus = null,
|
||||
isChecking = true
|
||||
)
|
||||
Text("Проверяется...")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Preview(showBackground = true)
|
||||
@Composable
|
||||
fun ServerStatusRowPreview() {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Text("Строки серверов:", style = MaterialTheme.typography.headlineSmall)
|
||||
|
||||
ServerStatusRow(
|
||||
server = "http://10.0.2.2:8000",
|
||||
serverStatus = ServerStatus(
|
||||
url = "http://10.0.2.2:8000",
|
||||
isHealthy = true,
|
||||
pingMs = 8,
|
||||
status = HealthStatus.EXCELLENT
|
||||
),
|
||||
isChecking = false,
|
||||
isSelected = true,
|
||||
onClick = {}
|
||||
)
|
||||
|
||||
ServerStatusRow(
|
||||
server = "http://192.168.0.112:8000",
|
||||
serverStatus = ServerStatus(
|
||||
url = "http://192.168.0.112:8000",
|
||||
isHealthy = true,
|
||||
pingMs = 150,
|
||||
status = HealthStatus.GOOD
|
||||
),
|
||||
isChecking = false,
|
||||
isSelected = false,
|
||||
onClick = {}
|
||||
)
|
||||
|
||||
ServerStatusRow(
|
||||
server = "http://slow-server.com:8000",
|
||||
serverStatus = ServerStatus(
|
||||
url = "http://slow-server.com:8000",
|
||||
isHealthy = false,
|
||||
pingMs = 5000,
|
||||
status = HealthStatus.OFFLINE,
|
||||
error = "Connection timeout"
|
||||
),
|
||||
isChecking = false,
|
||||
isSelected = false,
|
||||
onClick = {}
|
||||
)
|
||||
|
||||
ServerStatusRow(
|
||||
server = "http://checking-server.com:8000",
|
||||
serverStatus = null,
|
||||
isChecking = true,
|
||||
isSelected = false,
|
||||
onClick = {}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package kr.smartsoltech.wellshe.ui.components
|
||||
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
@Composable
|
||||
fun PermissionRequestDialog(
|
||||
permissionText: String,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Требуется разрешение") },
|
||||
text = { Text(permissionText) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = onConfirm) {
|
||||
Text("Настройки")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text("Отмена")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -31,7 +31,8 @@ import java.util.Locale
|
||||
fun CycleScreen(
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: CycleViewModel = hiltViewModel(),
|
||||
onNavigateToSettings: () -> Unit = {} // Добавляем параметр для навигации к настройкам
|
||||
onNavigateToSettings: () -> Unit = {}, // Параметр для навигации к настройкам
|
||||
onNavigateToEmergency: () -> Unit = {} // Добавляем параметр для навигации к экрану экстренной помощи
|
||||
) {
|
||||
val uiState by viewModel.uiState.collectAsState()
|
||||
val scrollState = rememberScrollState()
|
||||
|
||||
@@ -83,13 +83,6 @@ fun DashboardScreen(
|
||||
)
|
||||
}
|
||||
|
||||
item {
|
||||
SleepCard(
|
||||
sleepData = uiState.sleepData,
|
||||
onClick = { onNavigate("sleep") }
|
||||
)
|
||||
}
|
||||
|
||||
item {
|
||||
RecentWorkoutsCard(
|
||||
workouts = uiState.recentWorkouts,
|
||||
@@ -404,26 +397,26 @@ private fun HealthOverviewCard(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceEvenly
|
||||
) {
|
||||
HealthMetric(
|
||||
label = "Пульс",
|
||||
value = "${healthData.heartRate}",
|
||||
unit = "bpm",
|
||||
icon = Icons.Default.Favorite
|
||||
)
|
||||
|
||||
HealthMetric(
|
||||
label = "Настроение",
|
||||
value = getMoodEmoji(healthData.mood),
|
||||
unit = "",
|
||||
icon = Icons.Default.Mood
|
||||
)
|
||||
|
||||
HealthMetric(
|
||||
label = "Энергия",
|
||||
value = "${healthData.energyLevel}",
|
||||
unit = "/10",
|
||||
icon = Icons.Default.Battery6Bar
|
||||
)
|
||||
|
||||
HealthMetric(
|
||||
label = "Симптомы",
|
||||
value = "${healthData.symptoms.size}",
|
||||
unit = "",
|
||||
icon = Icons.Default.HealthAndSafety
|
||||
)
|
||||
|
||||
HealthMetric(
|
||||
label = "Заметки",
|
||||
value = if (healthData.notes.isNotEmpty()) "✓" else "—",
|
||||
unit = "",
|
||||
icon = Icons.Default.Notes
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -479,63 +472,6 @@ private fun HealthMetric(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SleepCard(
|
||||
sleepData: SleepData,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onClick() },
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = NeutralWhite),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Bedtime,
|
||||
contentDescription = null,
|
||||
tint = PrimaryPink,
|
||||
modifier = Modifier.size(40.dp)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
|
||||
Column(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = "Сон",
|
||||
style = MaterialTheme.typography.titleMedium.copy(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = TextPrimary
|
||||
)
|
||||
)
|
||||
|
||||
Text(
|
||||
text = "${sleepData.sleepDuration}ч • ${getSleepQualityText(sleepData.sleepQuality)}",
|
||||
style = MaterialTheme.typography.bodyMedium.copy(
|
||||
color = TextSecondary
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
Icon(
|
||||
imageVector = Icons.Default.ChevronRight,
|
||||
contentDescription = null,
|
||||
tint = NeutralGray
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RecentWorkoutsCard(
|
||||
workouts: List<WorkoutData>,
|
||||
@@ -605,7 +541,7 @@ private fun WorkoutItem(
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = getWorkoutIcon(workout.type),
|
||||
imageVector = Icons.Default.FitnessCenter,
|
||||
contentDescription = null,
|
||||
tint = PrimaryPink,
|
||||
modifier = Modifier.size(20.dp)
|
||||
@@ -617,7 +553,7 @@ private fun WorkoutItem(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = getWorkoutTypeText(workout.type),
|
||||
text = workout.name,
|
||||
style = MaterialTheme.typography.bodyMedium.copy(
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = TextPrimary
|
||||
@@ -662,12 +598,12 @@ private val quickActions = listOf(
|
||||
textColor = SecondaryBlue
|
||||
),
|
||||
QuickAction(
|
||||
title = "Отметить сон",
|
||||
icon = Icons.Default.Bedtime,
|
||||
route = "sleep",
|
||||
backgroundColor = AccentPurpleLight,
|
||||
iconColor = AccentPurple,
|
||||
textColor = AccentPurple
|
||||
title = "Экстренная помощь",
|
||||
icon = Icons.Default.Emergency,
|
||||
route = "emergency",
|
||||
backgroundColor = ErrorRedLight,
|
||||
iconColor = ErrorRed,
|
||||
textColor = ErrorRed
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -8,19 +8,14 @@ import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.launch
|
||||
import kr.smartsoltech.wellshe.data.entity.CyclePeriodEntity
|
||||
import kr.smartsoltech.wellshe.data.entity.SleepLogEntity
|
||||
import kr.smartsoltech.wellshe.data.entity.HealthRecordEntity
|
||||
import kr.smartsoltech.wellshe.data.repository.WellSheRepository
|
||||
import kr.smartsoltech.wellshe.domain.model.*
|
||||
import javax.inject.Inject
|
||||
import java.time.LocalDate
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
data class DashboardUiState(
|
||||
val user: User = User(),
|
||||
val todayHealth: HealthData = HealthData(),
|
||||
val sleepData: SleepData = SleepData(),
|
||||
val cycleData: CycleData = CycleData(),
|
||||
val recentWorkouts: List<WorkoutData> = emptyList(),
|
||||
val todaySteps: Int = 0,
|
||||
@@ -53,37 +48,13 @@ class DashboardViewModel @Inject constructor(
|
||||
_uiState.value = _uiState.value.copy(user = user)
|
||||
}
|
||||
|
||||
// Загружаем данные о здоровье
|
||||
repository.getTodayHealthData().catch {
|
||||
// Игнорируем ошибки, используем дефолтные данные
|
||||
}.collect { healthEntity: HealthRecordEntity? ->
|
||||
val healthData = healthEntity?.let { convertHealthEntityToModel(it) } ?: HealthData()
|
||||
// TODO: Временно используем заглушки для данных о здоровье
|
||||
val healthData = HealthData()
|
||||
_uiState.value = _uiState.value.copy(todayHealth = healthData)
|
||||
}
|
||||
|
||||
// Загружаем данные о сне
|
||||
loadSleepData()
|
||||
|
||||
// Загружаем данные о цикле
|
||||
repository.getRecentPeriods().let { periods ->
|
||||
val cycleEntity = periods.firstOrNull()
|
||||
val cycleData = cycleEntity?.let { convertCycleEntityToModel(it) } ?: CycleData()
|
||||
// TODO: Временно используем заглушки для данных о цикле
|
||||
val cycleData = CycleData()
|
||||
_uiState.value = _uiState.value.copy(cycleData = cycleData)
|
||||
}
|
||||
|
||||
// Загружаем тренировки
|
||||
repository.getRecentWorkouts().catch {
|
||||
// Игнорируем ошибки
|
||||
}.collect { workoutEntities: List<WorkoutSession> ->
|
||||
val workouts = workoutEntities.map { convertWorkoutEntityToModel(it) }
|
||||
_uiState.value = _uiState.value.copy(recentWorkouts = workouts)
|
||||
}
|
||||
|
||||
// Загружаем шаги за сегодня
|
||||
loadTodayFitnessData()
|
||||
|
||||
// Загружаем воду за сегодня
|
||||
loadTodayWaterData()
|
||||
|
||||
_uiState.value = _uiState.value.copy(isLoading = false)
|
||||
|
||||
@@ -96,136 +67,28 @@ class DashboardViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun loadSleepData() {
|
||||
try {
|
||||
val yesterday = LocalDate.now().minusDays(1)
|
||||
val sleepEntity = repository.getSleepForDate(yesterday)
|
||||
val sleepData = sleepEntity?.let { convertSleepEntityToModel(it) } ?: SleepData()
|
||||
_uiState.value = _uiState.value.copy(sleepData = sleepData)
|
||||
} catch (_: Exception) {
|
||||
// Игнорируем ошибки загрузки сна
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun loadTodayFitnessData() {
|
||||
try {
|
||||
val today = LocalDate.now()
|
||||
repository.getFitnessDataForDate(today).catch {
|
||||
// Игнорируем ошибки
|
||||
}.collect { fitnessData: FitnessData ->
|
||||
_uiState.value = _uiState.value.copy(todaySteps = fitnessData.steps)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Игнорируем ошибки загрузки фитнеса
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun loadTodayWaterData() {
|
||||
try {
|
||||
val today = LocalDate.now()
|
||||
repository.getWaterIntakeForDate(today).catch {
|
||||
// Игнорируем ошибки
|
||||
}.collect { waterIntakes: List<WaterIntake> ->
|
||||
val totalAmount = waterIntakes.sumOf { it.amount.toDouble() }.toFloat()
|
||||
_uiState.value = _uiState.value.copy(todayWater = totalAmount)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Игнорируем ошибки загрузки воды
|
||||
}
|
||||
}
|
||||
|
||||
fun clearError() {
|
||||
_uiState.value = _uiState.value.copy(error = null)
|
||||
}
|
||||
|
||||
// Функции преобразования Entity -> Model
|
||||
private fun convertHealthEntityToModel(entity: HealthRecordEntity): HealthData {
|
||||
return HealthData(
|
||||
id = entity.id.toString(),
|
||||
userId = "current_user",
|
||||
date = entity.date,
|
||||
weight = entity.weight ?: 0f,
|
||||
heartRate = entity.heartRate ?: 70,
|
||||
bloodPressureSystolic = entity.bloodPressureS ?: 120,
|
||||
bloodPressureDiastolic = entity.bloodPressureD ?: 80,
|
||||
mood = convertMoodStringToEnum(entity.mood ?: "neutral"),
|
||||
energyLevel = entity.energyLevel ?: 5,
|
||||
stressLevel = entity.stressLevel ?: 5,
|
||||
symptoms = entity.symptoms ?: emptyList()
|
||||
)
|
||||
}
|
||||
|
||||
private fun convertSleepEntityToModel(entity: SleepLogEntity): SleepData {
|
||||
return SleepData(
|
||||
id = entity.id.toString(),
|
||||
userId = "current_user",
|
||||
date = entity.date,
|
||||
bedTime = java.time.LocalTime.parse(entity.bedTime),
|
||||
wakeTime = java.time.LocalTime.parse(entity.wakeTime),
|
||||
sleepDuration = entity.duration,
|
||||
sleepQuality = convertSleepQualityStringToEnum(entity.quality)
|
||||
)
|
||||
}
|
||||
|
||||
private fun convertCycleEntityToModel(entity: CyclePeriodEntity): CycleData {
|
||||
return CycleData(
|
||||
id = entity.id.toString(),
|
||||
userId = "current_user",
|
||||
cycleLength = entity.cycleLength ?: 28,
|
||||
periodLength = entity.endDate?.let {
|
||||
ChronoUnit.DAYS.between(entity.startDate, it).toInt() + 1
|
||||
} ?: 5,
|
||||
lastPeriodDate = entity.startDate,
|
||||
nextPeriodDate = entity.startDate.plusDays((entity.cycleLength ?: 28).toLong()),
|
||||
ovulationDate = entity.startDate.plusDays(((entity.cycleLength ?: 28) / 2).toLong())
|
||||
)
|
||||
}
|
||||
|
||||
private fun convertWorkoutEntityToModel(entity: kr.smartsoltech.wellshe.domain.model.WorkoutSession): WorkoutData {
|
||||
return WorkoutData(
|
||||
id = entity.id.toString(),
|
||||
userId = "current_user",
|
||||
date = entity.date,
|
||||
type = convertWorkoutTypeStringToEnum(entity.type),
|
||||
duration = entity.duration,
|
||||
intensity = WorkoutIntensity.MODERATE, // По умолчанию, так как в WorkoutSession нет intensity
|
||||
caloriesBurned = entity.caloriesBurned
|
||||
)
|
||||
}
|
||||
|
||||
// Вспомогательные функции преобразования
|
||||
private fun convertMoodStringToEnum(mood: String): Mood {
|
||||
return when (mood.lowercase()) {
|
||||
"very_sad" -> Mood.VERY_SAD
|
||||
"sad" -> Mood.SAD
|
||||
"neutral" -> Mood.NEUTRAL
|
||||
"happy" -> Mood.HAPPY
|
||||
"very_happy" -> Mood.VERY_HAPPY
|
||||
else -> Mood.NEUTRAL
|
||||
}
|
||||
}
|
||||
|
||||
private fun convertSleepQualityStringToEnum(quality: String): SleepQuality {
|
||||
return when (quality.lowercase()) {
|
||||
"poor" -> SleepQuality.POOR
|
||||
"fair" -> SleepQuality.FAIR
|
||||
"good" -> SleepQuality.GOOD
|
||||
"excellent" -> SleepQuality.EXCELLENT
|
||||
else -> SleepQuality.GOOD
|
||||
}
|
||||
}
|
||||
|
||||
private fun convertWorkoutTypeStringToEnum(type: String): WorkoutType {
|
||||
return when (type.lowercase()) {
|
||||
"кардио", "cardio" -> WorkoutType.CARDIO
|
||||
"силовая", "strength" -> WorkoutType.STRENGTH
|
||||
"йога", "yoga" -> WorkoutType.YOGA
|
||||
"пилатес", "pilates" -> WorkoutType.PILATES
|
||||
"бег", "running" -> WorkoutType.RUNNING
|
||||
"ходьба", "walking" -> WorkoutType.WALKING
|
||||
"велосипед", "cycling" -> WorkoutType.CYCLING
|
||||
"плавание", "swimming" -> WorkoutType.SWIMMING
|
||||
else -> WorkoutType.CARDIO
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Упрощенные модели данных для Dashboard
|
||||
data class HealthData(
|
||||
val energyLevel: Int = 5,
|
||||
val symptoms: List<String> = emptyList(),
|
||||
val notes: String = ""
|
||||
)
|
||||
|
||||
data class CycleData(
|
||||
val currentDay: Int = 1,
|
||||
val nextPeriodDate: LocalDate? = null,
|
||||
val cycleLength: Int = 28
|
||||
)
|
||||
|
||||
data class WorkoutData(
|
||||
val id: Long = 0,
|
||||
val name: String = "",
|
||||
val duration: Int = 0,
|
||||
val caloriesBurned: Int = 0,
|
||||
val date: LocalDate = LocalDate.now()
|
||||
)
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
package kr.smartsoltech.wellshe.ui.emergency
|
||||
|
||||
import android.provider.Settings
|
||||
import android.net.Uri
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.BatteryManager
|
||||
import android.os.Bundle
|
||||
import android.os.Vibrator
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Toast
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.core.app.ActivityCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import kr.smartsoltech.wellshe.R
|
||||
import kr.smartsoltech.wellshe.databinding.FragmentEmergencyBinding
|
||||
import kr.smartsoltech.wellshe.di.ViewModelFactory
|
||||
import kr.smartsoltech.wellshe.ui.emergency.EmergencyViewModel.EmergencyState
|
||||
import javax.inject.Inject
|
||||
import kotlin.text.get
|
||||
import android.content.Intent
|
||||
|
||||
|
||||
/**
|
||||
* Фрагмент для экрана экстренных оповещений
|
||||
*/
|
||||
class EmergencyFragment : Fragment(), LocationListener {
|
||||
|
||||
private var _binding: FragmentEmergencyBinding? = null
|
||||
private val binding get() = _binding!!
|
||||
|
||||
private lateinit var locationPermissionLauncher: androidx.activity.result.ActivityResultLauncher<Array<String>>
|
||||
|
||||
@Inject
|
||||
lateinit var viewModelFactory: ViewModelFactory
|
||||
|
||||
private lateinit var viewModel: EmergencyViewModel
|
||||
|
||||
private lateinit var locationManager: LocationManager
|
||||
private var currentLocation: Location? = null
|
||||
private var isLocationUpdatesActive = false
|
||||
|
||||
// Интервал обновления местоположения (мс)
|
||||
private val normalUpdateInterval = 60000L // 1 минута
|
||||
private val emergencyUpdateInterval = 15000L // 15 секунд
|
||||
|
||||
// Коды для запросов разрешений
|
||||
private val locationPermissionRequestCode = 100
|
||||
|
||||
override fun onCreateView(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View {
|
||||
_binding = FragmentEmergencyBinding.inflate(inflater, container, false)
|
||||
return binding.root
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
|
||||
// Получаем ViewModel через DI
|
||||
viewModel = ViewModelProvider(this, viewModelFactory)[EmergencyViewModel::class.java]
|
||||
|
||||
// Инициализируем менеджер местоположения
|
||||
locationManager = requireContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||
|
||||
locationPermissionLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { permissions ->
|
||||
val granted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true ||
|
||||
permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true
|
||||
if (granted) {
|
||||
startLocationUpdates(false)
|
||||
enableEmergencyUI(true)
|
||||
} else {
|
||||
enableEmergencyUI(false)
|
||||
showLocationPermissionDialog()
|
||||
}
|
||||
}
|
||||
setupEmergencyButton()
|
||||
observeViewModel()
|
||||
checkLocationPermissions()
|
||||
}
|
||||
|
||||
private fun setupEmergencyButton() {
|
||||
// Настраиваем кнопку SOS
|
||||
binding.buttonSos.setOnClickListener {
|
||||
// Показываем диалог подтверждения
|
||||
showEmergencyConfirmationDialog()
|
||||
}
|
||||
|
||||
// Настраиваем кнопку отмены оповещения
|
||||
binding.buttonCancelAlert.setOnClickListener {
|
||||
showCancelConfirmationDialog()
|
||||
}
|
||||
}
|
||||
|
||||
private fun showEmergencyConfirmationDialog() {
|
||||
AlertDialog.Builder(requireContext())
|
||||
.setTitle("Подтверждение")
|
||||
.setMessage("Вы уверены, что хотите отправить экстренное оповещение?")
|
||||
.setPositiveButton("Отправить") { _, _ ->
|
||||
createEmergencyAlert()
|
||||
}
|
||||
.setNegativeButton("Отмена", null)
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun showCancelConfirmationDialog() {
|
||||
AlertDialog.Builder(requireContext())
|
||||
.setTitle("Отмена оповещения")
|
||||
.setMessage("Вы уверены, что хотите отменить экстренное оповещение?")
|
||||
.setPositiveButton("Да") { _, _ ->
|
||||
viewModel.cancelAlert("Отменено пользователем")
|
||||
}
|
||||
.setNegativeButton("Нет", null)
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun createEmergencyAlert() {
|
||||
// Проверяем доступность местоположения
|
||||
val location = currentLocation
|
||||
if (location != null) {
|
||||
// Получаем уровень заряда батареи
|
||||
val batteryLevel = getBatteryLevel()
|
||||
|
||||
// Создаем экстренное оповещение
|
||||
viewModel.createEmergencyAlert(
|
||||
latitude = location.latitude,
|
||||
longitude = location.longitude,
|
||||
batteryLevel = batteryLevel
|
||||
)
|
||||
|
||||
// Вибрируем, чтобы дать обратную связь пользователю
|
||||
vibratePhone()
|
||||
|
||||
// Активируем более частое обновление местоположения
|
||||
startLocationUpdates(true)
|
||||
} else {
|
||||
Toast.makeText(requireContext(), "Не удалось определить местоположение", Toast.LENGTH_LONG).show()
|
||||
// Пробуем запросить местоположение принудительно
|
||||
requestLocationUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
private fun observeViewModel() {
|
||||
viewModel.emergencyState.observe(viewLifecycleOwner) { state ->
|
||||
when (state) {
|
||||
is EmergencyState.Inactive -> {
|
||||
binding.emergencyStatusGroup.visibility = View.GONE
|
||||
binding.buttonSos.visibility = View.VISIBLE
|
||||
binding.buttonCancelAlert.visibility = View.GONE
|
||||
// При неактивном состоянии переключаемся на нормальную частоту обновлений
|
||||
startLocationUpdates(false)
|
||||
}
|
||||
is EmergencyState.Creating -> {
|
||||
binding.emergencyStatusGroup.visibility = View.VISIBLE
|
||||
binding.buttonSos.visibility = View.GONE
|
||||
binding.buttonCancelAlert.visibility = View.GONE
|
||||
binding.statusText.text = "Создание оповещения..."
|
||||
binding.progressBar.visibility = View.VISIBLE
|
||||
}
|
||||
is EmergencyState.Active -> {
|
||||
binding.emergencyStatusGroup.visibility = View.VISIBLE
|
||||
binding.buttonSos.visibility = View.GONE
|
||||
binding.buttonCancelAlert.visibility = View.VISIBLE
|
||||
binding.statusText.text = "Оповещение активно\nID: ${state.alertResponse.alertId}"
|
||||
binding.progressBar.visibility = View.GONE
|
||||
binding.statusIndicator.setImageResource(R.drawable.ic_status_active)
|
||||
}
|
||||
is EmergencyState.Cancelled -> {
|
||||
binding.emergencyStatusGroup.visibility = View.VISIBLE
|
||||
binding.buttonSos.visibility = View.VISIBLE
|
||||
binding.buttonCancelAlert.visibility = View.GONE
|
||||
binding.statusText.text = "Оповещение отменено"
|
||||
binding.progressBar.visibility = View.GONE
|
||||
binding.statusIndicator.setImageResource(R.drawable.ic_status_cancelled)
|
||||
|
||||
// После короткой задержки скрываем статус и возвращаемся к нормальному состоянию
|
||||
binding.root.postDelayed({
|
||||
viewModel.resetState()
|
||||
}, 3000)
|
||||
}
|
||||
is EmergencyState.Resolved -> {
|
||||
binding.emergencyStatusGroup.visibility = View.VISIBLE
|
||||
binding.buttonSos.visibility = View.VISIBLE
|
||||
binding.buttonCancelAlert.visibility = View.GONE
|
||||
binding.statusText.text = "Оповещение обработано службами"
|
||||
binding.progressBar.visibility = View.GONE
|
||||
binding.statusIndicator.setImageResource(R.drawable.ic_status_resolved)
|
||||
|
||||
// После короткой задержки скрываем статус
|
||||
binding.root.postDelayed({
|
||||
viewModel.resetState()
|
||||
}, 3000)
|
||||
}
|
||||
is EmergencyState.Error -> {
|
||||
binding.emergencyStatusGroup.visibility = View.VISIBLE
|
||||
binding.buttonSos.visibility = View.VISIBLE
|
||||
binding.buttonCancelAlert.visibility = View.GONE
|
||||
binding.statusText.text = "Ошибка: ${state.message}"
|
||||
binding.progressBar.visibility = View.GONE
|
||||
binding.statusIndicator.setImageResource(R.drawable.ic_status_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewModel.alertStatus.observe(viewLifecycleOwner) { status ->
|
||||
status?.let {
|
||||
// Обновляем информацию о статусе оповещения
|
||||
binding.notifiedContactsCount.text = "${it.notifiedContacts.count { contact -> contact.status == "notified" }}/${it.notifiedContacts.size}"
|
||||
|
||||
val emergencyServicesText = if (it.emergencyServicesNotified) {
|
||||
"Службы экстренной помощи уведомлены"
|
||||
} else {
|
||||
"Ожидаем ответа служб"
|
||||
}
|
||||
binding.emergencyServicesStatus.text = emergencyServicesText
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getBatteryLevel(): Int {
|
||||
val batteryManager = requireContext().getSystemService(Context.BATTERY_SERVICE) as BatteryManager
|
||||
return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
|
||||
}
|
||||
|
||||
private fun vibratePhone() {
|
||||
val vibrator = requireContext().getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
|
||||
vibrator.vibrate(longArrayOf(0, 500, 200, 500), -1)
|
||||
}
|
||||
|
||||
private fun checkLocationPermissions() {
|
||||
val fineGranted = ActivityCompat.checkSelfPermission(
|
||||
requireContext(),
|
||||
Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
val coarseGranted = ActivityCompat.checkSelfPermission(
|
||||
requireContext(),
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
if (!fineGranted && !coarseGranted) {
|
||||
locationPermissionLauncher.launch(
|
||||
arrayOf(
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
)
|
||||
)
|
||||
} else {
|
||||
startLocationUpdates(false)
|
||||
enableEmergencyUI(true)
|
||||
}
|
||||
}
|
||||
|
||||
private fun enableEmergencyUI(enabled: Boolean) {
|
||||
binding.buttonSos.isEnabled = enabled
|
||||
binding.buttonCancelAlert.isEnabled = enabled
|
||||
binding.mapView.isEnabled = enabled
|
||||
// Если есть другие кнопки/типы сигналов, добавьте их сюда
|
||||
}
|
||||
|
||||
private fun showLocationPermissionDialog() {
|
||||
AlertDialog.Builder(requireContext())
|
||||
.setTitle("Доступ к геопозиции")
|
||||
.setMessage("Для работы экстренных функций нужен доступ к геопозиции. Откройте настройки и разрешите доступ.")
|
||||
.setPositiveButton("Открыть настройки") { _, _ ->
|
||||
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
|
||||
intent.data = Uri.fromParts("package", requireContext().packageName, null)
|
||||
startActivity(intent)
|
||||
}
|
||||
.setNegativeButton("Отмена", null)
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun startLocationUpdates(isEmergency: Boolean) {
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
requireContext(),
|
||||
Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Останавливаем предыдущие обновления, если они были
|
||||
if (isLocationUpdatesActive) {
|
||||
locationManager.removeUpdates(this)
|
||||
}
|
||||
|
||||
// Устанавливаем интервал обновления в зависимости от режима
|
||||
val updateInterval = if (isEmergency) emergencyUpdateInterval else normalUpdateInterval
|
||||
|
||||
try {
|
||||
// Запрашиваем обновления местоположения
|
||||
locationManager.requestLocationUpdates(
|
||||
LocationManager.GPS_PROVIDER,
|
||||
updateInterval,
|
||||
10f, // минимальное расстояние для обновления (метры)
|
||||
this
|
||||
)
|
||||
isLocationUpdatesActive = true
|
||||
|
||||
// Сразу запрашиваем последнее известное местоположение
|
||||
requestLocationUpdate()
|
||||
} catch (e: Exception) {
|
||||
Toast.makeText(requireContext(), "Ошибка получения местоположения", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestLocationUpdate() {
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
requireContext(),
|
||||
Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Пытаемся получить последнее известное местоположение
|
||||
val lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
|
||||
if (lastLocation != null) {
|
||||
currentLocation = lastLocation
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLocationChanged(location: Location) {
|
||||
currentLocation = location
|
||||
|
||||
// Если оповещение активно, отправляем обновленные координаты
|
||||
if (viewModel.emergencyState.value is EmergencyState.Active) {
|
||||
viewModel.updateLocation(
|
||||
latitude = location.latitude,
|
||||
longitude = location.longitude,
|
||||
accuracy = location.accuracy,
|
||||
batteryLevel = getBatteryLevel()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
// Если нет активного оповещения, останавливаем обновления местоположения
|
||||
if (viewModel.emergencyState.value !is EmergencyState.Active && isLocationUpdatesActive) {
|
||||
locationManager.removeUpdates(this)
|
||||
isLocationUpdatesActive = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
// Если есть активное оповещение, возобновляем обновления
|
||||
val isEmergency = viewModel.emergencyState.value is EmergencyState.Active
|
||||
if (isEmergency || !isLocationUpdatesActive) {
|
||||
startLocationUpdates(isEmergency)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
if (isLocationUpdatesActive) {
|
||||
locationManager.removeUpdates(this)
|
||||
isLocationUpdatesActive = false
|
||||
}
|
||||
_binding = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package kr.smartsoltech.wellshe.ui.emergency
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Call
|
||||
import androidx.compose.material.icons.filled.LocationOn
|
||||
import androidx.compose.material.icons.filled.Send
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun EmergencyScreen(
|
||||
onNavigateBack: () -> Unit
|
||||
) {
|
||||
var sendingSos by remember { mutableStateOf(false) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Экстренная помощь") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { onNavigateBack() }) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.ArrowBack,
|
||||
contentDescription = "Назад"
|
||||
)
|
||||
}
|
||||
},
|
||||
colors = TopAppBarDefaults.topAppBarColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||
titleContentColor = MaterialTheme.colorScheme.onErrorContainer
|
||||
)
|
||||
)
|
||||
}
|
||||
) { paddingValues ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues)
|
||||
.padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp)
|
||||
) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.7f)
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
text = "ЭКСТРЕННАЯ СИТУАЦИЯ",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Text(
|
||||
text = "Используйте эту функцию только в случае реальной опасности",
|
||||
textAlign = TextAlign.Center,
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Кнопка SOS
|
||||
Button(
|
||||
onClick = {
|
||||
sendingSos = true
|
||||
// Здесь должна быть логика отправки сигнала SOS
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(80.dp),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
|
||||
enabled = !sendingSos
|
||||
) {
|
||||
if (sendingSos) {
|
||||
CircularProgressIndicator(
|
||||
color = Color.White,
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Отправка сигнала SOS...")
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Send,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(32.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "ОТПРАВИТЬ СИГНАЛ SOS",
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Экстренные контакты
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "Экстренные контакты",
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
EmergencyContactItem(
|
||||
title = "Полиция",
|
||||
phoneNumber = "102"
|
||||
)
|
||||
|
||||
Divider(modifier = Modifier.padding(vertical = 8.dp))
|
||||
|
||||
EmergencyContactItem(
|
||||
title = "Скорая помощь",
|
||||
phoneNumber = "103"
|
||||
)
|
||||
|
||||
Divider(modifier = Modifier.padding(vertical = 8.dp))
|
||||
|
||||
EmergencyContactItem(
|
||||
title = "Единый номер экстренных служб",
|
||||
phoneNumber = "112"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Текущее местоположение
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.LocationOn,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Ваше местоположение",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Text(
|
||||
text = "Определяется...",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EmergencyContactItem(
|
||||
title: String,
|
||||
phoneNumber: String
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Text(
|
||||
text = phoneNumber,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
|
||||
IconButton(onClick = { /* Действие звонка */ }) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Call,
|
||||
contentDescription = "Позвонить",
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package kr.smartsoltech.wellshe.ui.emergency
|
||||
|
||||
import androidx.lifecycle.LiveData
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import kotlinx.coroutines.launch
|
||||
import kr.smartsoltech.wellshe.domain.emergency.*
|
||||
import kr.smartsoltech.wellshe.model.emergency.*
|
||||
import kr.smartsoltech.wellshe.util.Result
|
||||
|
||||
/**
|
||||
* ViewModel для управления экстренными оповещениями
|
||||
*/
|
||||
class EmergencyViewModel(
|
||||
private val createEmergencyAlertUseCase: CreateEmergencyAlertUseCase,
|
||||
private val getAlertStatusUseCase: GetAlertStatusUseCase,
|
||||
private val updateLocationUseCase: UpdateLocationUseCase,
|
||||
private val cancelAlertUseCase: CancelAlertUseCase
|
||||
) : ViewModel() {
|
||||
|
||||
private val _emergencyState = MutableLiveData<EmergencyState>(EmergencyState.Inactive)
|
||||
val emergencyState: LiveData<EmergencyState> = _emergencyState
|
||||
|
||||
private val _alertStatus = MutableLiveData<EmergencyAlertStatus?>()
|
||||
val alertStatus: LiveData<EmergencyAlertStatus?> = _alertStatus
|
||||
|
||||
private val _isLoading = MutableLiveData(false)
|
||||
val isLoading: LiveData<Boolean> = _isLoading
|
||||
|
||||
private var currentAlertId: String? = null
|
||||
|
||||
/**
|
||||
* Создание нового экстренного оповещения
|
||||
*/
|
||||
fun createEmergencyAlert(
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
message: String? = null,
|
||||
batteryLevel: Int? = null,
|
||||
contactIds: List<String>? = null
|
||||
) {
|
||||
_isLoading.value = true
|
||||
_emergencyState.value = EmergencyState.Creating
|
||||
|
||||
viewModelScope.launch {
|
||||
when (val result = createEmergencyAlertUseCase(latitude, longitude, message, batteryLevel, contactIds)) {
|
||||
is Result.Success -> {
|
||||
currentAlertId = result.data.alertId
|
||||
_emergencyState.value = EmergencyState.Active(result.data)
|
||||
// После создания оповещения сразу получаем его статус
|
||||
fetchAlertStatus(result.data.alertId)
|
||||
}
|
||||
is Result.Error -> {
|
||||
_emergencyState.value = EmergencyState.Error(result.exception.message ?: "Ошибка создания оповещения")
|
||||
}
|
||||
}
|
||||
_isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение статуса экстренного оповещения
|
||||
*/
|
||||
fun fetchAlertStatus(alertId: String) {
|
||||
_isLoading.value = true
|
||||
|
||||
viewModelScope.launch {
|
||||
when (val result = getAlertStatusUseCase(alertId)) {
|
||||
is Result.Success -> {
|
||||
_alertStatus.value = result.data
|
||||
|
||||
// Обновляем состояние на основе статуса оповещения
|
||||
_emergencyState.value = when (result.data.status.lowercase()) {
|
||||
"active" -> EmergencyState.Active(EmergencyAlertResponse(
|
||||
alertId = result.data.alertId,
|
||||
createdAt = result.data.createdAt,
|
||||
status = result.data.status,
|
||||
message = "Оповещение активно"
|
||||
))
|
||||
"cancelled" -> EmergencyState.Cancelled(result.data.alertId)
|
||||
"resolved" -> EmergencyState.Resolved(result.data.alertId)
|
||||
else -> EmergencyState.Active(EmergencyAlertResponse(
|
||||
alertId = result.data.alertId,
|
||||
createdAt = result.data.createdAt,
|
||||
status = result.data.status,
|
||||
message = "Статус: ${result.data.status}"
|
||||
))
|
||||
}
|
||||
}
|
||||
is Result.Error -> {
|
||||
_emergencyState.value = EmergencyState.Error(result.exception.message ?: "Ошибка получения статуса")
|
||||
}
|
||||
}
|
||||
_isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновление местоположения для активного оповещения
|
||||
*/
|
||||
fun updateLocation(
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
accuracy: Float? = null,
|
||||
batteryLevel: Int? = null
|
||||
) {
|
||||
val alertId = currentAlertId ?: return
|
||||
|
||||
viewModelScope.launch {
|
||||
when (val result = updateLocationUseCase(alertId, latitude, longitude, accuracy, batteryLevel)) {
|
||||
is Result.Success -> {
|
||||
// После успешного обновления местоположения можно запросить текущий статус
|
||||
fetchAlertStatus(alertId)
|
||||
}
|
||||
is Result.Error -> {
|
||||
// Обработка ошибок обновления местоположения
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Отмена экстренного оповещения
|
||||
*/
|
||||
fun cancelAlert(reason: String? = null, details: String? = null) {
|
||||
val alertId = currentAlertId ?: return
|
||||
_isLoading.value = true
|
||||
|
||||
viewModelScope.launch {
|
||||
when (val result = cancelAlertUseCase(alertId, reason, details)) {
|
||||
is Result.Success -> {
|
||||
_emergencyState.value = EmergencyState.Cancelled(alertId)
|
||||
// После отмены оповещения очищаем текущий ID оповещения
|
||||
currentAlertId = null
|
||||
}
|
||||
is Result.Error -> {
|
||||
_emergencyState.value = EmergencyState.Error(result.exception.message ?: "Ошибка отмены оповещения")
|
||||
}
|
||||
}
|
||||
_isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Сброс состояния (например, после завершения сценария экстренного оповещения)
|
||||
*/
|
||||
fun resetState() {
|
||||
currentAlertId = null
|
||||
_emergencyState.value = EmergencyState.Inactive
|
||||
_alertStatus.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Состояния экстренного оповещения
|
||||
*/
|
||||
sealed class EmergencyState {
|
||||
object Inactive : EmergencyState()
|
||||
object Creating : EmergencyState()
|
||||
data class Active(val alertResponse: EmergencyAlertResponse) : EmergencyState()
|
||||
data class Cancelled(val alertId: String) : EmergencyState()
|
||||
data class Resolved(val alertId: String) : EmergencyState()
|
||||
data class Error(val message: String) : EmergencyState()
|
||||
}
|
||||
}
|
||||
@@ -93,9 +93,7 @@ fun HealthOverviewScreen(
|
||||
TodayHealthCard(
|
||||
uiState = uiState,
|
||||
onUpdateVitals = viewModel::updateVitals,
|
||||
onUpdateMood = viewModel::updateMood,
|
||||
onUpdateEnergy = viewModel::updateEnergyLevel,
|
||||
onUpdateStress = viewModel::updateStressLevel
|
||||
onUpdateEnergy = viewModel::updateEnergyLevel
|
||||
)
|
||||
}
|
||||
|
||||
@@ -133,9 +131,7 @@ fun HealthOverviewScreen(
|
||||
private fun TodayHealthCard(
|
||||
uiState: HealthUiState,
|
||||
onUpdateVitals: (Float?, Int?, Int?, Int?, Float?) -> Unit,
|
||||
onUpdateMood: (String) -> Unit,
|
||||
onUpdateEnergy: (Int) -> Unit,
|
||||
onUpdateStress: (Int) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
var weight by remember { mutableStateOf(uiState.todayRecord?.weight?.toString() ?: "") }
|
||||
@@ -269,16 +265,7 @@ private fun TodayHealthCard(
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Настроение
|
||||
MoodSection(
|
||||
currentMood = uiState.todayRecord?.mood ?: "neutral",
|
||||
onMoodChange = onUpdateMood,
|
||||
isEditMode = uiState.isEditMode
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Уровень энергии и стресса
|
||||
// Уровень энергии
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp)
|
||||
@@ -288,18 +275,9 @@ private fun TodayHealthCard(
|
||||
value = uiState.todayRecord?.energyLevel ?: 5,
|
||||
onValueChange = onUpdateEnergy,
|
||||
isEditMode = uiState.isEditMode,
|
||||
modifier = Modifier.weight(1f),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
color = WarningOrange
|
||||
)
|
||||
|
||||
LevelSlider(
|
||||
label = "Стресс",
|
||||
value = uiState.todayRecord?.stressLevel ?: 5,
|
||||
onValueChange = onUpdateStress,
|
||||
isEditMode = uiState.isEditMode,
|
||||
modifier = Modifier.weight(1f),
|
||||
color = ErrorRed
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -352,68 +330,6 @@ private fun VitalMetric(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MoodSection(
|
||||
currentMood: String,
|
||||
onMoodChange: (String) -> Unit,
|
||||
isEditMode: Boolean,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Column(modifier = modifier) {
|
||||
Text(
|
||||
text = "Настроение",
|
||||
style = MaterialTheme.typography.bodyMedium.copy(
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = TextPrimary
|
||||
)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
if (isEditMode) {
|
||||
LazyRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
items(healthMoods) { mood ->
|
||||
FilterChip(
|
||||
onClick = { onMoodChange(mood.key) },
|
||||
label = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(mood.emoji)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text(mood.name)
|
||||
}
|
||||
},
|
||||
selected = currentMood == mood.key,
|
||||
colors = FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor = SuccessGreenLight,
|
||||
selectedLabelColor = SuccessGreen
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
val currentMoodData = healthMoods.find { it.key == currentMood } ?: healthMoods[2]
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = currentMoodData.emoji,
|
||||
style = MaterialTheme.typography.headlineSmall
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = currentMoodData.name,
|
||||
style = MaterialTheme.typography.bodyLarge.copy(
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = TextPrimary
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LevelSlider(
|
||||
label: String,
|
||||
@@ -679,18 +595,8 @@ private fun NotesCard(
|
||||
}
|
||||
|
||||
// Данные для UI
|
||||
private data class HealthMoodData(val key: String, val name: String, val emoji: String)
|
||||
|
||||
private val healthMoods = listOf(
|
||||
HealthMoodData("very_sad", "Очень плохо", "😢"),
|
||||
HealthMoodData("sad", "Плохо", "😔"),
|
||||
HealthMoodData("neutral", "Нормально", "😐"),
|
||||
HealthMoodData("happy", "Хорошо", "😊"),
|
||||
HealthMoodData("very_happy", "Отлично", "😄")
|
||||
)
|
||||
|
||||
private val healthSymptoms = listOf(
|
||||
"Головная боль", "Усталость", "Тошнота", "Головокружение",
|
||||
"Боль в спине", "Боль в суставах", "Бессонница", "Стресс",
|
||||
"Боль в спине", "Боль в суставах", "Бессонница",
|
||||
"Простуда", "Аллергия", "Боль в животе", "Другое"
|
||||
)
|
||||
|
||||
@@ -248,9 +248,7 @@ private fun VitalSignsCard(
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = "",
|
||||
energyLevel = 5,
|
||||
stressLevel = 5,
|
||||
symptoms = emptyList(),
|
||||
notes = ""
|
||||
)
|
||||
@@ -275,9 +273,7 @@ private fun VitalSignsCard(
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = "",
|
||||
energyLevel = 5,
|
||||
stressLevel = 5,
|
||||
symptoms = emptyList(),
|
||||
notes = ""
|
||||
)
|
||||
@@ -305,9 +301,7 @@ private fun VitalSignsCard(
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = "",
|
||||
energyLevel = 5,
|
||||
stressLevel = 5,
|
||||
symptoms = emptyList(),
|
||||
notes = ""
|
||||
)
|
||||
@@ -333,9 +327,7 @@ private fun VitalSignsCard(
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = "",
|
||||
energyLevel = 5,
|
||||
stressLevel = 5,
|
||||
symptoms = emptyList(),
|
||||
notes = ""
|
||||
)
|
||||
|
||||
@@ -37,30 +37,41 @@ class HealthViewModel @Inject constructor(
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
|
||||
try {
|
||||
// Загружаем данные о здоровье за сегодня
|
||||
repository.getTodayHealthData().collect { todayRecord: HealthRecordEntity? ->
|
||||
// TODO: Временно используем заглушки, пока не добавим методы в repository
|
||||
_uiState.value = _uiState.value.copy(
|
||||
todayRecord = todayRecord,
|
||||
lastUpdateDate = todayRecord?.date,
|
||||
todaySymptoms = todayRecord?.symptoms ?: emptyList(),
|
||||
todayNotes = todayRecord?.notes ?: "",
|
||||
todayRecord = null,
|
||||
lastUpdateDate = null,
|
||||
todaySymptoms = emptyList(),
|
||||
todayNotes = "",
|
||||
recentRecords = emptyList(),
|
||||
weeklyWeights = emptyMap(),
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
|
||||
// Загружаем данные о здоровье за сегодня
|
||||
// repository.getTodayHealthData().collect { todayRecord: HealthRecordEntity? ->
|
||||
// _uiState.value = _uiState.value.copy(
|
||||
// todayRecord = todayRecord,
|
||||
// lastUpdateDate = todayRecord?.date,
|
||||
// todaySymptoms = todayRecord?.symptoms ?: emptyList(),
|
||||
// todayNotes = todayRecord?.notes ?: "",
|
||||
// isLoading = false
|
||||
// )
|
||||
// }
|
||||
|
||||
// Загружаем недельные данные веса
|
||||
repository.getAllHealthRecords().collect { records: List<HealthRecordEntity> ->
|
||||
val weightsMap = records
|
||||
.filter { it.weight != null && it.weight > 0f }
|
||||
.groupBy { it.date }
|
||||
.mapValues { entry -> entry.value.last().weight ?: 0f }
|
||||
_uiState.value = _uiState.value.copy(weeklyWeights = weightsMap)
|
||||
}
|
||||
// repository.getAllHealthRecords().collect { records: List<HealthRecordEntity> ->
|
||||
// val weightsMap = records
|
||||
// .filter { it.weight != null && it.weight > 0f }
|
||||
// .groupBy { it.date }
|
||||
// .mapValues { entry -> entry.value.last().weight ?: 0f }
|
||||
// _uiState.value = _uiState.value.copy(weeklyWeights = weightsMap)
|
||||
// }
|
||||
|
||||
// Загружаем последние записи
|
||||
repository.getRecentHealthRecords().collect { records: List<HealthRecordEntity> ->
|
||||
_uiState.value = _uiState.value.copy(recentRecords = records)
|
||||
}
|
||||
// repository.getRecentHealthRecords().collect { records: List<HealthRecordEntity> ->
|
||||
// _uiState.value = _uiState.value.copy(recentRecords = records)
|
||||
// }
|
||||
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = _uiState.value.copy(
|
||||
@@ -91,42 +102,13 @@ class HealthViewModel @Inject constructor(
|
||||
bloodPressureS = bpSystolic,
|
||||
bloodPressureD = bpDiastolic,
|
||||
temperature = temperature,
|
||||
mood = "",
|
||||
energyLevel = 5,
|
||||
stressLevel = 5,
|
||||
symptoms = emptyList(),
|
||||
notes = ""
|
||||
)
|
||||
}
|
||||
repository.saveHealthRecord(updatedRecord)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = _uiState.value.copy(error = e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateMood(mood: String) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val currentRecord = _uiState.value.todayRecord
|
||||
val updatedRecord = if (currentRecord != null) {
|
||||
currentRecord.copy(mood = mood)
|
||||
} else {
|
||||
HealthRecordEntity(
|
||||
date = LocalDate.now(),
|
||||
weight = 0f,
|
||||
heartRate = 0,
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = mood,
|
||||
energyLevel = 5,
|
||||
stressLevel = 5,
|
||||
symptoms = emptyList(),
|
||||
notes = ""
|
||||
)
|
||||
}
|
||||
repository.saveHealthRecord(updatedRecord)
|
||||
// TODO: Добавить метод saveHealthRecord в repository
|
||||
// repository.saveHealthRecord(updatedRecord)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = _uiState.value.copy(error = e.message)
|
||||
}
|
||||
@@ -142,47 +124,18 @@ class HealthViewModel @Inject constructor(
|
||||
} else {
|
||||
HealthRecordEntity(
|
||||
date = LocalDate.now(),
|
||||
weight = 0f,
|
||||
heartRate = 0,
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = "",
|
||||
weight = null,
|
||||
heartRate = null,
|
||||
bloodPressureS = null,
|
||||
bloodPressureD = null,
|
||||
temperature = null,
|
||||
energyLevel = energy,
|
||||
stressLevel = 5,
|
||||
symptoms = emptyList(),
|
||||
notes = ""
|
||||
)
|
||||
}
|
||||
repository.saveHealthRecord(updatedRecord)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = _uiState.value.copy(error = e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateStressLevel(stress: Int) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val currentRecord = _uiState.value.todayRecord
|
||||
val updatedRecord = if (currentRecord != null) {
|
||||
currentRecord.copy(stressLevel = stress)
|
||||
} else {
|
||||
HealthRecordEntity(
|
||||
date = LocalDate.now(),
|
||||
weight = 0f,
|
||||
heartRate = 0,
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = "",
|
||||
energyLevel = 5,
|
||||
stressLevel = stress,
|
||||
symptoms = emptyList(),
|
||||
notes = ""
|
||||
)
|
||||
}
|
||||
repository.saveHealthRecord(updatedRecord)
|
||||
// TODO: Добавить метод saveHealthRecord в repository
|
||||
// repository.saveHealthRecord(updatedRecord)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = _uiState.value.copy(error = e.message)
|
||||
}
|
||||
@@ -199,19 +152,18 @@ class HealthViewModel @Inject constructor(
|
||||
} else {
|
||||
HealthRecordEntity(
|
||||
date = LocalDate.now(),
|
||||
weight = 0f,
|
||||
heartRate = 0,
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = "",
|
||||
weight = null,
|
||||
heartRate = null,
|
||||
bloodPressureS = null,
|
||||
bloodPressureD = null,
|
||||
temperature = null,
|
||||
energyLevel = 5,
|
||||
stressLevel = 5,
|
||||
symptoms = symptoms,
|
||||
notes = ""
|
||||
)
|
||||
}
|
||||
repository.saveHealthRecord(updatedRecord)
|
||||
// TODO: Добавить метод saveHealthRecord в repository
|
||||
// repository.saveHealthRecord(updatedRecord)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = _uiState.value.copy(error = e.message)
|
||||
}
|
||||
@@ -228,19 +180,18 @@ class HealthViewModel @Inject constructor(
|
||||
} else {
|
||||
HealthRecordEntity(
|
||||
date = LocalDate.now(),
|
||||
weight = 0f,
|
||||
heartRate = 0,
|
||||
bloodPressureS = 0,
|
||||
bloodPressureD = 0,
|
||||
temperature = 36.6f,
|
||||
mood = "",
|
||||
weight = null,
|
||||
heartRate = null,
|
||||
bloodPressureS = null,
|
||||
bloodPressureD = null,
|
||||
temperature = null,
|
||||
energyLevel = 5,
|
||||
stressLevel = 5,
|
||||
symptoms = emptyList(),
|
||||
notes = notes
|
||||
)
|
||||
}
|
||||
repository.saveHealthRecord(updatedRecord)
|
||||
// TODO: Добавить метод saveHealthRecord в repository
|
||||
// repository.saveHealthRecord(updatedRecord)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = _uiState.value.copy(error = e.message)
|
||||
}
|
||||
@@ -250,7 +201,8 @@ class HealthViewModel @Inject constructor(
|
||||
fun deleteHealthRecord(record: HealthRecordEntity) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.deleteHealthRecord(record.id)
|
||||
// TODO: Добавить метод deleteHealthRecord в repository
|
||||
// repository.deleteHealthRecord(record.id)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = _uiState.value.copy(error = e.message)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package kr.smartsoltech.wellshe.ui.main
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import kr.smartsoltech.wellshe.R
|
||||
|
||||
/**
|
||||
* Главный экран приложения
|
||||
*/
|
||||
class MainFragment : Fragment() {
|
||||
|
||||
override fun onCreateView(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?,
|
||||
savedInstanceState: Bundle?
|
||||
): View? {
|
||||
return inflater.inflate(R.layout.fragment_main, container, false)
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
|
||||
// Инициализация UI и обработчиков событий
|
||||
}
|
||||
}
|
||||
114
app/src/main/java/kr/smartsoltech/wellshe/ui/main/MainScreen.kt
Normal file
114
app/src/main/java/kr/smartsoltech/wellshe/ui/main/MainScreen.kt
Normal file
@@ -0,0 +1,114 @@
|
||||
package kr.smartsoltech.wellshe.ui.main
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ExitToApp
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kr.smartsoltech.wellshe.R
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun MainScreen(
|
||||
onNavigateToEmergency: () -> Unit,
|
||||
onLogout: () -> Unit
|
||||
) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("WellShe") },
|
||||
actions = {
|
||||
IconButton(onClick = { onLogout() }) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.ExitToApp,
|
||||
contentDescription = "Выйти"
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
BottomAppBar {
|
||||
// Навигация внизу экрана, если необходимо
|
||||
}
|
||||
}
|
||||
) { paddingValues ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues)
|
||||
.padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)
|
||||
) {
|
||||
Text(
|
||||
text = "Главный экран приложения WellShe",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
Button(
|
||||
onClick = { onNavigateToEmergency() },
|
||||
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
|
||||
modifier = Modifier.fillMaxWidth(0.8f)
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Warning,
|
||||
contentDescription = null
|
||||
)
|
||||
Text("ЭКСТРЕННАЯ ПОМОЩЬ")
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Добавление основных функциональных кнопок
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.fillMaxWidth(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
text = "Функции приложения",
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
// Кнопки для основных функций
|
||||
Button(
|
||||
onClick = { /* Действие */ },
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text("Мой профиль")
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Button(
|
||||
onClick = { /* Действие */ },
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text("Настройки")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user