Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 247cddd38a | |||
| 47afd9848b | |||
| 18753b214d | |||
| f429d54e1b | |||
| f98a77e5a5 | |||
| 3fea080626 | |||
| 0e792d28e0 | |||
| 5128762d91 |
2
.idea/deploymentTargetSelector.xml
generated
2
.idea/deploymentTargetSelector.xml
generated
@@ -4,7 +4,7 @@
|
|||||||
<selectionStates>
|
<selectionStates>
|
||||||
<SelectionState runConfigName="app">
|
<SelectionState runConfigName="app">
|
||||||
<option name="selectionMode" value="DROPDOWN" />
|
<option name="selectionMode" value="DROPDOWN" />
|
||||||
<DropdownSelection timestamp="2025-10-12T11:23:35.923427438Z">
|
<DropdownSelection timestamp="2025-10-18T10:08:22.623831996Z">
|
||||||
<Target type="DEFAULT_BOOT">
|
<Target type="DEFAULT_BOOT">
|
||||||
<handle>
|
<handle>
|
||||||
<DeviceId pluginId="PhysicalDevice" identifier="serial=R3CT80VPBQZ" />
|
<DeviceId pluginId="PhysicalDevice" identifier="serial=R3CT80VPBQZ" />
|
||||||
|
|||||||
@@ -27,6 +27,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 {
|
buildTypes {
|
||||||
@@ -47,6 +65,8 @@ android {
|
|||||||
}
|
}
|
||||||
buildFeatures {
|
buildFeatures {
|
||||||
compose = true
|
compose = true
|
||||||
|
viewBinding = true
|
||||||
|
buildConfig = true
|
||||||
}
|
}
|
||||||
composeOptions {
|
composeOptions {
|
||||||
kotlinCompilerExtensionVersion = "1.5.14"
|
kotlinCompilerExtensionVersion = "1.5.14"
|
||||||
@@ -64,6 +84,7 @@ dependencies {
|
|||||||
implementation(libs.androidx.compose.material3)
|
implementation(libs.androidx.compose.material3)
|
||||||
implementation("androidx.hilt:hilt-navigation-compose:1.1.0")
|
implementation("androidx.hilt:hilt-navigation-compose:1.1.0")
|
||||||
implementation(libs.hilt.android)
|
implementation(libs.hilt.android)
|
||||||
|
implementation(libs.material)
|
||||||
kapt(libs.hilt.compiler)
|
kapt(libs.hilt.compiler)
|
||||||
implementation("androidx.room:room-runtime:2.6.1")
|
implementation("androidx.room:room-runtime:2.6.1")
|
||||||
kapt("androidx.room:room-compiler:2.6.1")
|
kapt("androidx.room:room-compiler:2.6.1")
|
||||||
@@ -83,8 +104,26 @@ dependencies {
|
|||||||
implementation("com.squareup.moshi:moshi-adapters:1.15.0")
|
implementation("com.squareup.moshi:moshi-adapters:1.15.0")
|
||||||
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.6.2")
|
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(libs.junit)
|
||||||
testImplementation("io.mockk:mockk:1.13.8")
|
|
||||||
androidTestImplementation(libs.androidx.junit)
|
androidTestImplementation(libs.androidx.junit)
|
||||||
androidTestImplementation(libs.androidx.espresso.core)
|
androidTestImplementation(libs.androidx.espresso.core)
|
||||||
androidTestImplementation(platform(libs.androidx.compose.bom))
|
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
@@ -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.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<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
|
<application
|
||||||
android:name=".WellSheApplication"
|
android:name=".WellSheApplication"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
@@ -24,6 +33,7 @@
|
|||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
android:supportsRtl="true"
|
android:supportsRtl="true"
|
||||||
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
android:theme="@style/Theme.WellShe">
|
android:theme="@style/Theme.WellShe">
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
@@ -49,6 +59,17 @@
|
|||||||
android:value="androidx.startup" />
|
android:value="androidx.startup" />
|
||||||
</provider>
|
</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>
|
</application>
|
||||||
|
|
||||||
</manifest>
|
</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
|
package kr.smartsoltech.wellshe
|
||||||
|
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.setContent
|
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 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
|
import kr.smartsoltech.wellshe.ui.theme.WellSheTheme
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
enableEdgeToEdge()
|
|
||||||
|
try {
|
||||||
setContent {
|
setContent {
|
||||||
WellSheTheme {
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,12 +2,31 @@ package kr.smartsoltech.wellshe
|
|||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
|
import kr.smartsoltech.wellshe.emergency.domain.repository.EmergencyRepository
|
||||||
|
import dagger.hilt.EntryPoint
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
|
||||||
@HiltAndroidApp
|
@HiltAndroidApp
|
||||||
class WellSheApplication : Application() {
|
class WellSheApplication : Application() {
|
||||||
|
|
||||||
|
@EntryPoint
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
interface EmergencyRepositoryEntryPoint {
|
||||||
|
fun emergencyRepository(): EmergencyRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
val emergencyRepository: EmergencyRepository by lazy {
|
||||||
|
val hiltEntryPoint = EntryPointAccessors.fromApplication(
|
||||||
|
this,
|
||||||
|
EmergencyRepositoryEntryPoint::class.java
|
||||||
|
)
|
||||||
|
hiltEntryPoint.emergencyRepository()
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
// TODO: Initialize app components when repositories are ready
|
// Hilt will inject dependencies after onCreate
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import androidx.room.TypeConverter
|
|||||||
entities = [
|
entities = [
|
||||||
// Основные сущности
|
// Основные сущности
|
||||||
WaterLogEntity::class,
|
WaterLogEntity::class,
|
||||||
SleepLogEntity::class,
|
|
||||||
WorkoutEntity::class,
|
WorkoutEntity::class,
|
||||||
CalorieEntity::class,
|
CalorieEntity::class,
|
||||||
StepsEntity::class,
|
StepsEntity::class,
|
||||||
@@ -41,15 +40,18 @@ import androidx.room.TypeConverter
|
|||||||
ExerciseParam::class,
|
ExerciseParam::class,
|
||||||
ExerciseFormula::class,
|
ExerciseFormula::class,
|
||||||
ExerciseFormulaVar::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
|
exportSchema = true
|
||||||
)
|
)
|
||||||
@TypeConverters(LocalDateConverter::class, InstantConverter::class, StringListConverter::class)
|
@TypeConverters(LocalDateConverter::class, InstantConverter::class, StringListConverter::class, EmergencyTypeConverter::class)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
abstract fun waterLogDao(): WaterLogDao
|
abstract fun waterLogDao(): WaterLogDao
|
||||||
abstract fun sleepLogDao(): SleepLogDao
|
|
||||||
abstract fun workoutDao(): WorkoutDao
|
abstract fun workoutDao(): WorkoutDao
|
||||||
abstract fun calorieDao(): CalorieDao
|
abstract fun calorieDao(): CalorieDao
|
||||||
abstract fun stepsDao(): StepsDao
|
abstract fun stepsDao(): StepsDao
|
||||||
@@ -63,6 +65,8 @@ abstract class AppDatabase : RoomDatabase() {
|
|||||||
abstract fun cycleForecastDao(): CycleForecastDao
|
abstract fun cycleForecastDao(): CycleForecastDao
|
||||||
|
|
||||||
// Дополнительные DAO для repo
|
// Дополнительные DAO для repo
|
||||||
|
abstract fun beverageDao(): BeverageDao
|
||||||
|
abstract fun beverageServingDao(): BeverageServingDao
|
||||||
abstract fun beverageLogDao(): BeverageLogDao
|
abstract fun beverageLogDao(): BeverageLogDao
|
||||||
abstract fun beverageLogNutrientDao(): BeverageLogNutrientDao
|
abstract fun beverageLogNutrientDao(): BeverageLogNutrientDao
|
||||||
abstract fun beverageServingNutrientDao(): BeverageServingNutrientDao
|
abstract fun beverageServingNutrientDao(): BeverageServingNutrientDao
|
||||||
@@ -71,8 +75,14 @@ abstract class AppDatabase : RoomDatabase() {
|
|||||||
abstract fun workoutSessionParamDao(): WorkoutSessionParamDao
|
abstract fun workoutSessionParamDao(): WorkoutSessionParamDao
|
||||||
abstract fun workoutEventDao(): WorkoutEventDao
|
abstract fun workoutEventDao(): WorkoutEventDao
|
||||||
abstract fun exerciseDao(): ExerciseDao
|
abstract fun exerciseDao(): ExerciseDao
|
||||||
|
abstract fun exerciseParamDao(): ExerciseParamDao
|
||||||
abstract fun exerciseFormulaDao(): ExerciseFormulaDao
|
abstract fun exerciseFormulaDao(): ExerciseFormulaDao
|
||||||
abstract fun exerciseFormulaVarDao(): ExerciseFormulaVarDao
|
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 {
|
class LocalDateConverter {
|
||||||
@@ -81,3 +91,19 @@ class LocalDateConverter {
|
|||||||
@TypeConverter
|
@TypeConverter
|
||||||
fun dateToTimestamp(date: LocalDate?): Long? = date?.atStartOfDay(java.time.ZoneId.systemDefault())?.toInstant()?.toEpochMilli()
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,27 +5,6 @@ import kotlinx.coroutines.flow.Flow
|
|||||||
import kr.smartsoltech.wellshe.data.entity.*
|
import kr.smartsoltech.wellshe.data.entity.*
|
||||||
import java.time.LocalDate
|
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
|
@Dao
|
||||||
interface WorkoutDao {
|
interface WorkoutDao {
|
||||||
@Query("SELECT * FROM workouts WHERE date = :date ORDER BY id DESC")
|
@Query("SELECT * FROM workouts WHERE date = :date ORDER BY id DESC")
|
||||||
|
|||||||
@@ -22,6 +22,5 @@ data class CycleHistoryEntity(
|
|||||||
// Добавляем поля для соответствия с CyclePeriodEntity
|
// Добавляем поля для соответствия с CyclePeriodEntity
|
||||||
val flow: String = "",
|
val flow: String = "",
|
||||||
val symptoms: List<String> = emptyList(),
|
val symptoms: List<String> = emptyList(),
|
||||||
val mood: String = "",
|
|
||||||
val cycleLength: Int? = null
|
val cycleLength: Int? = null
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,6 +11,5 @@ data class CyclePeriodEntity(
|
|||||||
val endDate: LocalDate?,
|
val endDate: LocalDate?,
|
||||||
val flow: String = "",
|
val flow: String = "",
|
||||||
val symptoms: List<String> = emptyList(),
|
val symptoms: List<String> = emptyList(),
|
||||||
val mood: String = "",
|
|
||||||
val cycleLength: Int? = null
|
val cycleLength: Int? = null
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -13,18 +13,6 @@ data class WaterLogEntity(
|
|||||||
val timestamp: Long = System.currentTimeMillis()
|
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")
|
@Entity(tableName = "workouts")
|
||||||
data class WorkoutEntity(
|
data class WorkoutEntity(
|
||||||
@PrimaryKey(autoGenerate = true)
|
@PrimaryKey(autoGenerate = true)
|
||||||
@@ -76,5 +64,10 @@ data class UserProfileEntity(
|
|||||||
val cycleLength: Int = 28,
|
val cycleLength: Int = 28,
|
||||||
val periodLength: Int = 5,
|
val periodLength: Int = 5,
|
||||||
val lastPeriodDate: LocalDate? = null,
|
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 bloodPressureS: Int?,
|
||||||
val bloodPressureD: Int?,
|
val bloodPressureD: Int?,
|
||||||
val temperature: Float?,
|
val temperature: Float?,
|
||||||
val mood: String?,
|
|
||||||
val energyLevel: Int?,
|
val energyLevel: Int?,
|
||||||
val stressLevel: Int?,
|
|
||||||
val symptoms: List<String>?,
|
val symptoms: List<String>?,
|
||||||
val notes: 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,64 @@
|
|||||||
|
package kr.smartsoltech.wellshe.data.network
|
||||||
|
|
||||||
|
import com.google.gson.Gson
|
||||||
|
import com.google.gson.GsonBuilder
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.logging.HttpLoggingInterceptor
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.converter.gson.GsonConverterFactory
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Класс для настройки и создания API-клиентов
|
||||||
|
*/
|
||||||
|
object ApiClient {
|
||||||
|
private const val BASE_URL = "http://192.168.219.108:8000/api/v1/"
|
||||||
|
private const val CONNECT_TIMEOUT = 15L
|
||||||
|
private const val READ_TIMEOUT = 15L
|
||||||
|
private const val WRITE_TIMEOUT = 15L
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Создает экземпляр Retrofit с настройками для работы с API
|
||||||
|
*/
|
||||||
|
private fun createRetrofit(baseUrl: String = BASE_URL): Retrofit {
|
||||||
|
val gson: Gson = GsonBuilder()
|
||||||
|
.setLenient()
|
||||||
|
.create()
|
||||||
|
|
||||||
|
return Retrofit.Builder()
|
||||||
|
.baseUrl(baseUrl)
|
||||||
|
.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(CONNECT_TIMEOUT, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(WRITE_TIMEOUT, 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,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,
|
endDate = historyEntity.periodEnd,
|
||||||
flow = historyEntity.flow,
|
flow = historyEntity.flow,
|
||||||
symptoms = historyEntity.symptoms,
|
symptoms = historyEntity.symptoms,
|
||||||
mood = historyEntity.mood,
|
|
||||||
cycleLength = historyEntity.cycleLength
|
cycleLength = historyEntity.cycleLength
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -277,7 +276,6 @@ class CycleRepository @Inject constructor(
|
|||||||
periodEnd = period.endDate,
|
periodEnd = period.endDate,
|
||||||
flow = period.flow,
|
flow = period.flow,
|
||||||
symptoms = period.symptoms,
|
symptoms = period.symptoms,
|
||||||
mood = period.mood,
|
|
||||||
cycleLength = period.cycleLength,
|
cycleLength = period.cycleLength,
|
||||||
atypical = false // по умолчанию не отмечаем как нетипичный
|
atypical = false // по умолчанию не отмечаем как нетипичный
|
||||||
)
|
)
|
||||||
@@ -292,7 +290,6 @@ class CycleRepository @Inject constructor(
|
|||||||
periodEnd = period.endDate,
|
periodEnd = period.endDate,
|
||||||
flow = period.flow,
|
flow = period.flow,
|
||||||
symptoms = period.symptoms,
|
symptoms = period.symptoms,
|
||||||
mood = period.mood,
|
|
||||||
cycleLength = period.cycleLength,
|
cycleLength = period.cycleLength,
|
||||||
atypical = false // сохраняем существующее значение, если возможно
|
atypical = false // сохраняем существующее значение, если возможно
|
||||||
)
|
)
|
||||||
@@ -306,7 +303,6 @@ class CycleRepository @Inject constructor(
|
|||||||
periodEnd = period.endDate,
|
periodEnd = period.endDate,
|
||||||
flow = period.flow,
|
flow = period.flow,
|
||||||
symptoms = period.symptoms,
|
symptoms = period.symptoms,
|
||||||
mood = period.mood,
|
|
||||||
cycleLength = period.cycleLength,
|
cycleLength = period.cycleLength,
|
||||||
atypical = false
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,7 +12,6 @@ import kr.smartsoltech.wellshe.domain.model.User
|
|||||||
import kr.smartsoltech.wellshe.domain.model.WaterIntake
|
import kr.smartsoltech.wellshe.domain.model.WaterIntake
|
||||||
import kr.smartsoltech.wellshe.domain.model.WorkoutSession
|
import kr.smartsoltech.wellshe.domain.model.WorkoutSession
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.LocalDateTime
|
|
||||||
import java.time.LocalTime
|
import java.time.LocalTime
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -21,7 +20,6 @@ import javax.inject.Singleton
|
|||||||
class WellSheRepository @Inject constructor(
|
class WellSheRepository @Inject constructor(
|
||||||
private val waterLogDao: WaterLogDao,
|
private val waterLogDao: WaterLogDao,
|
||||||
private val cyclePeriodDao: CyclePeriodDao,
|
private val cyclePeriodDao: CyclePeriodDao,
|
||||||
private val sleepLogDao: SleepLogDao,
|
|
||||||
private val healthRecordDao: HealthRecordDao,
|
private val healthRecordDao: HealthRecordDao,
|
||||||
private val workoutDao: WorkoutDao,
|
private val workoutDao: WorkoutDao,
|
||||||
private val calorieDao: CalorieDao,
|
private val calorieDao: CalorieDao,
|
||||||
@@ -45,8 +43,7 @@ class WellSheRepository @Inject constructor(
|
|||||||
weight = 60f,
|
weight = 60f,
|
||||||
dailyWaterGoal = 2.5f,
|
dailyWaterGoal = 2.5f,
|
||||||
dailyStepsGoal = 10000,
|
dailyStepsGoal = 10000,
|
||||||
dailyCaloriesGoal = 2000,
|
dailyCaloriesGoal = 2000
|
||||||
dailySleepGoal = 8.0f
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -157,231 +154,89 @@ class WellSheRepository @Inject constructor(
|
|||||||
// TODO: Реализовать окончание тренировки
|
// 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(
|
val period = CyclePeriodEntity(
|
||||||
startDate = startDate,
|
startDate = startDate,
|
||||||
endDate = endDate,
|
endDate = endDate,
|
||||||
flow = flow,
|
flow = flow,
|
||||||
symptoms = symptoms,
|
symptoms = symptoms
|
||||||
mood = mood
|
|
||||||
)
|
)
|
||||||
cyclePeriodDao.insert(period)
|
// Используем CycleRepository для работы с периодами
|
||||||
|
// cyclePeriodDao.insertPeriod(period)
|
||||||
|
// TODO: Добавить интеграцию с CycleRepository
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun updatePeriod(periodId: Long, endDate: LocalDate?, flow: String, symptoms: List<String>, mood: String) {
|
suspend fun updatePeriod(periodId: Long, endDate: LocalDate?, flow: String, symptoms: List<String>) {
|
||||||
val periods = cyclePeriodDao.getAll()
|
// TODO: Реализовать через CycleRepository
|
||||||
val existingPeriod = periods.firstOrNull { it.id == periodId }
|
// val existingPeriod = cyclePeriodDao.getPeriodById(periodId)
|
||||||
if (existingPeriod != null) {
|
// existingPeriod?.let {
|
||||||
val updatedPeriod = existingPeriod.copy(
|
// val updatedPeriod = it.copy(
|
||||||
endDate = endDate,
|
// endDate = endDate,
|
||||||
flow = flow,
|
// flow = flow,
|
||||||
symptoms = symptoms,
|
// symptoms = symptoms
|
||||||
mood = mood
|
// )
|
||||||
)
|
// cyclePeriodDao.updatePeriod(updatedPeriod)
|
||||||
cyclePeriodDao.update(updatedPeriod)
|
// }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun getRecentPeriods(): List<CyclePeriodEntity> {
|
fun getPeriods(): Flow<List<CyclePeriodEntity>> {
|
||||||
return cyclePeriodDao.getAll().take(6)
|
// 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: Реализовать получение настроек из БД
|
// TODO: Реализовать получение настроек из БД
|
||||||
return flowOf(
|
return flowOf(
|
||||||
AppSettings(
|
AppSettings(
|
||||||
isWaterReminderEnabled = true,
|
notificationsEnabled = true,
|
||||||
isCycleReminderEnabled = true,
|
darkModeEnabled = false
|
||||||
isSleepReminderEnabled = true,
|
|
||||||
cycleLength = 28,
|
|
||||||
periodLength = 5,
|
|
||||||
waterGoal = 2.5f,
|
|
||||||
stepsGoal = 10000,
|
|
||||||
sleepGoal = 8.0f,
|
|
||||||
isDarkTheme = false
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun updateWaterReminderSetting(enabled: Boolean) {
|
suspend fun updateAppSettings(settings: AppSettings) {
|
||||||
// TODO: Реализовать обновление настройки напоминаний о воде
|
// 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 exportUserData() {
|
fun getDashboardData(date: LocalDate): Flow<DashboardData> {
|
||||||
// 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>> {
|
|
||||||
return flow {
|
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(
|
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 date: LocalDate,
|
||||||
val bloodPressureSystolic: Int = 0,
|
val waterIntake: Float,
|
||||||
val bloodPressureDiastolic: Int = 0,
|
val steps: Int,
|
||||||
val heartRate: Int = 0,
|
val calories: Int,
|
||||||
val weight: Float = 0f,
|
val workouts: Int,
|
||||||
val mood: String = "neutral", // Добавляем поле настроения
|
val cycleDay: Int?
|
||||||
val energyLevel: Int = 5, // Добавляем уровень энергии (1-10)
|
|
||||||
val stressLevel: Int = 5, // Добавляем уровень стресса (1-10)
|
|
||||||
val notes: String = ""
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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.android.qualifiers.ApplicationContext
|
||||||
import dagger.hilt.components.SingletonComponent
|
import dagger.hilt.components.SingletonComponent
|
||||||
import kr.smartsoltech.wellshe.data.AppDatabase
|
import kr.smartsoltech.wellshe.data.AppDatabase
|
||||||
import kr.smartsoltech.wellshe.data.datastore.DataStoreManager
|
|
||||||
import kr.smartsoltech.wellshe.data.dao.*
|
import kr.smartsoltech.wellshe.data.dao.*
|
||||||
import kr.smartsoltech.wellshe.data.repo.DrinkLogger
|
import kr.smartsoltech.wellshe.data.repo.*
|
||||||
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 javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@Module
|
@Module
|
||||||
@@ -31,34 +18,19 @@ object AppModule {
|
|||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideDataStoreManager(@ApplicationContext context: Context): DataStoreManager =
|
fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase {
|
||||||
DataStoreManager(context)
|
return Room.databaseBuilder(
|
||||||
|
|
||||||
@Provides
|
|
||||||
@Singleton
|
|
||||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
|
||||||
Room.databaseBuilder(
|
|
||||||
context,
|
context,
|
||||||
AppDatabase::class.java,
|
AppDatabase::class.java,
|
||||||
"well_she_db"
|
"wellshe_database"
|
||||||
)
|
).fallbackToDestructiveMigration()
|
||||||
.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()
|
|
||||||
.build()
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
// DAO providers
|
// DAO Providers
|
||||||
@Provides
|
@Provides
|
||||||
fun provideWaterLogDao(database: AppDatabase): WaterLogDao = database.waterLogDao()
|
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
|
@Provides
|
||||||
fun provideWorkoutDao(database: AppDatabase): WorkoutDao = database.workoutDao()
|
fun provideWorkoutDao(database: AppDatabase): WorkoutDao = database.workoutDao()
|
||||||
|
|
||||||
@@ -71,7 +43,12 @@ object AppModule {
|
|||||||
@Provides
|
@Provides
|
||||||
fun provideUserProfileDao(database: AppDatabase): UserProfileDao = database.userProfileDao()
|
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
|
@Provides
|
||||||
fun provideBeverageLogDao(database: AppDatabase): BeverageLogDao = database.beverageLogDao()
|
fun provideBeverageLogDao(database: AppDatabase): BeverageLogDao = database.beverageLogDao()
|
||||||
|
|
||||||
@@ -102,7 +79,28 @@ object AppModule {
|
|||||||
@Provides
|
@Provides
|
||||||
fun provideExerciseFormulaVarDao(database: AppDatabase): ExerciseFormulaVarDao = database.exerciseFormulaVarDao()
|
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
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideDrinkLogger(
|
fun provideDrinkLogger(
|
||||||
@@ -110,12 +108,9 @@ object AppModule {
|
|||||||
beverageLogDao: BeverageLogDao,
|
beverageLogDao: BeverageLogDao,
|
||||||
beverageLogNutrientDao: BeverageLogNutrientDao,
|
beverageLogNutrientDao: BeverageLogNutrientDao,
|
||||||
servingNutrientDao: BeverageServingNutrientDao
|
servingNutrientDao: BeverageServingNutrientDao
|
||||||
): DrinkLogger = DrinkLogger(waterLogDao, beverageLogDao, beverageLogNutrientDao, servingNutrientDao)
|
): DrinkLogger {
|
||||||
|
return DrinkLogger(waterLogDao, beverageLogDao, beverageLogNutrientDao, servingNutrientDao)
|
||||||
@Provides
|
}
|
||||||
@Singleton
|
|
||||||
fun provideWeightRepository(weightLogDao: WeightLogDao): WeightRepository =
|
|
||||||
WeightRepository(weightLogDao)
|
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
@@ -127,23 +122,27 @@ object AppModule {
|
|||||||
formulaDao: ExerciseFormulaDao,
|
formulaDao: ExerciseFormulaDao,
|
||||||
formulaVarDao: ExerciseFormulaVarDao,
|
formulaVarDao: ExerciseFormulaVarDao,
|
||||||
exerciseDao: ExerciseDao
|
exerciseDao: ExerciseDao
|
||||||
): WorkoutService = WorkoutService(sessionDao, paramDao, eventDao, weightRepo, formulaDao, formulaVarDao, exerciseDao)
|
): WorkoutService {
|
||||||
|
return WorkoutService(sessionDao, paramDao, eventDao, weightRepo, formulaDao, formulaVarDao, exerciseDao)
|
||||||
|
}
|
||||||
|
|
||||||
// Repository
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun provideWellSheRepository(
|
fun provideBeverageCatalogRepository(
|
||||||
waterLogDao: WaterLogDao,
|
beverageDao: BeverageDao,
|
||||||
cyclePeriodDao: CyclePeriodDao,
|
servingDao: BeverageServingDao,
|
||||||
sleepLogDao: SleepLogDao,
|
servingNutrientDao: BeverageServingNutrientDao
|
||||||
healthRecordDao: HealthRecordDao,
|
): BeverageCatalogRepository {
|
||||||
workoutDao: WorkoutDao,
|
return BeverageCatalogRepository(beverageDao, servingDao, servingNutrientDao)
|
||||||
calorieDao: CalorieDao,
|
}
|
||||||
stepsDao: StepsDao,
|
|
||||||
userProfileDao: UserProfileDao
|
@Provides
|
||||||
): kr.smartsoltech.wellshe.data.repository.WellSheRepository =
|
@Singleton
|
||||||
kr.smartsoltech.wellshe.data.repository.WellSheRepository(
|
fun provideExerciseCatalogRepository(
|
||||||
waterLogDao, cyclePeriodDao, sleepLogDao, healthRecordDao,
|
exerciseDao: ExerciseDao,
|
||||||
workoutDao, calorieDao, stepsDao, userProfileDao
|
paramDao: ExerciseParamDao,
|
||||||
)
|
formulaDao: ExerciseFormulaDao
|
||||||
|
): ExerciseCatalogRepository {
|
||||||
|
return ExerciseCatalogRepository(exerciseDao, paramDao, formulaDao)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
77
app/src/main/java/kr/smartsoltech/wellshe/di/AuthModule.kt
Normal file
77
app/src/main/java/kr/smartsoltech/wellshe/di/AuthModule.kt
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
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.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 retrofit2.Retrofit
|
||||||
|
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 provideAuthService(retrofit: Retrofit): AuthService {
|
||||||
|
return retrofit.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,58 @@
|
|||||||
|
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.BuildConfig
|
||||||
|
import kr.smartsoltech.wellshe.data.local.AuthTokenRepository
|
||||||
|
import kr.smartsoltech.wellshe.data.network.AuthInterceptor
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.logging.HttpLoggingInterceptor
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.converter.gson.GsonConverterFactory
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object NetworkModule {
|
||||||
|
private const val CONNECT_TIMEOUT = 15L
|
||||||
|
private const val READ_TIMEOUT = 15L
|
||||||
|
private const val WRITE_TIMEOUT = 15L
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideGson(): Gson {
|
||||||
|
return GsonBuilder()
|
||||||
|
.setLenient()
|
||||||
|
.create()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideAuthInterceptor(authTokenRepository: AuthTokenRepository): AuthInterceptor {
|
||||||
|
return AuthInterceptor(authTokenRepository)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideRetrofit(gson: Gson, authInterceptor: AuthInterceptor): Retrofit {
|
||||||
|
val client = OkHttpClient.Builder()
|
||||||
|
.addInterceptor(authInterceptor)
|
||||||
|
.addInterceptor(HttpLoggingInterceptor().apply {
|
||||||
|
level = HttpLoggingInterceptor.Level.BODY
|
||||||
|
})
|
||||||
|
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
return Retrofit.Builder()
|
||||||
|
.baseUrl(BuildConfig.API_BASE_URL)
|
||||||
|
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||||
|
.client(client)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
package kr.smartsoltech.wellshe.domain.model
|
||||||
|
|
||||||
data class AppSettings(
|
data class AppSettings(
|
||||||
val id: Long = 0,
|
val notificationsEnabled: Boolean = true,
|
||||||
val isWaterReminderEnabled: Boolean = true,
|
val darkModeEnabled: Boolean = false
|
||||||
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
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ data class User(
|
|||||||
val dailyWaterGoal: Float = 2.5f, // в литрах
|
val dailyWaterGoal: Float = 2.5f, // в литрах
|
||||||
val dailyStepsGoal: Int = 10000,
|
val dailyStepsGoal: Int = 10000,
|
||||||
val dailyCaloriesGoal: Int = 2000,
|
val dailyCaloriesGoal: Int = 2000,
|
||||||
val dailySleepGoal: Float = 8.0f, // в часах
|
|
||||||
val cycleLength: Int = 28, // дней
|
val cycleLength: Int = 28, // дней
|
||||||
val periodLength: Int = 5, // дней
|
val periodLength: Int = 5, // дней
|
||||||
val lastPeriodStart: LocalDate? = null,
|
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,
|
context.applicationContext,
|
||||||
JournalDatabase::class.java,
|
JournalDatabase::class.java,
|
||||||
"journal_database"
|
"journal_database"
|
||||||
).build()
|
).fallbackToDestructiveMigration()
|
||||||
|
.build()
|
||||||
INSTANCE = instance
|
INSTANCE = 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,159 @@
|
|||||||
|
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.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 kr.smartsoltech.wellshe.ui.auth.AuthViewModel
|
||||||
|
|
||||||
|
@OptIn(ExperimentalComposeUiApi::class)
|
||||||
|
@Composable
|
||||||
|
fun LoginScreen(
|
||||||
|
onNavigateToRegister: () -> Unit,
|
||||||
|
onLoginSuccess: () -> Unit,
|
||||||
|
viewModel: AuthViewModel = hiltViewModel()
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val authState by viewModel.authState.observeAsState()
|
||||||
|
val isLoading by viewModel.isLoading.observeAsState()
|
||||||
|
val keyboardController = LocalSoftwareKeyboardController.current
|
||||||
|
|
||||||
|
var username by remember { mutableStateOf("") }
|
||||||
|
var password by remember { mutableStateOf("") }
|
||||||
|
var passwordVisible by remember { mutableStateOf(false) }
|
||||||
|
var isFormValid 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 { 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("Создать новый аккаунт")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (authState is AuthViewModel.AuthState.AuthError) {
|
||||||
|
Text(
|
||||||
|
text = (authState as AuthViewModel.AuthState.AuthError).message,
|
||||||
|
color = MaterialTheme.colorScheme.error
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,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(
|
fun CycleScreen(
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
viewModel: CycleViewModel = hiltViewModel(),
|
viewModel: CycleViewModel = hiltViewModel(),
|
||||||
onNavigateToSettings: () -> Unit = {} // Добавляем параметр для навигации к настройкам
|
onNavigateToSettings: () -> Unit = {}, // Параметр для навигации к настройкам
|
||||||
|
onNavigateToEmergency: () -> Unit = {} // Добавляем параметр для навигации к экрану экстренной помощи
|
||||||
) {
|
) {
|
||||||
val uiState by viewModel.uiState.collectAsState()
|
val uiState by viewModel.uiState.collectAsState()
|
||||||
val scrollState = rememberScrollState()
|
val scrollState = rememberScrollState()
|
||||||
|
|||||||
@@ -83,13 +83,6 @@ fun DashboardScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
item {
|
|
||||||
SleepCard(
|
|
||||||
sleepData = uiState.sleepData,
|
|
||||||
onClick = { onNavigate("sleep") }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
item {
|
item {
|
||||||
RecentWorkoutsCard(
|
RecentWorkoutsCard(
|
||||||
workouts = uiState.recentWorkouts,
|
workouts = uiState.recentWorkouts,
|
||||||
@@ -404,26 +397,26 @@ private fun HealthOverviewCard(
|
|||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly
|
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(
|
HealthMetric(
|
||||||
label = "Энергия",
|
label = "Энергия",
|
||||||
value = "${healthData.energyLevel}",
|
value = "${healthData.energyLevel}",
|
||||||
unit = "/10",
|
unit = "/10",
|
||||||
icon = Icons.Default.Battery6Bar
|
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
|
@Composable
|
||||||
private fun RecentWorkoutsCard(
|
private fun RecentWorkoutsCard(
|
||||||
workouts: List<WorkoutData>,
|
workouts: List<WorkoutData>,
|
||||||
@@ -605,7 +541,7 @@ private fun WorkoutItem(
|
|||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = getWorkoutIcon(workout.type),
|
imageVector = Icons.Default.FitnessCenter,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = PrimaryPink,
|
tint = PrimaryPink,
|
||||||
modifier = Modifier.size(20.dp)
|
modifier = Modifier.size(20.dp)
|
||||||
@@ -617,7 +553,7 @@ private fun WorkoutItem(
|
|||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f)
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = getWorkoutTypeText(workout.type),
|
text = workout.name,
|
||||||
style = MaterialTheme.typography.bodyMedium.copy(
|
style = MaterialTheme.typography.bodyMedium.copy(
|
||||||
fontWeight = FontWeight.Medium,
|
fontWeight = FontWeight.Medium,
|
||||||
color = TextPrimary
|
color = TextPrimary
|
||||||
@@ -662,12 +598,12 @@ private val quickActions = listOf(
|
|||||||
textColor = SecondaryBlue
|
textColor = SecondaryBlue
|
||||||
),
|
),
|
||||||
QuickAction(
|
QuickAction(
|
||||||
title = "Отметить сон",
|
title = "Экстренная помощь",
|
||||||
icon = Icons.Default.Bedtime,
|
icon = Icons.Default.Emergency,
|
||||||
route = "sleep",
|
route = "emergency",
|
||||||
backgroundColor = AccentPurpleLight,
|
backgroundColor = ErrorRedLight,
|
||||||
iconColor = AccentPurple,
|
iconColor = ErrorRed,
|
||||||
textColor = AccentPurple
|
textColor = ErrorRed
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -8,19 +8,14 @@ import kotlinx.coroutines.flow.StateFlow
|
|||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.catch
|
import kotlinx.coroutines.flow.catch
|
||||||
import kotlinx.coroutines.launch
|
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.data.repository.WellSheRepository
|
||||||
import kr.smartsoltech.wellshe.domain.model.*
|
import kr.smartsoltech.wellshe.domain.model.*
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.temporal.ChronoUnit
|
|
||||||
|
|
||||||
data class DashboardUiState(
|
data class DashboardUiState(
|
||||||
val user: User = User(),
|
val user: User = User(),
|
||||||
val todayHealth: HealthData = HealthData(),
|
val todayHealth: HealthData = HealthData(),
|
||||||
val sleepData: SleepData = SleepData(),
|
|
||||||
val cycleData: CycleData = CycleData(),
|
val cycleData: CycleData = CycleData(),
|
||||||
val recentWorkouts: List<WorkoutData> = emptyList(),
|
val recentWorkouts: List<WorkoutData> = emptyList(),
|
||||||
val todaySteps: Int = 0,
|
val todaySteps: Int = 0,
|
||||||
@@ -53,37 +48,13 @@ class DashboardViewModel @Inject constructor(
|
|||||||
_uiState.value = _uiState.value.copy(user = user)
|
_uiState.value = _uiState.value.copy(user = user)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Загружаем данные о здоровье
|
// TODO: Временно используем заглушки для данных о здоровье
|
||||||
repository.getTodayHealthData().catch {
|
val healthData = HealthData()
|
||||||
// Игнорируем ошибки, используем дефолтные данные
|
|
||||||
}.collect { healthEntity: HealthRecordEntity? ->
|
|
||||||
val healthData = healthEntity?.let { convertHealthEntityToModel(it) } ?: HealthData()
|
|
||||||
_uiState.value = _uiState.value.copy(todayHealth = healthData)
|
_uiState.value = _uiState.value.copy(todayHealth = healthData)
|
||||||
}
|
|
||||||
|
|
||||||
// Загружаем данные о сне
|
// TODO: Временно используем заглушки для данных о цикле
|
||||||
loadSleepData()
|
val cycleData = CycleData()
|
||||||
|
|
||||||
// Загружаем данные о цикле
|
|
||||||
repository.getRecentPeriods().let { periods ->
|
|
||||||
val cycleEntity = periods.firstOrNull()
|
|
||||||
val cycleData = cycleEntity?.let { convertCycleEntityToModel(it) } ?: CycleData()
|
|
||||||
_uiState.value = _uiState.value.copy(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)
|
_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() {
|
fun clearError() {
|
||||||
_uiState.value = _uiState.value.copy(error = null)
|
_uiState.value = _uiState.value.copy(error = null)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Функции преобразования Entity -> Model
|
// Упрощенные модели данных для Dashboard
|
||||||
private fun convertHealthEntityToModel(entity: HealthRecordEntity): HealthData {
|
data class HealthData(
|
||||||
return HealthData(
|
val energyLevel: Int = 5,
|
||||||
id = entity.id.toString(),
|
val symptoms: List<String> = emptyList(),
|
||||||
userId = "current_user",
|
val notes: String = ""
|
||||||
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 {
|
data class CycleData(
|
||||||
return SleepData(
|
val currentDay: Int = 1,
|
||||||
id = entity.id.toString(),
|
val nextPeriodDate: LocalDate? = null,
|
||||||
userId = "current_user",
|
val cycleLength: Int = 28
|
||||||
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 {
|
data class WorkoutData(
|
||||||
return CycleData(
|
val id: Long = 0,
|
||||||
id = entity.id.toString(),
|
val name: String = "",
|
||||||
userId = "current_user",
|
val duration: Int = 0,
|
||||||
cycleLength = entity.cycleLength ?: 28,
|
val caloriesBurned: Int = 0,
|
||||||
periodLength = entity.endDate?.let {
|
val date: LocalDate = LocalDate.now()
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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(
|
TodayHealthCard(
|
||||||
uiState = uiState,
|
uiState = uiState,
|
||||||
onUpdateVitals = viewModel::updateVitals,
|
onUpdateVitals = viewModel::updateVitals,
|
||||||
onUpdateMood = viewModel::updateMood,
|
onUpdateEnergy = viewModel::updateEnergyLevel
|
||||||
onUpdateEnergy = viewModel::updateEnergyLevel,
|
|
||||||
onUpdateStress = viewModel::updateStressLevel
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,9 +131,7 @@ fun HealthOverviewScreen(
|
|||||||
private fun TodayHealthCard(
|
private fun TodayHealthCard(
|
||||||
uiState: HealthUiState,
|
uiState: HealthUiState,
|
||||||
onUpdateVitals: (Float?, Int?, Int?, Int?, Float?) -> Unit,
|
onUpdateVitals: (Float?, Int?, Int?, Int?, Float?) -> Unit,
|
||||||
onUpdateMood: (String) -> Unit,
|
|
||||||
onUpdateEnergy: (Int) -> Unit,
|
onUpdateEnergy: (Int) -> Unit,
|
||||||
onUpdateStress: (Int) -> Unit,
|
|
||||||
modifier: Modifier = Modifier
|
modifier: Modifier = Modifier
|
||||||
) {
|
) {
|
||||||
var weight by remember { mutableStateOf(uiState.todayRecord?.weight?.toString() ?: "") }
|
var weight by remember { mutableStateOf(uiState.todayRecord?.weight?.toString() ?: "") }
|
||||||
@@ -269,16 +265,7 @@ private fun TodayHealthCard(
|
|||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
// Настроение
|
// Уровень энергии
|
||||||
MoodSection(
|
|
||||||
currentMood = uiState.todayRecord?.mood ?: "neutral",
|
|
||||||
onMoodChange = onUpdateMood,
|
|
||||||
isEditMode = uiState.isEditMode
|
|
||||||
)
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
|
||||||
|
|
||||||
// Уровень энергии и стресса
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.spacedBy(16.dp)
|
horizontalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
@@ -288,18 +275,9 @@ private fun TodayHealthCard(
|
|||||||
value = uiState.todayRecord?.energyLevel ?: 5,
|
value = uiState.todayRecord?.energyLevel ?: 5,
|
||||||
onValueChange = onUpdateEnergy,
|
onValueChange = onUpdateEnergy,
|
||||||
isEditMode = uiState.isEditMode,
|
isEditMode = uiState.isEditMode,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
color = WarningOrange
|
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
|
@Composable
|
||||||
private fun LevelSlider(
|
private fun LevelSlider(
|
||||||
label: String,
|
label: String,
|
||||||
@@ -679,18 +595,8 @@ private fun NotesCard(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Данные для UI
|
// Данные для 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(
|
private val healthSymptoms = listOf(
|
||||||
"Головная боль", "Усталость", "Тошнота", "Головокружение",
|
"Головная боль", "Усталость", "Тошнота", "Головокружение",
|
||||||
"Боль в спине", "Боль в суставах", "Бессонница", "Стресс",
|
"Боль в спине", "Боль в суставах", "Бессонница",
|
||||||
"Простуда", "Аллергия", "Боль в животе", "Другое"
|
"Простуда", "Аллергия", "Боль в животе", "Другое"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -248,9 +248,7 @@ private fun VitalSignsCard(
|
|||||||
bloodPressureS = 0,
|
bloodPressureS = 0,
|
||||||
bloodPressureD = 0,
|
bloodPressureD = 0,
|
||||||
temperature = 36.6f,
|
temperature = 36.6f,
|
||||||
mood = "",
|
|
||||||
energyLevel = 5,
|
energyLevel = 5,
|
||||||
stressLevel = 5,
|
|
||||||
symptoms = emptyList(),
|
symptoms = emptyList(),
|
||||||
notes = ""
|
notes = ""
|
||||||
)
|
)
|
||||||
@@ -275,9 +273,7 @@ private fun VitalSignsCard(
|
|||||||
bloodPressureS = 0,
|
bloodPressureS = 0,
|
||||||
bloodPressureD = 0,
|
bloodPressureD = 0,
|
||||||
temperature = 36.6f,
|
temperature = 36.6f,
|
||||||
mood = "",
|
|
||||||
energyLevel = 5,
|
energyLevel = 5,
|
||||||
stressLevel = 5,
|
|
||||||
symptoms = emptyList(),
|
symptoms = emptyList(),
|
||||||
notes = ""
|
notes = ""
|
||||||
)
|
)
|
||||||
@@ -305,9 +301,7 @@ private fun VitalSignsCard(
|
|||||||
bloodPressureS = 0,
|
bloodPressureS = 0,
|
||||||
bloodPressureD = 0,
|
bloodPressureD = 0,
|
||||||
temperature = 36.6f,
|
temperature = 36.6f,
|
||||||
mood = "",
|
|
||||||
energyLevel = 5,
|
energyLevel = 5,
|
||||||
stressLevel = 5,
|
|
||||||
symptoms = emptyList(),
|
symptoms = emptyList(),
|
||||||
notes = ""
|
notes = ""
|
||||||
)
|
)
|
||||||
@@ -333,9 +327,7 @@ private fun VitalSignsCard(
|
|||||||
bloodPressureS = 0,
|
bloodPressureS = 0,
|
||||||
bloodPressureD = 0,
|
bloodPressureD = 0,
|
||||||
temperature = 36.6f,
|
temperature = 36.6f,
|
||||||
mood = "",
|
|
||||||
energyLevel = 5,
|
energyLevel = 5,
|
||||||
stressLevel = 5,
|
|
||||||
symptoms = emptyList(),
|
symptoms = emptyList(),
|
||||||
notes = ""
|
notes = ""
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -37,30 +37,41 @@ class HealthViewModel @Inject constructor(
|
|||||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Загружаем данные о здоровье за сегодня
|
// TODO: Временно используем заглушки, пока не добавим методы в repository
|
||||||
repository.getTodayHealthData().collect { todayRecord: HealthRecordEntity? ->
|
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
todayRecord = todayRecord,
|
todayRecord = null,
|
||||||
lastUpdateDate = todayRecord?.date,
|
lastUpdateDate = null,
|
||||||
todaySymptoms = todayRecord?.symptoms ?: emptyList(),
|
todaySymptoms = emptyList(),
|
||||||
todayNotes = todayRecord?.notes ?: "",
|
todayNotes = "",
|
||||||
|
recentRecords = emptyList(),
|
||||||
|
weeklyWeights = emptyMap(),
|
||||||
isLoading = false
|
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> ->
|
// repository.getAllHealthRecords().collect { records: List<HealthRecordEntity> ->
|
||||||
val weightsMap = records
|
// val weightsMap = records
|
||||||
.filter { it.weight != null && it.weight > 0f }
|
// .filter { it.weight != null && it.weight > 0f }
|
||||||
.groupBy { it.date }
|
// .groupBy { it.date }
|
||||||
.mapValues { entry -> entry.value.last().weight ?: 0f }
|
// .mapValues { entry -> entry.value.last().weight ?: 0f }
|
||||||
_uiState.value = _uiState.value.copy(weeklyWeights = weightsMap)
|
// _uiState.value = _uiState.value.copy(weeklyWeights = weightsMap)
|
||||||
}
|
// }
|
||||||
|
|
||||||
// Загружаем последние записи
|
// Загружаем последние записи
|
||||||
repository.getRecentHealthRecords().collect { records: List<HealthRecordEntity> ->
|
// repository.getRecentHealthRecords().collect { records: List<HealthRecordEntity> ->
|
||||||
_uiState.value = _uiState.value.copy(recentRecords = records)
|
// _uiState.value = _uiState.value.copy(recentRecords = records)
|
||||||
}
|
// }
|
||||||
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
@@ -91,42 +102,13 @@ class HealthViewModel @Inject constructor(
|
|||||||
bloodPressureS = bpSystolic,
|
bloodPressureS = bpSystolic,
|
||||||
bloodPressureD = bpDiastolic,
|
bloodPressureD = bpDiastolic,
|
||||||
temperature = temperature,
|
temperature = temperature,
|
||||||
mood = "",
|
|
||||||
energyLevel = 5,
|
energyLevel = 5,
|
||||||
stressLevel = 5,
|
|
||||||
symptoms = emptyList(),
|
symptoms = emptyList(),
|
||||||
notes = ""
|
notes = ""
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
repository.saveHealthRecord(updatedRecord)
|
// TODO: Добавить метод saveHealthRecord в repository
|
||||||
} catch (e: Exception) {
|
// repository.saveHealthRecord(updatedRecord)
|
||||||
_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)
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
}
|
}
|
||||||
@@ -142,47 +124,18 @@ class HealthViewModel @Inject constructor(
|
|||||||
} else {
|
} else {
|
||||||
HealthRecordEntity(
|
HealthRecordEntity(
|
||||||
date = LocalDate.now(),
|
date = LocalDate.now(),
|
||||||
weight = 0f,
|
weight = null,
|
||||||
heartRate = 0,
|
heartRate = null,
|
||||||
bloodPressureS = 0,
|
bloodPressureS = null,
|
||||||
bloodPressureD = 0,
|
bloodPressureD = null,
|
||||||
temperature = 36.6f,
|
temperature = null,
|
||||||
mood = "",
|
|
||||||
energyLevel = energy,
|
energyLevel = energy,
|
||||||
stressLevel = 5,
|
|
||||||
symptoms = emptyList(),
|
symptoms = emptyList(),
|
||||||
notes = ""
|
notes = ""
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
repository.saveHealthRecord(updatedRecord)
|
// TODO: Добавить метод saveHealthRecord в repository
|
||||||
} catch (e: Exception) {
|
// repository.saveHealthRecord(updatedRecord)
|
||||||
_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)
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
}
|
}
|
||||||
@@ -199,19 +152,18 @@ class HealthViewModel @Inject constructor(
|
|||||||
} else {
|
} else {
|
||||||
HealthRecordEntity(
|
HealthRecordEntity(
|
||||||
date = LocalDate.now(),
|
date = LocalDate.now(),
|
||||||
weight = 0f,
|
weight = null,
|
||||||
heartRate = 0,
|
heartRate = null,
|
||||||
bloodPressureS = 0,
|
bloodPressureS = null,
|
||||||
bloodPressureD = 0,
|
bloodPressureD = null,
|
||||||
temperature = 36.6f,
|
temperature = null,
|
||||||
mood = "",
|
|
||||||
energyLevel = 5,
|
energyLevel = 5,
|
||||||
stressLevel = 5,
|
|
||||||
symptoms = symptoms,
|
symptoms = symptoms,
|
||||||
notes = ""
|
notes = ""
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
repository.saveHealthRecord(updatedRecord)
|
// TODO: Добавить метод saveHealthRecord в repository
|
||||||
|
// repository.saveHealthRecord(updatedRecord)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
}
|
}
|
||||||
@@ -228,19 +180,18 @@ class HealthViewModel @Inject constructor(
|
|||||||
} else {
|
} else {
|
||||||
HealthRecordEntity(
|
HealthRecordEntity(
|
||||||
date = LocalDate.now(),
|
date = LocalDate.now(),
|
||||||
weight = 0f,
|
weight = null,
|
||||||
heartRate = 0,
|
heartRate = null,
|
||||||
bloodPressureS = 0,
|
bloodPressureS = null,
|
||||||
bloodPressureD = 0,
|
bloodPressureD = null,
|
||||||
temperature = 36.6f,
|
temperature = null,
|
||||||
mood = "",
|
|
||||||
energyLevel = 5,
|
energyLevel = 5,
|
||||||
stressLevel = 5,
|
|
||||||
symptoms = emptyList(),
|
symptoms = emptyList(),
|
||||||
notes = notes
|
notes = notes
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
repository.saveHealthRecord(updatedRecord)
|
// TODO: Добавить метод saveHealthRecord в repository
|
||||||
|
// repository.saveHealthRecord(updatedRecord)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
}
|
}
|
||||||
@@ -250,7 +201,8 @@ class HealthViewModel @Inject constructor(
|
|||||||
fun deleteHealthRecord(record: HealthRecordEntity) {
|
fun deleteHealthRecord(record: HealthRecordEntity) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.deleteHealthRecord(record.id)
|
// TODO: Добавить метод deleteHealthRecord в repository
|
||||||
|
// repository.deleteHealthRecord(record.id)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_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("Настройки")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,258 +0,0 @@
|
|||||||
package kr.smartsoltech.wellshe.ui.mood
|
|
||||||
|
|
||||||
import androidx.compose.foundation.layout.*
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.material.icons.Icons
|
|
||||||
import androidx.compose.material.icons.filled.Favorite
|
|
||||||
import androidx.compose.material.icons.filled.ModeNight
|
|
||||||
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.tooling.preview.Preview
|
|
||||||
import androidx.compose.ui.unit.dp
|
|
||||||
import kr.smartsoltech.wellshe.ui.components.InfoCard
|
|
||||||
import kr.smartsoltech.wellshe.ui.components.StatCard
|
|
||||||
import kr.smartsoltech.wellshe.ui.theme.MoodTabColor
|
|
||||||
import kr.smartsoltech.wellshe.ui.theme.WellSheTheme
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Экран "Настроение" для отслеживания сна и эмоционального состояния
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
fun MoodScreen(
|
|
||||||
modifier: Modifier = Modifier
|
|
||||||
) {
|
|
||||||
val scrollState = rememberScrollState()
|
|
||||||
|
|
||||||
Column(
|
|
||||||
modifier = modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.padding(16.dp)
|
|
||||||
.verticalScroll(scrollState),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
|
||||||
) {
|
|
||||||
// Статистические карточки
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(16.dp)
|
|
||||||
) {
|
|
||||||
StatCard(
|
|
||||||
title = "Сон",
|
|
||||||
value = "7.2 ч",
|
|
||||||
tone = Color(0xFF673AB7), // Фиолетовый для сна
|
|
||||||
modifier = Modifier.weight(1f)
|
|
||||||
)
|
|
||||||
|
|
||||||
StatCard(
|
|
||||||
title = "Стресс",
|
|
||||||
value = "3/10",
|
|
||||||
tone = Color(0xFFE91E63), // Розовый для стресса
|
|
||||||
modifier = Modifier.weight(1f)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Карточка дневника
|
|
||||||
Card(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
shape = MaterialTheme.shapes.extraLarge,
|
|
||||||
colors = CardDefaults.cardColors(
|
|
||||||
containerColor = MoodTabColor.copy(alpha = 0.3f)
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
modifier = Modifier.padding(16.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
|
||||||
) {
|
|
||||||
// Заголовок
|
|
||||||
Text(
|
|
||||||
text = "Дневник",
|
|
||||||
style = MaterialTheme.typography.titleLarge,
|
|
||||||
fontWeight = FontWeight.SemiBold
|
|
||||||
)
|
|
||||||
|
|
||||||
// Содержимое дневника
|
|
||||||
Text(
|
|
||||||
text = "Сегодня было продуктивно, немного тревоги перед встречей. Выполнила все запланированные задачи, чувствую удовлетворение от проделанной работы.",
|
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
|
||||||
)
|
|
||||||
|
|
||||||
// Кнопки действий
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.End
|
|
||||||
) {
|
|
||||||
TextButton(onClick = { /* TODO */ }) {
|
|
||||||
Text("Редактировать")
|
|
||||||
}
|
|
||||||
|
|
||||||
TextButton(onClick = { /* TODO */ }) {
|
|
||||||
Text("Добавить запись")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Карточка сна
|
|
||||||
Card(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
shape = MaterialTheme.shapes.extraLarge,
|
|
||||||
colors = CardDefaults.cardColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
modifier = Modifier.padding(16.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
|
||||||
) {
|
|
||||||
// Заголовок с иконкой
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
imageVector = Icons.Default.ModeNight,
|
|
||||||
contentDescription = null,
|
|
||||||
tint = Color(0xFF673AB7)
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = "Качество сна",
|
|
||||||
style = MaterialTheme.typography.titleMedium,
|
|
||||||
fontWeight = FontWeight.SemiBold
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Оценка сна
|
|
||||||
Column(
|
|
||||||
modifier = Modifier.padding(vertical = 8.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(4.dp)
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween
|
|
||||||
) {
|
|
||||||
Text("Продолжительность")
|
|
||||||
Text("7.2 часа", fontWeight = FontWeight.SemiBold)
|
|
||||||
}
|
|
||||||
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween
|
|
||||||
) {
|
|
||||||
Text("Качество")
|
|
||||||
Text("Хорошее", fontWeight = FontWeight.SemiBold)
|
|
||||||
}
|
|
||||||
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween
|
|
||||||
) {
|
|
||||||
Text("Пробуждения")
|
|
||||||
Text("1 раз", fontWeight = FontWeight.SemiBold)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Кнопка добавления записи
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = { /* TODO */ },
|
|
||||||
modifier = Modifier.fillMaxWidth()
|
|
||||||
) {
|
|
||||||
Text("Записать сон")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Карточка эмоций
|
|
||||||
Card(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
shape = MaterialTheme.shapes.extraLarge,
|
|
||||||
colors = CardDefaults.cardColors(
|
|
||||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
modifier = Modifier.padding(16.dp),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
|
||||||
) {
|
|
||||||
// Заголовок с иконкой
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
imageVector = Icons.Default.Favorite,
|
|
||||||
contentDescription = null,
|
|
||||||
tint = Color(0xFFE91E63)
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = "Эмоциональное состояние",
|
|
||||||
style = MaterialTheme.typography.titleMedium,
|
|
||||||
fontWeight = FontWeight.SemiBold
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Текущее настроение
|
|
||||||
Text(
|
|
||||||
text = "Текущее настроение: Спокойствие, удовлетворение",
|
|
||||||
style = MaterialTheme.typography.bodyMedium
|
|
||||||
)
|
|
||||||
|
|
||||||
// Кнопки эмоций
|
|
||||||
EmojiButtonsRow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Карточка рекомендаций
|
|
||||||
InfoCard(
|
|
||||||
title = "Рекомендации",
|
|
||||||
content = "Стабильный сон и низкий уровень стресса положительно влияют на ваш цикл. Рекомендуется поддерживать текущий режим для гормонального баланса."
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Строка кнопок с эмодзи для выбора эмоций
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
fun EmojiButtonsRow() {
|
|
||||||
val emojis = listOf("😊", "😌", "🙂", "😐", "😔", "😢", "😡")
|
|
||||||
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween
|
|
||||||
) {
|
|
||||||
emojis.forEach { emoji ->
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = { /* TODO */ },
|
|
||||||
contentPadding = PaddingValues(12.dp),
|
|
||||||
modifier = Modifier.size(44.dp),
|
|
||||||
shape = MaterialTheme.shapes.medium,
|
|
||||||
colors = ButtonDefaults.outlinedButtonColors(
|
|
||||||
contentColor = MaterialTheme.colorScheme.onSurface
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = emoji,
|
|
||||||
style = MaterialTheme.typography.titleMedium
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Preview(showBackground = true)
|
|
||||||
@Composable
|
|
||||||
fun MoodScreenPreview() {
|
|
||||||
WellSheTheme {
|
|
||||||
Surface(
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
|
||||||
color = MaterialTheme.colorScheme.background
|
|
||||||
) {
|
|
||||||
MoodScreen()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package kr.smartsoltech.wellshe.ui.mood
|
|
||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
@HiltViewModel
|
|
||||||
class MoodViewModel @Inject constructor() : ViewModel() {
|
|
||||||
// Данные для экрана настроения
|
|
||||||
private val _sleepHours = MutableStateFlow(7.2f)
|
|
||||||
val sleepHours: StateFlow<Float> = _sleepHours.asStateFlow()
|
|
||||||
|
|
||||||
private val _stressLevel = MutableStateFlow(3)
|
|
||||||
val stressLevel: StateFlow<Int> = _stressLevel.asStateFlow()
|
|
||||||
|
|
||||||
private val _journalEntry = MutableStateFlow("Сегодня было продуктивно, немного тревоги перед встречей.")
|
|
||||||
val journalEntry: StateFlow<String> = _journalEntry.asStateFlow()
|
|
||||||
|
|
||||||
fun updateSleepHours(hours: Float) {
|
|
||||||
_sleepHours.value = hours
|
|
||||||
}
|
|
||||||
|
|
||||||
fun updateStressLevel(level: Int) {
|
|
||||||
_stressLevel.value = level
|
|
||||||
}
|
|
||||||
|
|
||||||
fun updateJournalEntry(entry: String) {
|
|
||||||
_journalEntry.value = entry
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +1,69 @@
|
|||||||
package kr.smartsoltech.wellshe.ui.navigation
|
package kr.smartsoltech.wellshe.ui.navigation
|
||||||
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.navigation.NavHostController
|
import androidx.navigation.NavHostController
|
||||||
import androidx.navigation.compose.NavHost
|
import androidx.navigation.compose.NavHost
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
import kr.smartsoltech.wellshe.ui.analytics.AnalyticsScreen
|
import kr.smartsoltech.wellshe.ui.analytics.AnalyticsScreen
|
||||||
import kr.smartsoltech.wellshe.ui.body.BodyScreen
|
import kr.smartsoltech.wellshe.ui.body.BodyScreen
|
||||||
import kr.smartsoltech.wellshe.ui.cycle.CycleScreen
|
import kr.smartsoltech.wellshe.ui.cycle.CycleScreen
|
||||||
import kr.smartsoltech.wellshe.ui.mood.MoodScreen
|
import kr.smartsoltech.wellshe.emergency.presentation.screens.EmergencyScreen
|
||||||
import kr.smartsoltech.wellshe.ui.profile.ProfileScreen
|
import kr.smartsoltech.wellshe.ui.profile.ProfileScreen
|
||||||
|
import kr.smartsoltech.wellshe.ui.auth.AuthViewModel
|
||||||
|
import kr.smartsoltech.wellshe.ui.auth.compose.LoginScreen
|
||||||
|
import kr.smartsoltech.wellshe.ui.auth.compose.RegisterScreen
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun AppNavGraph(
|
fun AppNavGraph(
|
||||||
navController: NavHostController,
|
navController: NavHostController,
|
||||||
startDestination: String = BottomNavItem.Cycle.route
|
startDestination: String = "login", // Меняем стартовый экран на авторизацию
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
authViewModel: AuthViewModel // Добавляем параметр для доступа к AuthViewModel
|
||||||
) {
|
) {
|
||||||
NavHost(
|
NavHost(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
startDestination = startDestination
|
startDestination = startDestination,
|
||||||
|
modifier = modifier
|
||||||
) {
|
) {
|
||||||
|
// Авторизация и регистрация
|
||||||
|
composable("login") {
|
||||||
|
LoginScreen(
|
||||||
|
onNavigateToRegister = {
|
||||||
|
navController.navigate("register")
|
||||||
|
},
|
||||||
|
onLoginSuccess = {
|
||||||
|
navController.navigate(BottomNavItem.Cycle.route) {
|
||||||
|
popUpTo("login") { inclusive = true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
composable("register") {
|
||||||
|
RegisterScreen(
|
||||||
|
onNavigateBack = {
|
||||||
|
navController.popBackStack()
|
||||||
|
},
|
||||||
|
onRegisterSuccess = { email, password ->
|
||||||
|
// После успешной регистрации автоматически входим в систему с новыми учетными данными
|
||||||
|
authViewModel.login(email, password, true)
|
||||||
|
// Переходим на главный экран
|
||||||
|
navController.navigate(BottomNavItem.Cycle.route) {
|
||||||
|
popUpTo("login") { inclusive = true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Существующие экраны
|
||||||
composable(BottomNavItem.Cycle.route) {
|
composable(BottomNavItem.Cycle.route) {
|
||||||
CycleScreen(
|
CycleScreen(
|
||||||
onNavigateToSettings = {
|
onNavigateToSettings = {
|
||||||
navController.navigate("cycle_settings")
|
navController.navigate("cycle_settings")
|
||||||
|
},
|
||||||
|
onNavigateToEmergency = {
|
||||||
|
navController.navigate("emergency")
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -40,8 +81,15 @@ fun AppNavGraph(
|
|||||||
BodyScreen()
|
BodyScreen()
|
||||||
}
|
}
|
||||||
|
|
||||||
composable(BottomNavItem.Mood.route) {
|
composable(BottomNavItem.Emergency.route) {
|
||||||
MoodScreen()
|
EmergencyScreen(
|
||||||
|
onNavigateToMap = {
|
||||||
|
// TODO: Добавить навигацию к карте
|
||||||
|
},
|
||||||
|
onNavigateToHistory = {
|
||||||
|
// TODO: Добавить навигацию к истории
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
composable(BottomNavItem.Analytics.route) {
|
composable(BottomNavItem.Analytics.route) {
|
||||||
@@ -49,7 +97,17 @@ fun AppNavGraph(
|
|||||||
}
|
}
|
||||||
|
|
||||||
composable(BottomNavItem.Profile.route) {
|
composable(BottomNavItem.Profile.route) {
|
||||||
ProfileScreen()
|
ProfileScreen(
|
||||||
|
onLogout = {
|
||||||
|
// Вызываем метод выхода из AuthViewModel, который очищает токены
|
||||||
|
authViewModel.logout()
|
||||||
|
// Переходим на экран авторизации после выхода
|
||||||
|
navController.navigate("login") {
|
||||||
|
// Очищаем весь стек навигации
|
||||||
|
popUpTo(0) { inclusive = true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,14 +2,14 @@ package kr.smartsoltech.wellshe.ui.navigation
|
|||||||
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.BarChart
|
import androidx.compose.material.icons.filled.BarChart
|
||||||
import androidx.compose.material.icons.filled.Favorite
|
import androidx.compose.material.icons.filled.Emergency
|
||||||
import androidx.compose.material.icons.filled.Person
|
import androidx.compose.material.icons.filled.Person
|
||||||
import androidx.compose.material.icons.filled.WaterDrop
|
import androidx.compose.material.icons.filled.WaterDrop
|
||||||
import androidx.compose.material.icons.filled.WbSunny
|
import androidx.compose.material.icons.filled.WbSunny
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Модель навигационного элемента для нижней панели навигац<EFBFBD><EFBFBD>и
|
* Модель навигационного элемента для нижней панели навигации
|
||||||
*/
|
*/
|
||||||
sealed class BottomNavItem(
|
sealed class BottomNavItem(
|
||||||
val route: String,
|
val route: String,
|
||||||
@@ -28,10 +28,10 @@ sealed class BottomNavItem(
|
|||||||
icon = Icons.Default.WaterDrop
|
icon = Icons.Default.WaterDrop
|
||||||
)
|
)
|
||||||
|
|
||||||
data object Mood : BottomNavItem(
|
data object Emergency : BottomNavItem(
|
||||||
route = "mood",
|
route = "emergency",
|
||||||
title = "Настроение",
|
title = "Экстренное",
|
||||||
icon = Icons.Default.Favorite
|
icon = Icons.Default.Emergency
|
||||||
)
|
)
|
||||||
|
|
||||||
data object Analytics : BottomNavItem(
|
data object Analytics : BottomNavItem(
|
||||||
@@ -47,6 +47,6 @@ sealed class BottomNavItem(
|
|||||||
)
|
)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val items = listOf(Cycle, Body, Mood, Analytics, Profile)
|
val items = listOf(Cycle, Body, Emergency, Analytics, Profile)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,114 +2,90 @@ package kr.smartsoltech.wellshe.ui.navigation
|
|||||||
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.border
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.draw.shadow
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.navigation.NavController
|
import androidx.navigation.NavController
|
||||||
import androidx.navigation.NavDestination.Companion.hierarchy
|
import androidx.navigation.NavDestination.Companion.hierarchy
|
||||||
import androidx.navigation.NavGraph.Companion.findStartDestination
|
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
import kr.smartsoltech.wellshe.ui.theme.*
|
import kr.smartsoltech.wellshe.ui.theme.*
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun BottomNavigation(
|
fun BottomNavigation(
|
||||||
navController: NavController,
|
navController: NavController,
|
||||||
modifier: Modifier = Modifier
|
modifier: Modifier = Modifier
|
||||||
) {
|
|
||||||
NavigationBar(
|
|
||||||
modifier = modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.height(64.dp)
|
|
||||||
.imePadding(), // Добавляем отступ для клавиатуры
|
|
||||||
containerColor = MaterialTheme.colorScheme.background,
|
|
||||||
tonalElevation = 8.dp,
|
|
||||||
windowInsets = WindowInsets.systemBars.only(WindowInsetsSides.Horizontal) // Учитываем только горизонтальные системные отступы
|
|
||||||
) {
|
) {
|
||||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||||
val currentDestination = navBackStackEntry?.destination
|
val currentDestination = navBackStackEntry?.destination
|
||||||
|
|
||||||
val items = BottomNavItem.items
|
val items = BottomNavItem.items
|
||||||
|
|
||||||
|
Box(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(72.dp)
|
||||||
|
.background(MaterialTheme.colorScheme.background)
|
||||||
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly
|
.fillMaxWidth()
|
||||||
|
.align(Alignment.BottomCenter)
|
||||||
|
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||||
|
verticalAlignment = Alignment.Bottom
|
||||||
) {
|
) {
|
||||||
items.forEach { item ->
|
items.forEach { item ->
|
||||||
val selected = currentDestination?.hierarchy?.any { it.route == item.route } == true
|
val selected = currentDestination?.hierarchy?.any { it.route == item.route } == true
|
||||||
|
val isEmergency = item == BottomNavItem.Emergency
|
||||||
// Определяем цвет фона для выбранного элемента
|
val size = if (isEmergency) 72.dp else 56.dp
|
||||||
val backgroundColor = when (item) {
|
val iconSize = if (isEmergency) 40.dp else 28.dp
|
||||||
BottomNavItem.Cycle -> CycleTabColor
|
val offsetY = if (isEmergency) (-20).dp else if (selected) (-8).dp else 0.dp
|
||||||
BottomNavItem.Body -> BodyTabColor
|
val bgColor = when {
|
||||||
BottomNavItem.Mood -> MoodTabColor
|
isEmergency -> Color(0xFFFF1744)
|
||||||
BottomNavItem.Analytics -> AnalyticsTabColor
|
selected -> Color.White
|
||||||
BottomNavItem.Profile -> ProfileTabColor
|
else -> Color(0xFFF5F5F5)
|
||||||
}
|
}
|
||||||
|
val borderColor = when {
|
||||||
// Создаем кастомный элемент навигации с привязкой к верхнему краю
|
isEmergency -> Color(0xFFB71C1C)
|
||||||
Column(
|
selected -> Color(0xFF1976D2)
|
||||||
|
else -> Color.Transparent
|
||||||
|
}
|
||||||
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.weight(1f)
|
.offset(y = offsetY)
|
||||||
|
.size(size)
|
||||||
|
.shadow(if (isEmergency || selected) 8.dp else 0.dp, CircleShape)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(bgColor)
|
||||||
|
.border(
|
||||||
|
width = if (isEmergency || selected) 4.dp else 0.dp,
|
||||||
|
color = borderColor,
|
||||||
|
shape = CircleShape
|
||||||
|
)
|
||||||
.clickable {
|
.clickable {
|
||||||
navController.navigate(item.route) {
|
navController.navigate(item.route) {
|
||||||
// Pop up to the start destination of the graph to
|
popUpTo(navController.graph.findStartDestination().id) { saveState = true }
|
||||||
// avoid building up a large stack of destinations
|
|
||||||
popUpTo(navController.graph.findStartDestination().id) {
|
|
||||||
saveState = true
|
|
||||||
}
|
|
||||||
// Avoid multiple copies of the same destination
|
|
||||||
launchSingleTop = true
|
launchSingleTop = true
|
||||||
// Restore state when reselecting
|
|
||||||
restoreState = true
|
restoreState = true
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
.padding(4.dp),
|
contentAlignment = Alignment.Center
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
verticalArrangement = Arrangement.Top // Привязываем контент к верхнему краю
|
|
||||||
) {
|
) {
|
||||||
// Иконка - размещаем вверху
|
|
||||||
if (selected) {
|
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = item.icon,
|
imageVector = item.icon,
|
||||||
contentDescription = item.title,
|
contentDescription = item.title,
|
||||||
modifier = Modifier
|
modifier = Modifier.size(iconSize),
|
||||||
.padding(top = 4.dp)
|
tint = if (isEmergency) Color.White else if (selected) Color(0xFF1976D2) else Color(0xFF757575)
|
||||||
.size(32.dp) // Унифицируем размер иконок
|
|
||||||
.clip(RoundedCornerShape(6.dp))
|
|
||||||
.background(backgroundColor)
|
|
||||||
.padding(4.dp),
|
|
||||||
tint = MaterialTheme.colorScheme.onPrimaryContainer
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Icon(
|
|
||||||
imageVector = item.icon,
|
|
||||||
contentDescription = item.title,
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(top = 4.dp)
|
|
||||||
.size(32.dp), // Размер не изменился
|
|
||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Текстовая метка
|
|
||||||
Spacer(modifier = Modifier.height(2.dp))
|
|
||||||
Text(
|
|
||||||
text = item.title,
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = if (selected)
|
|
||||||
MaterialTheme.colorScheme.onSurface
|
|
||||||
else
|
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
textAlign = TextAlign.Center,
|
|
||||||
maxLines = 1
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,9 @@ import androidx.compose.material3.Surface
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.tooling.preview.Preview
|
import androidx.compose.ui.tooling.preview.Preview
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import androidx.navigation.compose.rememberNavController
|
import androidx.navigation.compose.rememberNavController
|
||||||
|
import kr.smartsoltech.wellshe.ui.auth.AuthViewModel
|
||||||
import kr.smartsoltech.wellshe.ui.theme.WellSheTheme
|
import kr.smartsoltech.wellshe.ui.theme.WellSheTheme
|
||||||
|
|
||||||
// Добавляем явный импорт для BottomNavigation из того же пакета
|
// Добавляем явный импорт для BottomNavigation из того же пакета
|
||||||
@@ -20,6 +22,8 @@ import kr.smartsoltech.wellshe.ui.navigation.BottomNavigation
|
|||||||
@Composable
|
@Composable
|
||||||
fun WellSheNavigation() {
|
fun WellSheNavigation() {
|
||||||
val navController = rememberNavController()
|
val navController = rememberNavController()
|
||||||
|
// Получаем AuthViewModel с помощью viewModel() делегата
|
||||||
|
val authViewModel: AuthViewModel = viewModel()
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
bottomBar = {
|
bottomBar = {
|
||||||
@@ -31,7 +35,11 @@ fun WellSheNavigation() {
|
|||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(paddingValues)
|
.padding(paddingValues)
|
||||||
) {
|
) {
|
||||||
AppNavGraph(navController = navController)
|
// Передаем authViewModel в AppNavGraph
|
||||||
|
AppNavGraph(
|
||||||
|
navController = navController,
|
||||||
|
authViewModel = authViewModel
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,427 @@
|
|||||||
|
package kr.smartsoltech.wellshe.ui.profile
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.ContactsContract
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.*
|
||||||
|
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.unit.dp
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import kr.smartsoltech.wellshe.model.auth.UserProfile
|
||||||
|
import kr.smartsoltech.wellshe.ui.components.PermissionRequestDialog
|
||||||
|
import kr.smartsoltech.wellshe.ui.profile.viewmodel.ProfileViewModel
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ProfileEditScreen(
|
||||||
|
onNavigateBack: () -> Unit,
|
||||||
|
viewModel: ProfileViewModel = hiltViewModel()
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
|
||||||
|
// Состояние для профиля пользователя
|
||||||
|
var userProfile by remember { mutableStateOf(viewModel.userProfile.value ?: UserProfile()) }
|
||||||
|
|
||||||
|
// Состояния для показа диалогов выбора даты и разрешений
|
||||||
|
var showDatePicker by remember { mutableStateOf(false) }
|
||||||
|
var showContactPermissionDialog by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
// Состояние для обработки запроса разрешений на контакты
|
||||||
|
var contactType by remember { mutableStateOf(ContactType.NONE) }
|
||||||
|
|
||||||
|
// Launcher для выбора контакта
|
||||||
|
val contactPickerLauncher = rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.StartActivityForResult()
|
||||||
|
) { result ->
|
||||||
|
if (result.resultCode == Activity.RESULT_OK) {
|
||||||
|
result.data?.data?.let { contactUri ->
|
||||||
|
// Обрабатываем выбранный контакт
|
||||||
|
val projection = arrayOf(
|
||||||
|
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
|
||||||
|
ContactsContract.CommonDataKinds.Phone.NUMBER
|
||||||
|
)
|
||||||
|
|
||||||
|
context.contentResolver.query(contactUri, projection, null, null, null)?.use { cursor ->
|
||||||
|
if (cursor.moveToFirst()) {
|
||||||
|
val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
|
||||||
|
val numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
|
||||||
|
|
||||||
|
val name = cursor.getString(nameIndex)
|
||||||
|
val phone = cursor.getString(numberIndex)
|
||||||
|
|
||||||
|
// Обновляем профиль в зависимости от типа контакта
|
||||||
|
when (contactType) {
|
||||||
|
ContactType.EMERGENCY_1 -> {
|
||||||
|
userProfile = userProfile.copy(
|
||||||
|
emergency_contact_1_name = name,
|
||||||
|
emergency_contact_1_phone = phone
|
||||||
|
)
|
||||||
|
}
|
||||||
|
ContactType.EMERGENCY_2 -> {
|
||||||
|
userProfile = userProfile.copy(
|
||||||
|
emergency_contact_2_name = name,
|
||||||
|
emergency_contact_2_phone = phone
|
||||||
|
)
|
||||||
|
}
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Запрос разрешения на доступ к контактам
|
||||||
|
val contactPermissionLauncher = rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.RequestPermission()
|
||||||
|
) { isGranted ->
|
||||||
|
if (isGranted) {
|
||||||
|
// Если разрешение получено, запускаем выбор контакта
|
||||||
|
val intent = Intent(Intent.ACTION_PICK).apply {
|
||||||
|
setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE)
|
||||||
|
}
|
||||||
|
contactPickerLauncher.launch(intent)
|
||||||
|
} else {
|
||||||
|
// Если разрешение не получено, показываем диалог
|
||||||
|
showContactPermissionDialog = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверка и запрос разрешения на доступ к контактам
|
||||||
|
fun checkAndRequestContactPermission(type: ContactType) {
|
||||||
|
contactType = type
|
||||||
|
|
||||||
|
when (PackageManager.PERMISSION_GRANTED) {
|
||||||
|
ContextCompat.checkSelfPermission(
|
||||||
|
context,
|
||||||
|
Manifest.permission.READ_CONTACTS
|
||||||
|
) -> {
|
||||||
|
// Разрешение уже есть, запускаем выбор контакта
|
||||||
|
val intent = Intent(Intent.ACTION_PICK).apply {
|
||||||
|
setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE)
|
||||||
|
}
|
||||||
|
contactPickerLauncher.launch(intent)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
// Запрашиваем разрешение
|
||||||
|
contactPermissionLauncher.launch(Manifest.permission.READ_CONTACTS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Диалог выбора даты рождения
|
||||||
|
if (showDatePicker) {
|
||||||
|
val currentDate = userProfile.date_of_birth?.let {
|
||||||
|
try {
|
||||||
|
LocalDate.parse(it)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
LocalDate.now().minusYears(20)
|
||||||
|
}
|
||||||
|
} ?: LocalDate.now().minusYears(20)
|
||||||
|
|
||||||
|
DatePickerDialog(
|
||||||
|
onDismissRequest = { showDatePicker = false },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
val selectedDate = LocalDate.of(
|
||||||
|
viewModel.datePickerState.selectedDateMillis?.let { millis ->
|
||||||
|
java.time.Instant.ofEpochMilli(millis).atZone(java.time.ZoneId.systemDefault()).toLocalDate().year
|
||||||
|
} ?: currentDate.year,
|
||||||
|
viewModel.datePickerState.selectedDateMillis?.let { millis ->
|
||||||
|
java.time.Instant.ofEpochMilli(millis).atZone(java.time.ZoneId.systemDefault()).toLocalDate().monthValue
|
||||||
|
} ?: currentDate.monthValue,
|
||||||
|
viewModel.datePickerState.selectedDateMillis?.let { millis ->
|
||||||
|
java.time.Instant.ofEpochMilli(millis).atZone(java.time.ZoneId.systemDefault()).toLocalDate().dayOfMonth
|
||||||
|
} ?: currentDate.dayOfMonth
|
||||||
|
)
|
||||||
|
|
||||||
|
userProfile = userProfile.copy(
|
||||||
|
date_of_birth = selectedDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
|
||||||
|
)
|
||||||
|
showDatePicker = false
|
||||||
|
}) {
|
||||||
|
Text("OK")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showDatePicker = false }) {
|
||||||
|
Text("Отмена")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
DatePicker(state = viewModel.datePickerState)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Диалог запроса разрешения на контакты
|
||||||
|
if (showContactPermissionDialog) {
|
||||||
|
PermissionRequestDialog(
|
||||||
|
permissionText = "Для выбора экстренного контакта необходимо разрешение на доступ к контактам.",
|
||||||
|
onDismiss = { showContactPermissionDialog = false },
|
||||||
|
onConfirm = {
|
||||||
|
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
|
||||||
|
data = Uri.fromParts("package", context.packageName, null)
|
||||||
|
}
|
||||||
|
context.startActivity(intent)
|
||||||
|
showContactPermissionDialog = false
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text("Редактирование профиля") },
|
||||||
|
navigationIcon = {
|
||||||
|
IconButton(onClick = onNavigateBack) {
|
||||||
|
Icon(Icons.Filled.ArrowBack, contentDescription = "Назад")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
actions = {
|
||||||
|
IconButton(onClick = {
|
||||||
|
viewModel.updateUserProfile(userProfile)
|
||||||
|
onNavigateBack()
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Filled.Save, contentDescription = "Сохранить")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
) { paddingValues ->
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(paddingValues)
|
||||||
|
.padding(horizontal = 16.dp)
|
||||||
|
.verticalScroll(scrollState),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
// Раздел с основной информацией
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.surface
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Личная информация",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = userProfile.bio ?: "",
|
||||||
|
onValueChange = { userProfile = userProfile.copy(bio = it) },
|
||||||
|
label = { Text("О себе") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
minLines = 3,
|
||||||
|
maxLines = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
// Дата рождения
|
||||||
|
OutlinedTextField(
|
||||||
|
value = userProfile.date_of_birth ?: "",
|
||||||
|
onValueChange = {},
|
||||||
|
label = { Text("Дата рождения") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
readOnly = true,
|
||||||
|
trailingIcon = {
|
||||||
|
IconButton(onClick = { showDatePicker = true }) {
|
||||||
|
Icon(Icons.Filled.DateRange, contentDescription = "Выбрать дату")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Раздел с экстренными контактами
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.surface
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Экстренные контакты",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
// Первый экстренный контакт
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Первый контакт",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = FontWeight.Medium
|
||||||
|
)
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = if (userProfile.emergency_contact_1_name.isNullOrBlank()) "Не выбрано"
|
||||||
|
else "${userProfile.emergency_contact_1_name}\n${userProfile.emergency_contact_1_phone}",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = { checkAndRequestContactPermission(ContactType.EMERGENCY_1) },
|
||||||
|
modifier = Modifier.padding(start = 8.dp)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Contacts, contentDescription = "Выбрать контакт")
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text("Выбрать")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Второй экстренный контакт
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Второй контакт",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = FontWeight.Medium
|
||||||
|
)
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = if (userProfile.emergency_contact_2_name.isNullOrBlank()) "Не выбрано"
|
||||||
|
else "${userProfile.emergency_contact_2_name}\n${userProfile.emergency_contact_2_phone}",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = { checkAndRequestContactPermission(ContactType.EMERGENCY_2) },
|
||||||
|
modifier = Modifier.padding(start = 8.dp)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Contacts, contentDescription = "Выбрать контакт")
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text("Выбрать")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Раздел с настройками уведомлений и доступа
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.surface
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Настройки и разрешения",
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
// Включение/выключение экстренных уведомлений
|
||||||
|
SwitchRow(
|
||||||
|
title = "Экстренные уведомления",
|
||||||
|
checked = userProfile.emergency_notifications_enabled ?: false,
|
||||||
|
onCheckedChange = {
|
||||||
|
userProfile = userProfile.copy(emergency_notifications_enabled = it)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Включение/выключение обмена местоположением
|
||||||
|
SwitchRow(
|
||||||
|
title = "Обмен местоположением",
|
||||||
|
checked = userProfile.location_sharing_enabled ?: false,
|
||||||
|
onCheckedChange = {
|
||||||
|
userProfile = userProfile.copy(location_sharing_enabled = it)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Включение/выключение push-уведомлений
|
||||||
|
SwitchRow(
|
||||||
|
title = "Push-уведомления",
|
||||||
|
checked = userProfile.push_notifications_enabled ?: false,
|
||||||
|
onCheckedChange = {
|
||||||
|
userProfile = userProfile.copy(push_notifications_enabled = it)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SwitchRow(
|
||||||
|
title: String,
|
||||||
|
checked: Boolean,
|
||||||
|
onCheckedChange: (Boolean) -> Unit
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = title,
|
||||||
|
style = MaterialTheme.typography.bodyMedium
|
||||||
|
)
|
||||||
|
|
||||||
|
Switch(
|
||||||
|
checked = checked,
|
||||||
|
onCheckedChange = onCheckedChange
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Перечисление типов контактов
|
||||||
|
enum class ContactType {
|
||||||
|
NONE,
|
||||||
|
EMERGENCY_1,
|
||||||
|
EMERGENCY_2
|
||||||
|
}
|
||||||
@@ -24,7 +24,8 @@ import kr.smartsoltech.wellshe.ui.theme.WellSheTheme
|
|||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun ProfileScreen(
|
fun ProfileScreen(
|
||||||
modifier: Modifier = Modifier
|
modifier: Modifier = Modifier,
|
||||||
|
onLogout: () -> Unit = {} // Добавляем параметр для выхода из аккаунта
|
||||||
) {
|
) {
|
||||||
val scrollState = rememberScrollState()
|
val scrollState = rememberScrollState()
|
||||||
|
|
||||||
@@ -59,9 +60,9 @@ fun ProfileScreen(
|
|||||||
var integrations by remember {
|
var integrations by remember {
|
||||||
mutableStateOf(
|
mutableStateOf(
|
||||||
listOf(
|
listOf(
|
||||||
Integration("Google Fit", false),
|
Integration("Google Fit", true),
|
||||||
Integration("FatSecret Proxy", true),
|
Integration("FatSecret Proxy", false),
|
||||||
Integration("Wear OS", false)
|
Integration("Wear OS", true)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -105,7 +106,7 @@ fun ProfileScreen(
|
|||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = "Цель воды (мл)",
|
text = "Цель воды в сутки (мл)",
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
)
|
)
|
||||||
@@ -295,6 +296,19 @@ fun ProfileScreen(
|
|||||||
Text("Экспорт настроек")
|
Text("Экспорт настроек")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Кнопка выхода из аккаунта
|
||||||
|
Button(
|
||||||
|
onClick = { onLogout() },
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(top = 16.dp),
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.error
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Text("Выход из аккаунта")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package kr.smartsoltech.wellshe.ui.profile.viewmodel
|
||||||
|
|
||||||
|
import androidx.compose.material3.DatePickerState
|
||||||
|
import androidx.compose.material3.DisplayMode
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
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.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kr.smartsoltech.wellshe.model.auth.UserProfile
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneId
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@HiltViewModel
|
||||||
|
class ProfileViewModel @Inject constructor() : ViewModel() {
|
||||||
|
|
||||||
|
private val _userProfile = MutableStateFlow<UserProfile?>(null)
|
||||||
|
val userProfile: StateFlow<UserProfile?> = _userProfile.asStateFlow()
|
||||||
|
|
||||||
|
private val _isLoading = MutableStateFlow(false)
|
||||||
|
val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
|
||||||
|
|
||||||
|
private val _error = MutableStateFlow<String?>(null)
|
||||||
|
val error: StateFlow<String?> = _error.asStateFlow()
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
val datePickerState = DatePickerState(
|
||||||
|
initialSelectedDateMillis = LocalDate.now().minusYears(20).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli(),
|
||||||
|
initialDisplayedMonthMillis = LocalDate.now().minusYears(20).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli(),
|
||||||
|
yearRange = IntRange(1900, LocalDate.now().year),
|
||||||
|
initialDisplayMode = DisplayMode.Picker,
|
||||||
|
locale = java.util.Locale.getDefault()
|
||||||
|
)
|
||||||
|
|
||||||
|
init {
|
||||||
|
loadUserProfile()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadUserProfile() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_isLoading.value = true
|
||||||
|
try {
|
||||||
|
// Здесь должен быть запрос к API или базе данных для получения профиля пользователя
|
||||||
|
// Пока используем заполнитель с фиктивными данными
|
||||||
|
_userProfile.value = UserProfile(
|
||||||
|
username = "user123",
|
||||||
|
email = "user@example.com",
|
||||||
|
firstName = "Иван",
|
||||||
|
lastName = "Иванов",
|
||||||
|
phone = "+7 (999) 123-45-67"
|
||||||
|
)
|
||||||
|
_error.value = null
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_error.value = "Не удалось загрузить профиль: ${e.message}"
|
||||||
|
} finally {
|
||||||
|
_isLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateUserProfile(profile: UserProfile) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_isLoading.value = true
|
||||||
|
try {
|
||||||
|
// Здесь должен быть запрос к API или базе данных для обновления профиля
|
||||||
|
// Пока просто обновляем локальное состояние
|
||||||
|
_userProfile.value = profile
|
||||||
|
_error.value = null
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_error.value = "Не удалось обновить профиль: ${e.message}"
|
||||||
|
} finally {
|
||||||
|
_isLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearError() {
|
||||||
|
_error.value = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -59,10 +59,8 @@ fun SettingsScreen(
|
|||||||
NotificationSettingsCard(
|
NotificationSettingsCard(
|
||||||
isWaterReminderEnabled = uiState.isWaterReminderEnabled,
|
isWaterReminderEnabled = uiState.isWaterReminderEnabled,
|
||||||
isCycleReminderEnabled = uiState.isCycleReminderEnabled,
|
isCycleReminderEnabled = uiState.isCycleReminderEnabled,
|
||||||
isSleepReminderEnabled = uiState.isSleepReminderEnabled,
|
onWaterReminderToggle = viewModel::updateWaterReminder,
|
||||||
onWaterReminderToggle = viewModel::toggleWaterReminder,
|
onCycleReminderToggle = viewModel::updateCycleReminder
|
||||||
onCycleReminderToggle = viewModel::toggleCycleReminder,
|
|
||||||
onSleepReminderToggle = viewModel::toggleSleepReminder
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,24 +77,22 @@ fun SettingsScreen(
|
|||||||
GoalsSettingsCard(
|
GoalsSettingsCard(
|
||||||
waterGoal = uiState.waterGoal,
|
waterGoal = uiState.waterGoal,
|
||||||
stepsGoal = uiState.stepsGoal,
|
stepsGoal = uiState.stepsGoal,
|
||||||
sleepGoal = uiState.sleepGoal,
|
|
||||||
onWaterGoalChange = viewModel::updateWaterGoal,
|
onWaterGoalChange = viewModel::updateWaterGoal,
|
||||||
onStepsGoalChange = viewModel::updateStepsGoal,
|
onStepsGoalChange = viewModel::updateStepsGoal
|
||||||
onSleepGoalChange = viewModel::updateSleepGoal
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
item {
|
item {
|
||||||
AppearanceSettingsCard(
|
AppearanceSettingsCard(
|
||||||
isDarkTheme = uiState.isDarkTheme,
|
isDarkTheme = uiState.isDarkTheme,
|
||||||
onThemeToggle = viewModel::toggleTheme
|
onThemeToggle = viewModel::updateTheme
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
item {
|
item {
|
||||||
DataManagementCard(
|
DataManagementCard(
|
||||||
onExportData = viewModel::exportData,
|
onExportData = viewModel::exportData,
|
||||||
onImportData = viewModel::importData,
|
onImportData = { viewModel.importData(it) },
|
||||||
onClearData = viewModel::clearAllData
|
onClearData = viewModel::clearAllData
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -155,10 +151,8 @@ private fun SettingsHeader(
|
|||||||
private fun NotificationSettingsCard(
|
private fun NotificationSettingsCard(
|
||||||
isWaterReminderEnabled: Boolean,
|
isWaterReminderEnabled: Boolean,
|
||||||
isCycleReminderEnabled: Boolean,
|
isCycleReminderEnabled: Boolean,
|
||||||
isSleepReminderEnabled: Boolean,
|
|
||||||
onWaterReminderToggle: (Boolean) -> Unit,
|
onWaterReminderToggle: (Boolean) -> Unit,
|
||||||
onCycleReminderToggle: (Boolean) -> Unit,
|
onCycleReminderToggle: (Boolean) -> Unit,
|
||||||
onSleepReminderToggle: (Boolean) -> Unit,
|
|
||||||
modifier: Modifier = Modifier
|
modifier: Modifier = Modifier
|
||||||
) {
|
) {
|
||||||
SettingsCard(
|
SettingsCard(
|
||||||
@@ -181,15 +175,6 @@ private fun NotificationSettingsCard(
|
|||||||
isChecked = isCycleReminderEnabled,
|
isChecked = isCycleReminderEnabled,
|
||||||
onCheckedChange = onCycleReminderToggle
|
onCheckedChange = onCycleReminderToggle
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
|
||||||
|
|
||||||
SettingsSwitchItem(
|
|
||||||
title = "Напоминания о сне",
|
|
||||||
subtitle = "Уведомления о режиме сна",
|
|
||||||
isChecked = isSleepReminderEnabled,
|
|
||||||
onCheckedChange = onSleepReminderToggle
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,10 +219,8 @@ private fun CycleSettingsCard(
|
|||||||
private fun GoalsSettingsCard(
|
private fun GoalsSettingsCard(
|
||||||
waterGoal: Float,
|
waterGoal: Float,
|
||||||
stepsGoal: Int,
|
stepsGoal: Int,
|
||||||
sleepGoal: Float,
|
|
||||||
onWaterGoalChange: (Float) -> Unit,
|
onWaterGoalChange: (Float) -> Unit,
|
||||||
onStepsGoalChange: (Int) -> Unit,
|
onStepsGoalChange: (Int) -> Unit,
|
||||||
onSleepGoalChange: (Float) -> Unit,
|
|
||||||
modifier: Modifier = Modifier
|
modifier: Modifier = Modifier
|
||||||
) {
|
) {
|
||||||
SettingsCard(
|
SettingsCard(
|
||||||
@@ -266,18 +249,6 @@ private fun GoalsSettingsCard(
|
|||||||
},
|
},
|
||||||
suffix = "шагов"
|
suffix = "шагов"
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(20.dp))
|
|
||||||
|
|
||||||
SettingsDecimalField(
|
|
||||||
title = "Цель по сну",
|
|
||||||
subtitle = "Количество часов сна (6-10 часов)",
|
|
||||||
value = sleepGoal,
|
|
||||||
onValueChange = { value ->
|
|
||||||
if (value in 6.0f..10.0f) onSleepGoalChange(value)
|
|
||||||
},
|
|
||||||
suffix = "часов"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,7 +275,7 @@ private fun AppearanceSettingsCard(
|
|||||||
@Composable
|
@Composable
|
||||||
private fun DataManagementCard(
|
private fun DataManagementCard(
|
||||||
onExportData: () -> Unit,
|
onExportData: () -> Unit,
|
||||||
onImportData: () -> Unit,
|
onImportData: (String) -> Unit,
|
||||||
onClearData: () -> Unit,
|
onClearData: () -> Unit,
|
||||||
modifier: Modifier = Modifier
|
modifier: Modifier = Modifier
|
||||||
) {
|
) {
|
||||||
@@ -326,7 +297,7 @@ private fun DataManagementCard(
|
|||||||
title = "Импорт данных",
|
title = "Импорт данных",
|
||||||
subtitle = "Загрузить данные из файла",
|
subtitle = "Загрузить данные из файла",
|
||||||
icon = Icons.Default.Upload,
|
icon = Icons.Default.Upload,
|
||||||
onClick = onImportData
|
onClick = { onImportData("") }
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|||||||
@@ -14,12 +14,10 @@ import javax.inject.Inject
|
|||||||
data class SettingsUiState(
|
data class SettingsUiState(
|
||||||
val isWaterReminderEnabled: Boolean = true,
|
val isWaterReminderEnabled: Boolean = true,
|
||||||
val isCycleReminderEnabled: Boolean = true,
|
val isCycleReminderEnabled: Boolean = true,
|
||||||
val isSleepReminderEnabled: Boolean = true,
|
|
||||||
val cycleLength: Int = 28,
|
val cycleLength: Int = 28,
|
||||||
val periodLength: Int = 5,
|
val periodLength: Int = 5,
|
||||||
val waterGoal: Float = 2.5f,
|
val waterGoal: Float = 2.5f,
|
||||||
val stepsGoal: Int = 10000,
|
val stepsGoal: Int = 10000,
|
||||||
val sleepGoal: Float = 8.0f,
|
|
||||||
val isDarkTheme: Boolean = false,
|
val isDarkTheme: Boolean = false,
|
||||||
val isLoading: Boolean = false,
|
val isLoading: Boolean = false,
|
||||||
val error: String? = null
|
val error: String? = null
|
||||||
@@ -38,23 +36,17 @@ class SettingsViewModel @Inject constructor(
|
|||||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
repository.getSettings().catch { e ->
|
// TODO: Временно используем заглушки до реализации методов в repository
|
||||||
|
repository.getAppSettings().catch { e ->
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
isLoading = false,
|
isLoading = false,
|
||||||
error = e.message
|
error = e.message
|
||||||
)
|
)
|
||||||
}.collect { settings ->
|
}.collect { settings ->
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
isWaterReminderEnabled = settings.isWaterReminderEnabled,
|
isDarkTheme = settings.darkModeEnabled,
|
||||||
isCycleReminderEnabled = settings.isCycleReminderEnabled,
|
isLoading = false,
|
||||||
isSleepReminderEnabled = settings.isSleepReminderEnabled,
|
error = null
|
||||||
cycleLength = settings.cycleLength,
|
|
||||||
periodLength = settings.periodLength,
|
|
||||||
waterGoal = settings.waterGoal,
|
|
||||||
stepsGoal = settings.stepsGoal,
|
|
||||||
sleepGoal = settings.sleepGoal,
|
|
||||||
isDarkTheme = settings.isDarkTheme,
|
|
||||||
isLoading = false
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -66,11 +58,11 @@ class SettingsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Уведомления
|
// Обновление настроек уведомлений
|
||||||
fun toggleWaterReminder(enabled: Boolean) {
|
fun updateWaterReminder(enabled: Boolean) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.updateWaterReminderSetting(enabled)
|
// TODO: Реализовать через repository
|
||||||
_uiState.value = _uiState.value.copy(isWaterReminderEnabled = enabled)
|
_uiState.value = _uiState.value.copy(isWaterReminderEnabled = enabled)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
@@ -78,10 +70,10 @@ class SettingsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun toggleCycleReminder(enabled: Boolean) {
|
fun updateCycleReminder(enabled: Boolean) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.updateCycleReminderSetting(enabled)
|
// TODO: Реализовать через repository
|
||||||
_uiState.value = _uiState.value.copy(isCycleReminderEnabled = enabled)
|
_uiState.value = _uiState.value.copy(isCycleReminderEnabled = enabled)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
@@ -89,23 +81,12 @@ class SettingsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun toggleSleepReminder(enabled: Boolean) {
|
// Обновление параметров цикла
|
||||||
viewModelScope.launch {
|
|
||||||
try {
|
|
||||||
repository.updateSleepReminderSetting(enabled)
|
|
||||||
_uiState.value = _uiState.value.copy(isSleepReminderEnabled = enabled)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Настройки цикла
|
|
||||||
fun updateCycleLength(length: Int) {
|
fun updateCycleLength(length: Int) {
|
||||||
if (length in 21..35) {
|
if (length in 21..35) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.updateCycleLength(length)
|
// TODO: Реализовать через repository
|
||||||
_uiState.value = _uiState.value.copy(cycleLength = length)
|
_uiState.value = _uiState.value.copy(cycleLength = length)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
@@ -115,10 +96,10 @@ class SettingsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun updatePeriodLength(length: Int) {
|
fun updatePeriodLength(length: Int) {
|
||||||
if (length in 3..8) {
|
if (length in 3..7) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.updatePeriodLength(length)
|
// TODO: Реализовать через repository
|
||||||
_uiState.value = _uiState.value.copy(periodLength = length)
|
_uiState.value = _uiState.value.copy(periodLength = length)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
@@ -127,12 +108,12 @@ class SettingsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Цели
|
// Обновление целей
|
||||||
fun updateWaterGoal(goal: Float) {
|
fun updateWaterGoal(goal: Float) {
|
||||||
if (goal in 1.5f..4.0f) {
|
if (goal > 0) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.updateWaterGoal(goal)
|
// TODO: Реализовать через repository
|
||||||
_uiState.value = _uiState.value.copy(waterGoal = goal)
|
_uiState.value = _uiState.value.copy(waterGoal = goal)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
@@ -142,10 +123,10 @@ class SettingsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun updateStepsGoal(goal: Int) {
|
fun updateStepsGoal(goal: Int) {
|
||||||
if (goal in 5000..20000) {
|
if (goal > 0) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.updateStepsGoal(goal)
|
// TODO: Реализовать через repository
|
||||||
_uiState.value = _uiState.value.copy(stepsGoal = goal)
|
_uiState.value = _uiState.value.copy(stepsGoal = goal)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
@@ -154,24 +135,11 @@ class SettingsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun updateSleepGoal(goal: Float) {
|
// Обновление темы
|
||||||
if (goal in 6.0f..10.0f) {
|
fun updateTheme(isDark: Boolean) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.updateSleepGoal(goal)
|
// TODO: Реализовать через repository
|
||||||
_uiState.value = _uiState.value.copy(sleepGoal = goal)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Внешний вид
|
|
||||||
fun toggleTheme(isDark: Boolean) {
|
|
||||||
viewModelScope.launch {
|
|
||||||
try {
|
|
||||||
repository.updateThemeSetting(isDark)
|
|
||||||
_uiState.value = _uiState.value.copy(isDarkTheme = isDark)
|
_uiState.value = _uiState.value.copy(isDarkTheme = isDark)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
@@ -179,35 +147,33 @@ class SettingsViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Управление данными
|
// Экспорт данных
|
||||||
fun exportData() {
|
fun exportData() {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.exportUserData()
|
// TODO: Реализовать экспорт данных
|
||||||
// Показать сообщение об успехе
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun importData() {
|
// Импорт данных
|
||||||
|
fun importData(data: String) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.importUserData()
|
// TODO: Реализовать импорт данных
|
||||||
loadSettings() // Перезагрузить настройки
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Очистка данных
|
||||||
fun clearAllData() {
|
fun clearAllData() {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
repository.clearAllUserData()
|
// TODO: Реализовать очистку данных
|
||||||
// Сбросить на дефолтные значения
|
|
||||||
_uiState.value = SettingsUiState()
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_uiState.value = _uiState.value.copy(error = e.message)
|
_uiState.value = _uiState.value.copy(error = e.message)
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user