Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
513c1785ef | ||
|
|
e70a53eca7 | ||
|
|
c3004a3d2e | ||
|
|
fda4b462dc | ||
|
|
6a1a15ade9 | ||
|
|
ea44cf5d2e | ||
|
|
984feb170a | ||
|
|
5691c87e91 | ||
|
|
227e08a671 | ||
|
|
3bfb5f9788 | ||
|
|
bf1cf3865a | ||
|
|
0c3bed6213 | ||
|
|
f1cb2d618d | ||
|
|
8c9a3b5b37 | ||
|
|
de8510bc79 | ||
|
|
34d01b312e | ||
|
|
f89332b28c | ||
|
|
8f12bf32bc | ||
|
|
b9ae128842 | ||
|
|
a86dca50b8 | ||
|
|
fc49eae512 | ||
|
|
ffbae9edfd | ||
|
|
2268c64250 | ||
|
|
c954fd9bb8 | ||
|
|
b9757348f2 | ||
|
|
130f8bbecc | ||
|
|
4c00d46a14 | ||
|
|
07fc4021e1 | ||
|
|
431436d0db | ||
|
|
905711d8de | ||
|
|
7c9cb3fb0d | ||
|
|
ae0d1b2d3d | ||
|
|
c5b3c5dae9 | ||
|
|
3fa3b4eac1 | ||
|
|
197bcc6f5e | ||
|
|
f4f5cec2be | ||
|
|
5a630f8401 | ||
|
|
54a3c58a22 | ||
|
|
1c6a044c37 | ||
|
|
fcc022db64 | ||
|
|
a908a2da18 | ||
|
|
2c25647fa5 | ||
|
|
956f33140e | ||
|
|
7bba4dc878 | ||
|
|
89235fbb46 | ||
|
|
0564101e9e | ||
|
|
2baa544b32 | ||
|
|
f9c3a2e305 | ||
|
|
e49e7c358e | ||
|
|
3267fee439 | ||
|
|
8a0651e578 | ||
|
|
32d45f6430 | ||
|
|
4a06e9da8b | ||
|
|
d6b36a1d3a | ||
|
|
e811b4bc43 | ||
|
|
5d3b355163 | ||
|
|
81f3b05653 | ||
|
|
37407e2737 | ||
|
|
13159c576e | ||
|
|
1834763f19 | ||
|
|
62c0469669 | ||
|
|
3d6e1624e9 | ||
|
|
b1a34105f1 | ||
|
|
72db88b25c | ||
|
|
97f0eb56d5 | ||
|
|
c6d6392656 | ||
|
|
958fb6eaa6 | ||
|
|
2c806ef14e | ||
|
|
0bbdbdb4f1 | ||
|
|
fe2e2e589a | ||
|
|
e0115e85fc | ||
|
|
0e15d5f9a4 | ||
|
|
5555676395 | ||
|
|
ca512f5993 | ||
|
|
64d6f5a41d | ||
|
|
a3d39764e2 | ||
|
|
705b8904a4 | ||
|
|
541dda292f | ||
|
|
fa98451533 | ||
|
|
ee9d8cdbaf | ||
|
|
76326bbc27 | ||
|
|
ed02da031b | ||
|
|
a4e24da717 | ||
|
|
ab84205bec | ||
|
|
9ba1b1fa13 | ||
|
|
06557e77b8 | ||
|
|
a08fe31d3d | ||
|
|
060896d12b | ||
|
|
1a26817d2c | ||
|
|
693f879078 | ||
|
|
0bc592f357 | ||
|
|
9b6564eedd | ||
|
|
a66351a6f4 | ||
|
|
b034384ab2 | ||
|
|
621745a93c | ||
|
|
bf6e76dcbf | ||
|
|
18baec5020 | ||
|
|
2531ff2b9f | ||
|
|
983a77c9fb |
@@ -1,5 +1,13 @@
|
||||
.gradle/
|
||||
build/
|
||||
local.properties
|
||||
app/google-services.json
|
||||
app/google-services.json:Zone.Identifier
|
||||
*/build/
|
||||
*.iml
|
||||
keystore.properties
|
||||
*.jks
|
||||
release-artifacts/
|
||||
app/src/main/res_bak/
|
||||
scripts/*.json
|
||||
scripts/*.json:Zone.Identifier
|
||||
|
||||
@@ -21,3 +21,65 @@ Natywna aplikacja Android Jetpack Compose dla kierowcow TPP.
|
||||
```bash
|
||||
./gradlew :app:testDebugUnitTest
|
||||
```
|
||||
|
||||
## Release Gitea i Google Play
|
||||
|
||||
Przed wydaniem zapisz wszystkie zmiany źródłowe w commicie. Następnie uruchom:
|
||||
|
||||
```bash
|
||||
./scripts/release-android.sh
|
||||
```
|
||||
|
||||
Skrypt automatycznie zwiększa `versionCode` i ostatni człon `versionName`, uruchamia testy,
|
||||
buduje podpisany APK oraz AAB, a po poprawnym buildzie pyta, czy wysłać aktualizację do
|
||||
Google Play. Po odpowiedzi „tak” publikuje AAB w skonfigurowanym teście zamkniętym i
|
||||
wysyła zmiany do weryfikacji. Następnie tworzy commit wersji, tag, push i Gitea Release.
|
||||
Artefakty zostają również zapisane lokalnie w `release-artifacts/<tag>/`.
|
||||
|
||||
Do publikacji Google Play konto serwisowe musi mieć dla aplikacji
|
||||
`pl.firmatpp.kierowca` uprawnienia „Wyświetlanie informacji o aplikacji (tylko do odczytu)”
|
||||
oraz „Publikowanie aplikacji na ścieżkach testowych”. Pobrany klucz JSON umieść
|
||||
bezpośrednio w folderze `scripts`, na przykład:
|
||||
|
||||
```text
|
||||
scripts/google-play-service-account.json
|
||||
```
|
||||
|
||||
Skrypt sam znajduje jedyny plik `scripts/*.json`, sprawdza, czy jest prawidłowym kluczem
|
||||
konta serwisowego, i używa go do autoryzacji. Pliki `scripts/*.json` są ignorowane przez
|
||||
Git i nie mogą zostać przypadkowo dodane do repozytorium. Jeśli w folderze znajduje się
|
||||
więcej niż jeden prawidłowy klucz, skrypt przerwie działanie i poprosi o pozostawienie
|
||||
jednego.
|
||||
|
||||
`GOOGLE_PLAY_TRACK` musi być identyfikatorem istniejącego testu zamkniętego. Domyślna
|
||||
wartość to `alpha`. Opcjonalnie można ustawić `GOOGLE_PLAY_PACKAGE_NAME` i
|
||||
`GOOGLE_PLAY_RELEASE_LANGUAGE` (domyślnie `pl-PL`). Zmienna
|
||||
`GOOGLE_PLAY_SERVICE_ACCOUNT_CREDENTIALS` pozostaje opcjonalnym sposobem wskazania klucza
|
||||
spoza folderu `scripts`. Skrypt nie zapisuje tokenu ani klucza w repozytorium; prywatny
|
||||
klucz tymczasowy jest usuwany po zakończeniu.
|
||||
|
||||
Przed zatwierdzeniem skrypt waliduje edycję Google Play. Commit edycji jawnie wysyła
|
||||
zmiany do weryfikacji. Jeżeli inne zmiany są już sprawdzane, skrypt nie anuluje ich —
|
||||
kończy się błędem i można go wznowić po zakończeniu poprzedniej weryfikacji.
|
||||
Jeżeli na koncie jest włączone publikowanie zarządzane, po akceptacji Google nadal trzeba
|
||||
wybrać „Opublikuj zmiany” w Play Console; bez publikowania zarządzanego zaakceptowane
|
||||
wydanie zostanie udostępnione testerom automatycznie.
|
||||
|
||||
Awaryjne wydanie wyłącznie do Gitea, bez Google Play:
|
||||
|
||||
```bash
|
||||
./scripts/release-android.sh --skip-google-play
|
||||
```
|
||||
|
||||
W środowisku bez interaktywnego terminala decyzję trzeba podać jawnie:
|
||||
|
||||
```bash
|
||||
./scripts/release-android.sh --publish-google-play
|
||||
```
|
||||
|
||||
Do autoryzacji Gitea używany jest `GITEA_TOKEN` albo dane zapisane w Git credential helper.
|
||||
Jeśli publikacja została przerwana już po utworzeniu commita wersji, można ją wznowić:
|
||||
|
||||
```bash
|
||||
./scripts/release-android.sh --reuse-current
|
||||
```
|
||||
|
||||
@@ -1,22 +1,65 @@
|
||||
import java.io.File
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
if (file("google-services.json").exists()) {
|
||||
apply(plugin = "com.google.gms.google-services")
|
||||
apply(plugin = "com.google.firebase.crashlytics")
|
||||
}
|
||||
|
||||
val keystorePropertiesFile = rootProject.file("keystore.properties")
|
||||
val keystoreProperties = Properties().apply {
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
keystorePropertiesFile.inputStream().use(::load)
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "pl.firmatpp.kierowca"
|
||||
compileSdk = 35
|
||||
compileSdk = 36
|
||||
|
||||
fun configValue(name: String, default: String): String =
|
||||
providers.gradleProperty(name)
|
||||
.orElse(providers.environmentVariable(name))
|
||||
.orElse(default)
|
||||
.get()
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "pl.firmatpp.kierowca"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 4
|
||||
versionName = "1.0.3"
|
||||
targetSdk = 36
|
||||
versionCode = 124
|
||||
versionName = "1.0.71"
|
||||
setProperty("archivesBaseName", "pl.firmatpp.kierowca")
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
buildConfigField("String", "API_BASE_URL", "\"https://api-intranet.firmatpp.pl/api/\"")
|
||||
buildConfigField("String", "REVERB_APP_KEY", "\"${configValue("REVERB_APP_KEY", "")}\"")
|
||||
buildConfigField("String", "REVERB_WS_BASE_URL", "\"${configValue("REVERB_WS_BASE_URL", "wss://api-intranet.firmatpp.pl/app/")}\"")
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
fun requiredSigningProperty(name: String): String =
|
||||
keystoreProperties.getProperty(name)
|
||||
?: throw GradleException("Missing '$name' in keystore.properties")
|
||||
|
||||
val configuredStoreFile = requiredSigningProperty("storeFile")
|
||||
storeFile = if (File(configuredStoreFile).isAbsolute) {
|
||||
file(configuredStoreFile)
|
||||
} else {
|
||||
rootProject.file(configuredStoreFile)
|
||||
}
|
||||
storePassword = requiredSigningProperty("storePassword")
|
||||
keyAlias = requiredSigningProperty("keyAlias")
|
||||
keyPassword = requiredSigningProperty("keyPassword")
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
@@ -24,7 +67,11 @@ android {
|
||||
isMinifyEnabled = false
|
||||
}
|
||||
release {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
isMinifyEnabled = false
|
||||
ndk {
|
||||
debugSymbolLevel = "SYMBOL_TABLE"
|
||||
}
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
@@ -45,6 +92,10 @@ android {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
lint {
|
||||
disable += "NullSafeMutableLiveData"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -57,6 +108,8 @@ dependencies {
|
||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
implementation(libs.androidx.room.runtime)
|
||||
implementation(libs.androidx.work.runtime.ktx)
|
||||
implementation(libs.camera.camera2)
|
||||
implementation(libs.camera.core)
|
||||
@@ -64,15 +117,21 @@ dependencies {
|
||||
implementation(libs.camera.view)
|
||||
implementation(libs.coil.compose)
|
||||
implementation(libs.compose.material.icons.extended)
|
||||
implementation("androidx.compose.material:material")
|
||||
implementation(libs.compose.material3)
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.ui.graphics)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
implementation(libs.coroutines.android)
|
||||
implementation(platform(libs.firebase.bom))
|
||||
implementation(libs.firebase.crashlytics)
|
||||
implementation(libs.firebase.messaging)
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.okhttp.logging)
|
||||
implementation(libs.play.services.auth)
|
||||
implementation(libs.play.services.auth.api.phone)
|
||||
implementation(libs.play.app.update)
|
||||
implementation(libs.play.app.update.ktx)
|
||||
implementation(libs.retrofit)
|
||||
implementation(libs.retrofit.gson)
|
||||
|
||||
@@ -80,4 +139,6 @@ dependencies {
|
||||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.coroutines.test)
|
||||
|
||||
ksp(libs.androidx.room.compiler)
|
||||
}
|
||||
|
||||
@@ -2,10 +2,29 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera"
|
||||
android:required="false" />
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.speech.RecognitionService" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:name=".DriverApplication"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.TppKierowca">
|
||||
<activity
|
||||
@@ -26,5 +45,18 @@
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
|
||||
<service
|
||||
android:name=".sync.DriverFirebaseMessagingService"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="com.google.firebase.MESSAGING_EVENT" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".tracking.ActiveRouteTrackingService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="location" />
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package pl.firmatpp.kierowca
|
||||
|
||||
import android.app.Application
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.firmatpp.kierowca.data.upload.OfflineOutboxManager
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
|
||||
class DriverApplication : Application() {
|
||||
private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
AppDiagnostics.installFirebaseCrashlytics()
|
||||
AppDiagnostics.log("app_started")
|
||||
applicationScope.launch {
|
||||
val outboxManager = OfflineOutboxManager(this@DriverApplication)
|
||||
runCatching { outboxManager.repairOperationalQueues() }
|
||||
.onFailure { AppDiagnostics.reportNonFatal(it, "repair_operational_queues") }
|
||||
runCatching { outboxManager.repairGpsQueue() }
|
||||
.onFailure { AppDiagnostics.reportNonFatal(it, "repair_gps_queue") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,19 +3,88 @@ package pl.firmatpp.kierowca
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import pl.firmatpp.kierowca.ui.DriverApp
|
||||
import pl.firmatpp.kierowca.ui.DriverViewModel
|
||||
import pl.firmatpp.kierowca.ui.theme.TppKierowcaTheme
|
||||
import pl.firmatpp.kierowca.update.PlayAppUpdateState
|
||||
import pl.firmatpp.kierowca.update.PlayInAppUpdateController
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
TppKierowcaTheme {
|
||||
val viewModel: DriverViewModel = viewModel()
|
||||
DriverApp(viewModel = viewModel)
|
||||
}
|
||||
private var notificationRouteId by mutableStateOf<String?>(null)
|
||||
private var notificationRouteTarget by mutableStateOf<String?>(null)
|
||||
private var notificationLeaveRequestId by mutableStateOf<String?>(null)
|
||||
private var playAppUpdateState by mutableStateOf(PlayAppUpdateState())
|
||||
private lateinit var playInAppUpdates: PlayInAppUpdateController
|
||||
private val appUpdateLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.StartIntentSenderForResult(),
|
||||
) { result ->
|
||||
if (::playInAppUpdates.isInitialized) {
|
||||
playInAppUpdates.onUpdateFlowResult(result.resultCode)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
notificationRouteId = intent.getStringExtra(EXTRA_ROUTE_ID)
|
||||
notificationRouteTarget = intent.getStringExtra(EXTRA_ROUTE_TARGET)
|
||||
notificationLeaveRequestId = intent.getStringExtra(EXTRA_LEAVE_REQUEST_ID)
|
||||
playInAppUpdates = PlayInAppUpdateController(
|
||||
activity = this,
|
||||
launcher = appUpdateLauncher,
|
||||
onStateChanged = { playAppUpdateState = it },
|
||||
)
|
||||
setContent {
|
||||
val viewModel: DriverViewModel = viewModel()
|
||||
val state by viewModel.state.collectAsStateWithLifecycle()
|
||||
|
||||
TppKierowcaTheme(themeMode = state.themeMode) {
|
||||
DriverApp(
|
||||
viewModel = viewModel,
|
||||
initialRouteId = notificationRouteId,
|
||||
initialRouteTarget = notificationRouteTarget,
|
||||
initialLeaveRequestId = notificationLeaveRequestId,
|
||||
playAppUpdateState = playAppUpdateState,
|
||||
onStartAppUpdate = playInAppUpdates::startUpdate,
|
||||
onCompleteAppUpdate = playInAppUpdates::completeDownloadedUpdate,
|
||||
)
|
||||
}
|
||||
}
|
||||
playInAppUpdates.checkForUpdate()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (::playInAppUpdates.isInitialized) {
|
||||
playInAppUpdates.checkForUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (::playInAppUpdates.isInitialized) {
|
||||
playInAppUpdates.dispose()
|
||||
}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: android.content.Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
notificationRouteId = intent.getStringExtra(EXTRA_ROUTE_ID)
|
||||
notificationRouteTarget = intent.getStringExtra(EXTRA_ROUTE_TARGET)
|
||||
notificationLeaveRequestId = intent.getStringExtra(EXTRA_LEAVE_REQUEST_ID)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_ROUTE_ID = "pl.firmatpp.kierowca.EXTRA_ROUTE_ID"
|
||||
const val EXTRA_ROUTE_TARGET = "pl.firmatpp.kierowca.EXTRA_ROUTE_TARGET"
|
||||
const val EXTRA_LEAVE_REQUEST_ID = "pl.firmatpp.kierowca.EXTRA_LEAVE_REQUEST_ID"
|
||||
const val ROUTE_TARGET_DETAIL = "detail"
|
||||
const val ROUTE_TARGET_FINISH = "finish"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import java.io.IOException
|
||||
import java.net.UnknownHostException
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import retrofit2.HttpException
|
||||
|
||||
enum class ApiErrorKind {
|
||||
Network,
|
||||
Auth,
|
||||
Forbidden,
|
||||
Validation,
|
||||
Conflict,
|
||||
RateLimited,
|
||||
Server,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
data class ApiError(
|
||||
val kind: ApiErrorKind,
|
||||
val message: String,
|
||||
val retryable: Boolean,
|
||||
val code: String? = null,
|
||||
val statusCode: Int? = null,
|
||||
val responseBody: String? = null,
|
||||
)
|
||||
|
||||
object ApiErrorMapper {
|
||||
fun map(throwable: Throwable): ApiError =
|
||||
when (throwable) {
|
||||
is UnknownHostException -> ApiError(
|
||||
kind = ApiErrorKind.Network,
|
||||
message = "Brak internetu lub połączenia z serwerem. Sprawdź zasięg i spróbuj ponownie.",
|
||||
retryable = true,
|
||||
)
|
||||
is IOException -> ApiError(
|
||||
kind = ApiErrorKind.Network,
|
||||
message = "Nie udało się połączyć z serwerem. Operacja nie została potwierdzona.",
|
||||
retryable = true,
|
||||
)
|
||||
is HttpException -> mapHttpException(throwable)
|
||||
else -> ApiError(
|
||||
kind = ApiErrorKind.Unknown,
|
||||
message = throwable.message ?: "Wystąpił błąd. Operacja nie została potwierdzona.",
|
||||
retryable = false,
|
||||
)
|
||||
}
|
||||
|
||||
fun shouldReportNonFatal(throwable: Throwable): Boolean =
|
||||
map(throwable).kind != ApiErrorKind.Network
|
||||
|
||||
fun mapHttpStatus(statusCode: Int, body: String?): ApiError {
|
||||
val code = body?.let {
|
||||
""""code"\s*:\s*"([^"]+)"""".toRegex().find(it)?.groupValues?.getOrNull(1)
|
||||
?: """"reason"\s*:\s*"([^"]+)"""".toRegex().find(it)?.groupValues?.getOrNull(1)
|
||||
}
|
||||
val message = body?.let { """"message"\s*:\s*"([^"]+)"""".toRegex().find(it)?.groupValues?.getOrNull(1) }
|
||||
val retryable = body?.let { """"retryable"\s*:\s*(true|false)""".toRegex().find(it)?.groupValues?.getOrNull(1)?.toBooleanStrictOrNull() }
|
||||
|
||||
return mapProblem(
|
||||
statusCode = statusCode,
|
||||
code = code,
|
||||
message = message,
|
||||
retryable = retryable,
|
||||
responseBody = body,
|
||||
)
|
||||
}
|
||||
|
||||
fun mapProblem(
|
||||
statusCode: Int,
|
||||
code: String?,
|
||||
message: String?,
|
||||
retryable: Boolean?,
|
||||
responseBody: String? = null,
|
||||
): ApiError {
|
||||
val kind = when (statusCode) {
|
||||
401 -> ApiErrorKind.Auth
|
||||
403 -> ApiErrorKind.Forbidden
|
||||
400, 422 -> ApiErrorKind.Validation
|
||||
409 -> ApiErrorKind.Conflict
|
||||
429 -> ApiErrorKind.RateLimited
|
||||
in 500..599 -> ApiErrorKind.Server
|
||||
else -> ApiErrorKind.Unknown
|
||||
}
|
||||
val defaultRetryable = statusCode == 429 || statusCode in 500..599
|
||||
val resolvedRetryable = retryable ?: defaultRetryable
|
||||
val resolvedMessage = when {
|
||||
code == "INVALID_OTP" -> "Kod jest nieprawidłowy lub wygasł. Użyj kodu z najnowszego SMS-a."
|
||||
kind == ApiErrorKind.RateLimited -> "Za dużo prób. Odczekaj chwilę i spróbuj ponownie."
|
||||
!message.isNullOrBlank() -> message
|
||||
else -> when (kind) {
|
||||
ApiErrorKind.Auth -> "Sesja wygasła. Zaloguj się ponownie."
|
||||
ApiErrorKind.Forbidden -> "Brak uprawnień do tej operacji."
|
||||
ApiErrorKind.Validation -> "Serwer odrzucił operację. Nie została zapisana."
|
||||
ApiErrorKind.Conflict -> "Operacja jest w konflikcie z aktualnym stanem danych."
|
||||
ApiErrorKind.RateLimited -> "Za dużo prób. Odczekaj chwilę i spróbuj ponownie."
|
||||
ApiErrorKind.Server -> "Serwer nie potwierdził operacji. Aplikacja spróbuje ponownie."
|
||||
ApiErrorKind.Network -> "Nie udało się połączyć z serwerem. Operacja nie została potwierdzona."
|
||||
ApiErrorKind.Unknown -> "Wystąpił błąd. Operacja nie została potwierdzona."
|
||||
}
|
||||
}
|
||||
|
||||
return ApiError(
|
||||
kind = kind,
|
||||
message = resolvedMessage,
|
||||
retryable = resolvedRetryable,
|
||||
code = code,
|
||||
statusCode = statusCode,
|
||||
responseBody = responseBody,
|
||||
)
|
||||
}
|
||||
|
||||
private fun mapHttpException(exception: HttpException): ApiError {
|
||||
val body = runCatching {
|
||||
val source = exception.response()?.errorBody()?.source() ?: return@runCatching null
|
||||
source.request(Long.MAX_VALUE)
|
||||
source.buffer.clone().readUtf8()
|
||||
}.getOrNull()
|
||||
return mapHttpStatus(exception.code(), body)
|
||||
}
|
||||
}
|
||||
|
||||
fun Throwable.rethrowIfCancellation() {
|
||||
if (this is CancellationException) throw this
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
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 pl.firmatpp.kierowca.ui.theme.AppThemeMode
|
||||
|
||||
private val Context.driverAppPreferencesDataStore by preferencesDataStore(name = "driver_app_preferences")
|
||||
|
||||
class AppPreferencesStore(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
constructor(context: Context) : this(context.driverAppPreferencesDataStore)
|
||||
|
||||
private val themeModeKey = stringPreferencesKey("theme_mode")
|
||||
private val routeProgressNotificationEnabledKey = booleanPreferencesKey("route_progress_notification_enabled")
|
||||
private val routeLocationEnabledKey = booleanPreferencesKey("route_location_enabled")
|
||||
|
||||
val themeMode: Flow<AppThemeMode> = dataStore.data
|
||||
.map { preferences -> AppThemeMode.fromStoredValue(preferences[themeModeKey]) }
|
||||
|
||||
val routeProgressNotificationEnabled: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[routeProgressNotificationEnabledKey] ?: true }
|
||||
|
||||
val routeLocationEnabled: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[routeLocationEnabledKey] ?: false }
|
||||
|
||||
suspend fun setThemeMode(themeMode: AppThemeMode) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[themeModeKey] = themeMode.storedValue
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setRouteProgressNotificationEnabled(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[routeProgressNotificationEnabledKey] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setRouteLocationEnabled(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[routeLocationEnabledKey] = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import pl.firmatpp.kierowca.BuildConfig
|
||||
import pl.firmatpp.kierowca.data.model.DriverDeviceInfo
|
||||
|
||||
class DeviceInfoProvider(
|
||||
private val context: Context,
|
||||
private val tokenStore: TokenStore,
|
||||
) {
|
||||
suspend fun currentDeviceInfo(): DriverDeviceInfo =
|
||||
DriverDeviceInfo(
|
||||
deviceId = tokenStore.deviceId(),
|
||||
androidId = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID),
|
||||
brand = Build.BRAND,
|
||||
manufacturer = Build.MANUFACTURER,
|
||||
model = Build.MODEL,
|
||||
device = Build.DEVICE,
|
||||
product = Build.PRODUCT,
|
||||
androidVersion = Build.VERSION.RELEASE,
|
||||
sdkInt = Build.VERSION.SDK_INT,
|
||||
appVersion = BuildConfig.VERSION_NAME,
|
||||
serialNumber = null,
|
||||
)
|
||||
}
|
||||
@@ -2,54 +2,214 @@ package pl.firmatpp.kierowca.data
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.util.UUID
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import pl.firmatpp.kierowca.data.api.ApiFactory
|
||||
import pl.firmatpp.kierowca.data.api.MobileDriverApi
|
||||
import pl.firmatpp.kierowca.data.model.BootstrapResponse
|
||||
import pl.firmatpp.kierowca.data.model.AcknowledgeTachographReminderBody
|
||||
import pl.firmatpp.kierowca.data.model.BroadcastAuthBody
|
||||
import pl.firmatpp.kierowca.data.model.BroadcastAuthResponse
|
||||
import pl.firmatpp.kierowca.data.model.CancelLeaveRequestBody
|
||||
import pl.firmatpp.kierowca.data.model.DispatchSheetUploadResponse
|
||||
import pl.firmatpp.kierowca.data.model.CreateLeaveRequestBody
|
||||
import pl.firmatpp.kierowca.data.model.DriverDto
|
||||
import pl.firmatpp.kierowca.data.model.DriverLeaveCalendarEntryDto
|
||||
import pl.firmatpp.kierowca.data.model.DriverLeaveRequestDto
|
||||
import pl.firmatpp.kierowca.data.model.FinishRouteBody
|
||||
import pl.firmatpp.kierowca.data.model.NotificationPreferencesBody
|
||||
import pl.firmatpp.kierowca.data.model.NotificationPreferencesDto
|
||||
import pl.firmatpp.kierowca.data.model.OtpResponse
|
||||
import pl.firmatpp.kierowca.data.model.PhotoUploadResponse
|
||||
import pl.firmatpp.kierowca.data.model.PushTokenBody
|
||||
import pl.firmatpp.kierowca.data.model.RealtimeStatusBody
|
||||
import pl.firmatpp.kierowca.data.model.RequestOtpBody
|
||||
import pl.firmatpp.kierowca.data.model.RoutePointBatchBody
|
||||
import pl.firmatpp.kierowca.data.model.RoutePointsResponse
|
||||
import pl.firmatpp.kierowca.data.model.RouteResponse
|
||||
import pl.firmatpp.kierowca.data.model.StartRouteBody
|
||||
import pl.firmatpp.kierowca.data.model.SyncStateResponse
|
||||
import pl.firmatpp.kierowca.data.model.TachographReminderDto
|
||||
import pl.firmatpp.kierowca.data.model.VerifyOtpBody
|
||||
import pl.firmatpp.kierowca.data.upload.DispatchSheetUploadEntity
|
||||
import pl.firmatpp.kierowca.data.upload.PhotoUploadEntity
|
||||
|
||||
class DriverRepository(
|
||||
private val context: Context,
|
||||
private val api: MobileDriverApi = ApiFactory.mobileDriverApi(),
|
||||
private val tokenStore: TokenStore = TokenStore(context),
|
||||
private val deviceInfoProvider: DeviceInfoProvider = DeviceInfoProvider(context, tokenStore),
|
||||
) {
|
||||
suspend fun requestOtp(phoneNumber: String): OtpResponse =
|
||||
api.requestOtp(RequestOtpBody(phoneNumber))
|
||||
|
||||
suspend fun verifyOtp(phoneNumber: String, code: String, deviceName: String): DriverDto {
|
||||
val response = api.verifyOtp(VerifyOtpBody(phoneNumber, code, deviceName))
|
||||
val response = api.verifyOtp(VerifyOtpBody(phoneNumber, code, deviceName, deviceInfoProvider.currentDeviceInfo()))
|
||||
val token = response.accessToken ?: error("Brak tokenu sesji.")
|
||||
tokenStore.save(token)
|
||||
return response.driver ?: error("Brak danych kierowcy.")
|
||||
}
|
||||
|
||||
suspend fun bootstrap(): BootstrapResponse =
|
||||
api.bootstrap(authHeader(requireToken()))
|
||||
suspend fun bootstrap(date: String? = null): BootstrapResponse =
|
||||
api.bootstrap(authHeader(requireToken()), date)
|
||||
|
||||
suspend fun acknowledgeTachographReminder(taskIds: List<String>): TachographReminderDto =
|
||||
api.acknowledgeTachographReminder(
|
||||
authHeader(requireToken()),
|
||||
AcknowledgeTachographReminderBody(taskIds),
|
||||
).tachographReminder
|
||||
|
||||
suspend fun route(routeId: String): RouteResponse =
|
||||
api.route(authHeader(requireToken()), routeId)
|
||||
|
||||
suspend fun uploadPhoto(routeId: String, uri: Uri, source: String): PhotoUploadResponse {
|
||||
suspend fun leaveRequests(): List<DriverLeaveRequestDto> =
|
||||
api.leaveRequests(authHeader(requireToken())).data
|
||||
|
||||
suspend fun leaveCalendar(from: String, to: String): List<DriverLeaveCalendarEntryDto> =
|
||||
api.leaveCalendar(authHeader(requireToken()), from, to).data
|
||||
|
||||
suspend fun leaveRequest(id: String): DriverLeaveRequestDto =
|
||||
api.leaveRequest(authHeader(requireToken()), id).data
|
||||
|
||||
suspend fun createLeaveRequest(dateFrom: String, dateTo: String, type: String, note: String?): DriverLeaveRequestDto =
|
||||
api.createLeaveRequest(authHeader(requireToken()), CreateLeaveRequestBody(dateFrom, dateTo, type, note)).data
|
||||
|
||||
suspend fun cancelLeaveRequest(id: String, expectedVersion: Long, comment: String? = null): DriverLeaveRequestDto =
|
||||
api.cancelLeaveRequest(authHeader(requireToken()), id, CancelLeaveRequestBody(comment, expectedVersion)).data
|
||||
|
||||
suspend fun completeRoute(routeId: String) =
|
||||
api.completeRoute(authHeader(requireToken()), routeId)
|
||||
|
||||
suspend fun startRoute(routeId: String, body: StartRouteBody) =
|
||||
api.startRoute(authHeader(requireToken()), routeId, body)
|
||||
|
||||
suspend fun finishRoute(routeId: String, body: FinishRouteBody) =
|
||||
api.finishRoute(authHeader(requireToken()), routeId, body)
|
||||
|
||||
suspend fun storeRoutePoints(routeId: String, body: RoutePointBatchBody): RoutePointsResponse =
|
||||
api.storeRoutePoints(authHeader(requireToken()), routeId, body)
|
||||
|
||||
suspend fun updateNotificationPreferences(notifyNewRoutes: Boolean): NotificationPreferencesDto =
|
||||
api.updateNotificationPreferences(authHeader(requireToken()), NotificationPreferencesBody(notifyNewRoutes))
|
||||
|
||||
suspend fun syncState(date: String?, routeId: String? = null): SyncStateResponse =
|
||||
api.syncState(authHeader(requireToken()), date, routeId)
|
||||
|
||||
suspend fun broadcastAuth(socketId: String, channelName: String): BroadcastAuthResponse =
|
||||
api.broadcastAuth(authHeader(requireToken()), BroadcastAuthBody(socketId, channelName))
|
||||
|
||||
suspend fun storePushToken(token: String) {
|
||||
api.storePushToken(authHeader(requireToken()), PushTokenBody(token))
|
||||
}
|
||||
|
||||
suspend fun storeRealtimeStatus(status: String, socketId: String? = null, error: String? = null) {
|
||||
api.storeRealtimeStatus(authHeader(requireToken()), RealtimeStatusBody(status, socketId, error))
|
||||
}
|
||||
|
||||
suspend fun deletePushToken() {
|
||||
val token = tokenStore.read() ?: return
|
||||
runCatching { api.deletePushToken(authHeader(token)) }
|
||||
}
|
||||
|
||||
suspend fun uploadPhoto(
|
||||
routeId: String,
|
||||
uri: Uri,
|
||||
source: String,
|
||||
stage: String = "other",
|
||||
metadata: PhotoUploadMetadata = PhotoUploadMetadata(),
|
||||
): PhotoUploadResponse {
|
||||
val resolver = context.contentResolver
|
||||
val mimeType = resolver.getType(uri) ?: "image/jpeg"
|
||||
val bytes = resolver.openInputStream(uri)?.use { it.readBytes() } ?: error("Nie mozna odczytac zdjecia.")
|
||||
val clientRequestId = UUID.randomUUID().toString()
|
||||
val contentSha256 = sha256(bytes)
|
||||
val body = bytes.toRequestBody(mimeType.toMediaTypeOrNull())
|
||||
val photo = MultipartBody.Part.createFormData("photo", "ladunek.jpg", body)
|
||||
val sourceBody = source.toRequestBody("text/plain".toMediaTypeOrNull())
|
||||
val metadataParts = metadata.toMultipartTextParts()
|
||||
|
||||
return api.uploadPhoto(authHeader(requireToken()), routeId, photo, sourceBody)
|
||||
return api.uploadPhoto(
|
||||
authHeader(requireToken()),
|
||||
clientRequestId,
|
||||
routeId,
|
||||
photo,
|
||||
clientRequestId.toPlainTextBody(),
|
||||
contentSha256.toPlainTextBody(),
|
||||
sourceBody,
|
||||
stage.toPlainTextBody(),
|
||||
metadataParts["takenAt"],
|
||||
metadataParts["latitude"],
|
||||
metadataParts["longitude"],
|
||||
metadataParts["locationAccuracyMeters"],
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun logout() {
|
||||
suspend fun uploadQueuedPhoto(upload: PhotoUploadEntity): PhotoUploadResponse {
|
||||
val file = File(upload.localPath)
|
||||
val body = file.readBytes().toRequestBody(upload.mimeType.toMediaTypeOrNull())
|
||||
val photo = MultipartBody.Part.createFormData("photo", file.name, body)
|
||||
val metadataParts = PhotoUploadMetadata(
|
||||
takenAt = upload.takenAt,
|
||||
latitude = upload.latitude,
|
||||
longitude = upload.longitude,
|
||||
locationAccuracyMeters = upload.locationAccuracyMeters,
|
||||
).toMultipartTextParts()
|
||||
|
||||
return api.uploadPhoto(
|
||||
authHeader(requireToken()),
|
||||
upload.clientRequestId,
|
||||
upload.routeId,
|
||||
photo,
|
||||
upload.clientRequestId.toPlainTextBody(),
|
||||
upload.contentSha256.toPlainTextBody(),
|
||||
upload.source.toPlainTextBody(),
|
||||
upload.stage.toPlainTextBody(),
|
||||
metadataParts["takenAt"],
|
||||
metadataParts["latitude"],
|
||||
metadataParts["longitude"],
|
||||
metadataParts["locationAccuracyMeters"],
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun uploadQueuedDispatchSheetPhoto(upload: DispatchSheetUploadEntity): DispatchSheetUploadResponse {
|
||||
val file = File(upload.localPath)
|
||||
val body = file.readBytes().toRequestBody(upload.mimeType.toMediaTypeOrNull())
|
||||
val photo = MultipartBody.Part.createFormData("photo", file.name, body)
|
||||
val metadataParts = PhotoUploadMetadata(
|
||||
takenAt = upload.takenAt,
|
||||
latitude = upload.latitude,
|
||||
longitude = upload.longitude,
|
||||
locationAccuracyMeters = upload.locationAccuracyMeters,
|
||||
).toMultipartTextParts()
|
||||
|
||||
return api.uploadDispatchSheetPhoto(
|
||||
authHeader(requireToken()),
|
||||
upload.clientRequestId,
|
||||
photo,
|
||||
upload.clientRequestId.toPlainTextBody(),
|
||||
upload.contentSha256.toPlainTextBody(),
|
||||
upload.source.toPlainTextBody(),
|
||||
metadataParts["takenAt"],
|
||||
metadataParts["latitude"],
|
||||
metadataParts["longitude"],
|
||||
metadataParts["locationAccuracyMeters"],
|
||||
upload.replacePhotoId?.toPlainTextBody(),
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun deletePhoto(photoId: String) {
|
||||
api.deletePhoto(authHeader(requireToken()), photoId)
|
||||
}
|
||||
|
||||
suspend fun logout(notifyServer: Boolean = true) {
|
||||
val token = tokenStore.read()
|
||||
if (token != null) {
|
||||
if (token != null && notifyServer) {
|
||||
runCatching { api.deletePushToken(authHeader(token)) }
|
||||
runCatching { api.logout(authHeader(token)) }
|
||||
}
|
||||
tokenStore.clear()
|
||||
@@ -62,4 +222,11 @@ class DriverRepository(
|
||||
private suspend fun requireToken(): String = tokenStore.read() ?: error("Brak aktywnej sesji.")
|
||||
|
||||
private fun authHeader(token: String): String = "Bearer $token"
|
||||
|
||||
private fun String.toPlainTextBody(): RequestBody = toRequestBody("text/plain".toMediaTypeOrNull())
|
||||
|
||||
private fun sha256(bytes: ByteArray): String =
|
||||
MessageDigest.getInstance("SHA-256")
|
||||
.digest(bytes)
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
|
||||
data class PhotoUploadMetadata(
|
||||
val takenAt: String? = null,
|
||||
val latitude: Double? = null,
|
||||
val longitude: Double? = null,
|
||||
val locationAccuracyMeters: Double? = null,
|
||||
)
|
||||
|
||||
fun PhotoUploadMetadata.toMultipartTextParts(): Map<String, RequestBody> = buildMap {
|
||||
takenAt?.let { put("takenAt", it.toPlainTextBody()) }
|
||||
latitude?.let { put("latitude", it.toString().toPlainTextBody()) }
|
||||
longitude?.let { put("longitude", it.toString().toPlainTextBody()) }
|
||||
locationAccuracyMeters?.let { put("locationAccuracyMeters", it.toString().toPlainTextBody()) }
|
||||
}
|
||||
|
||||
private fun String.toPlainTextBody(): RequestBody = toRequestBody("text/plain".toMediaTypeOrNull())
|
||||
@@ -6,11 +6,13 @@ import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import java.util.UUID
|
||||
|
||||
private val Context.driverDataStore by preferencesDataStore(name = "driver_session")
|
||||
|
||||
class TokenStore(private val context: Context) {
|
||||
private val tokenKey = stringPreferencesKey("access_token")
|
||||
private val deviceIdKey = stringPreferencesKey("device_id")
|
||||
|
||||
suspend fun save(token: String) {
|
||||
context.driverDataStore.edit { preferences ->
|
||||
@@ -22,6 +24,21 @@ class TokenStore(private val context: Context) {
|
||||
.map { it[tokenKey] }
|
||||
.first()
|
||||
|
||||
suspend fun deviceId(): String {
|
||||
val existing = context.driverDataStore.data
|
||||
.map { it[deviceIdKey] }
|
||||
.first()
|
||||
|
||||
if (!existing.isNullOrBlank()) return existing
|
||||
|
||||
val generated = UUID.randomUUID().toString()
|
||||
context.driverDataStore.edit { preferences ->
|
||||
preferences[deviceIdKey] = generated
|
||||
}
|
||||
|
||||
return generated
|
||||
}
|
||||
|
||||
suspend fun clear() {
|
||||
context.driverDataStore.edit { it.remove(tokenKey) }
|
||||
}
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
package pl.firmatpp.kierowca.data.api
|
||||
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import pl.firmatpp.kierowca.BuildConfig
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.gson.GsonConverterFactory
|
||||
|
||||
internal const val DRIVER_APP_VERSION_HEADER = "X-Driver-App-Version"
|
||||
|
||||
internal fun Request.withDriverAppVersion(appVersion: String): Request =
|
||||
newBuilder()
|
||||
.header(DRIVER_APP_VERSION_HEADER, appVersion)
|
||||
.build()
|
||||
|
||||
object ApiFactory {
|
||||
fun mobileDriverApi(): MobileDriverApi {
|
||||
val logging = HttpLoggingInterceptor().apply {
|
||||
@@ -13,6 +21,9 @@ object ApiFactory {
|
||||
}
|
||||
|
||||
val client = OkHttpClient.Builder()
|
||||
.addInterceptor { chain ->
|
||||
chain.proceed(chain.request().withDriverAppVersion(BuildConfig.VERSION_NAME))
|
||||
}
|
||||
.addInterceptor(logging)
|
||||
.build()
|
||||
|
||||
|
||||
@@ -3,19 +3,44 @@ package pl.firmatpp.kierowca.data.api
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import pl.firmatpp.kierowca.data.model.BootstrapResponse
|
||||
import pl.firmatpp.kierowca.data.model.AcknowledgeTachographReminderBody
|
||||
import pl.firmatpp.kierowca.data.model.AcknowledgeTachographReminderResponse
|
||||
import pl.firmatpp.kierowca.data.model.BroadcastAuthBody
|
||||
import pl.firmatpp.kierowca.data.model.BroadcastAuthResponse
|
||||
import pl.firmatpp.kierowca.data.model.CancelLeaveRequestBody
|
||||
import pl.firmatpp.kierowca.data.model.CompleteRouteResponse
|
||||
import pl.firmatpp.kierowca.data.model.CreateLeaveRequestBody
|
||||
import pl.firmatpp.kierowca.data.model.DispatchSheetUploadResponse
|
||||
import pl.firmatpp.kierowca.data.model.FinishRouteBody
|
||||
import pl.firmatpp.kierowca.data.model.LeaveCalendarResponse
|
||||
import pl.firmatpp.kierowca.data.model.LeaveRequestListResponse
|
||||
import pl.firmatpp.kierowca.data.model.LeaveRequestResponse
|
||||
import pl.firmatpp.kierowca.data.model.LeaveRequestTypesResponse
|
||||
import pl.firmatpp.kierowca.data.model.OtpResponse
|
||||
import pl.firmatpp.kierowca.data.model.NotificationPreferencesBody
|
||||
import pl.firmatpp.kierowca.data.model.NotificationPreferencesDto
|
||||
import pl.firmatpp.kierowca.data.model.PhotoUploadResponse
|
||||
import pl.firmatpp.kierowca.data.model.PushTokenBody
|
||||
import pl.firmatpp.kierowca.data.model.RealtimeStatusBody
|
||||
import pl.firmatpp.kierowca.data.model.RequestOtpBody
|
||||
import pl.firmatpp.kierowca.data.model.RouteActionResponse
|
||||
import pl.firmatpp.kierowca.data.model.RoutePointBatchBody
|
||||
import pl.firmatpp.kierowca.data.model.RoutePointsResponse
|
||||
import pl.firmatpp.kierowca.data.model.RouteResponse
|
||||
import pl.firmatpp.kierowca.data.model.StartRouteBody
|
||||
import pl.firmatpp.kierowca.data.model.SyncStateResponse
|
||||
import pl.firmatpp.kierowca.data.model.VerifyOtpBody
|
||||
import pl.firmatpp.kierowca.data.model.VerifyOtpResponse
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.DELETE
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Header
|
||||
import retrofit2.http.Multipart
|
||||
import retrofit2.http.POST
|
||||
import retrofit2.http.PUT
|
||||
import retrofit2.http.Part
|
||||
import retrofit2.http.Path
|
||||
import retrofit2.http.Query
|
||||
|
||||
interface MobileDriverApi {
|
||||
@POST("mobile/driver/auth/request-otp")
|
||||
@@ -27,8 +52,64 @@ interface MobileDriverApi {
|
||||
@POST("mobile/driver/auth/logout")
|
||||
suspend fun logout(@Header("Authorization") authorization: String): Map<String, Boolean>
|
||||
|
||||
@GET("mobile/driver/notification-preferences")
|
||||
suspend fun notificationPreferences(
|
||||
@Header("Authorization") authorization: String,
|
||||
): NotificationPreferencesDto
|
||||
|
||||
@PUT("mobile/driver/notification-preferences")
|
||||
suspend fun updateNotificationPreferences(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Body body: NotificationPreferencesBody,
|
||||
): NotificationPreferencesDto
|
||||
|
||||
@GET("mobile/driver/bootstrap")
|
||||
suspend fun bootstrap(@Header("Authorization") authorization: String): BootstrapResponse
|
||||
suspend fun bootstrap(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Query("date") date: String?,
|
||||
): BootstrapResponse
|
||||
|
||||
@POST("mobile/driver/tachograph-reminder/acknowledge")
|
||||
suspend fun acknowledgeTachographReminder(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Body body: AcknowledgeTachographReminderBody,
|
||||
): AcknowledgeTachographReminderResponse
|
||||
|
||||
@GET("mobile/driver/leave-request-types")
|
||||
suspend fun leaveRequestTypes(
|
||||
@Header("Authorization") authorization: String,
|
||||
): LeaveRequestTypesResponse
|
||||
|
||||
@GET("mobile/driver/leave-requests")
|
||||
suspend fun leaveRequests(
|
||||
@Header("Authorization") authorization: String,
|
||||
): LeaveRequestListResponse
|
||||
|
||||
@GET("mobile/driver/leave-requests/calendar")
|
||||
suspend fun leaveCalendar(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Query("from") from: String,
|
||||
@Query("to") to: String,
|
||||
): LeaveCalendarResponse
|
||||
|
||||
@POST("mobile/driver/leave-requests")
|
||||
suspend fun createLeaveRequest(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Body body: CreateLeaveRequestBody,
|
||||
): LeaveRequestResponse
|
||||
|
||||
@GET("mobile/driver/leave-requests/{id}")
|
||||
suspend fun leaveRequest(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("id") id: String,
|
||||
): LeaveRequestResponse
|
||||
|
||||
@POST("mobile/driver/leave-requests/{id}/cancel")
|
||||
suspend fun cancelLeaveRequest(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("id") id: String,
|
||||
@Body body: CancelLeaveRequestBody,
|
||||
): LeaveRequestResponse
|
||||
|
||||
@GET("mobile/driver/routes/{routeId}")
|
||||
suspend fun route(
|
||||
@@ -36,12 +117,99 @@ interface MobileDriverApi {
|
||||
@Path("routeId") routeId: String,
|
||||
): RouteResponse
|
||||
|
||||
@POST("mobile/driver/routes/{routeId}/complete")
|
||||
suspend fun completeRoute(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("routeId") routeId: String,
|
||||
): CompleteRouteResponse
|
||||
|
||||
@POST("mobile/driver/routes/{routeId}/start")
|
||||
suspend fun startRoute(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("routeId") routeId: String,
|
||||
@Body body: StartRouteBody,
|
||||
): RouteActionResponse
|
||||
|
||||
@POST("mobile/driver/routes/{routeId}/finish")
|
||||
suspend fun finishRoute(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("routeId") routeId: String,
|
||||
@Body body: FinishRouteBody,
|
||||
): RouteActionResponse
|
||||
|
||||
@POST("mobile/driver/routes/{routeId}/points")
|
||||
suspend fun storeRoutePoints(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("routeId") routeId: String,
|
||||
@Body body: RoutePointBatchBody,
|
||||
): RoutePointsResponse
|
||||
|
||||
@GET("mobile/driver/sync-state")
|
||||
suspend fun syncState(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Query("date") date: String?,
|
||||
@Query("routeId") routeId: String?,
|
||||
): SyncStateResponse
|
||||
|
||||
@POST("mobile/driver/broadcasting/auth")
|
||||
suspend fun broadcastAuth(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Body body: BroadcastAuthBody,
|
||||
): BroadcastAuthResponse
|
||||
|
||||
@PUT("mobile/driver/push-token")
|
||||
suspend fun storePushToken(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Body body: PushTokenBody,
|
||||
): Map<String, Boolean>
|
||||
|
||||
@PUT("mobile/driver/realtime-status")
|
||||
suspend fun storeRealtimeStatus(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Body body: RealtimeStatusBody,
|
||||
): Map<String, Boolean>
|
||||
|
||||
@DELETE("mobile/driver/push-token")
|
||||
suspend fun deletePushToken(
|
||||
@Header("Authorization") authorization: String,
|
||||
): Map<String, Boolean>
|
||||
|
||||
@Multipart
|
||||
@POST("mobile/driver/routes/{routeId}/photos")
|
||||
suspend fun uploadPhoto(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Header("Idempotency-Key") idempotencyKey: String,
|
||||
@Path("routeId") routeId: String,
|
||||
@Part photo: MultipartBody.Part,
|
||||
@Part("clientRequestId") clientRequestId: RequestBody,
|
||||
@Part("contentSha256") contentSha256: RequestBody,
|
||||
@Part("source") source: RequestBody,
|
||||
@Part("stage") stage: RequestBody?,
|
||||
@Part("takenAt") takenAt: RequestBody?,
|
||||
@Part("latitude") latitude: RequestBody?,
|
||||
@Part("longitude") longitude: RequestBody?,
|
||||
@Part("locationAccuracyMeters") locationAccuracyMeters: RequestBody?,
|
||||
): PhotoUploadResponse
|
||||
|
||||
@Multipart
|
||||
@POST("mobile/driver/dispatch-sheet-photos")
|
||||
suspend fun uploadDispatchSheetPhoto(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Header("Idempotency-Key") idempotencyKey: String,
|
||||
@Part photo: MultipartBody.Part,
|
||||
@Part("clientRequestId") clientRequestId: RequestBody,
|
||||
@Part("contentSha256") contentSha256: RequestBody,
|
||||
@Part("source") source: RequestBody,
|
||||
@Part("takenAt") takenAt: RequestBody?,
|
||||
@Part("latitude") latitude: RequestBody?,
|
||||
@Part("longitude") longitude: RequestBody?,
|
||||
@Part("locationAccuracyMeters") locationAccuracyMeters: RequestBody?,
|
||||
@Part("replacePhotoId") replacePhotoId: RequestBody?,
|
||||
): DispatchSheetUploadResponse
|
||||
|
||||
@DELETE("mobile/driver/photos/{photoId}")
|
||||
suspend fun deletePhoto(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("photoId") photoId: String,
|
||||
): Map<String, Boolean>
|
||||
}
|
||||
|
||||
@@ -6,6 +6,21 @@ data class VerifyOtpBody(
|
||||
val phoneNumber: String,
|
||||
val code: String,
|
||||
val deviceName: String,
|
||||
val device: DriverDeviceInfo,
|
||||
)
|
||||
|
||||
data class DriverDeviceInfo(
|
||||
val deviceId: String,
|
||||
val androidId: String?,
|
||||
val brand: String?,
|
||||
val manufacturer: String?,
|
||||
val model: String?,
|
||||
val device: String?,
|
||||
val product: String?,
|
||||
val androidVersion: String?,
|
||||
val sdkInt: Int,
|
||||
val appVersion: String?,
|
||||
val serialNumber: String?,
|
||||
)
|
||||
|
||||
data class OtpResponse(
|
||||
@@ -30,6 +45,100 @@ data class DriverDto(
|
||||
data class BootstrapResponse(
|
||||
val session: DriverSessionDto,
|
||||
val routes: RoutesBucketDto,
|
||||
val driverAppSettings: DriverAppSettingsDto?,
|
||||
val dispatchSheetReminder: DispatchSheetReminderDto? = null,
|
||||
val tachographReminder: TachographReminderDto? = null,
|
||||
val notificationPreferences: NotificationPreferencesDto? = null,
|
||||
val realtime: RealtimeConfigDto? = null,
|
||||
val syncState: SyncStateResponse? = null,
|
||||
val appUpdate: AppUpdateDto? = null,
|
||||
)
|
||||
|
||||
data class AppUpdateDto(
|
||||
val latestVersionCode: Int? = null,
|
||||
val latestVersionName: String? = null,
|
||||
val minimumSupportedVersionCode: Int = 0,
|
||||
val playStoreUrl: String? = null,
|
||||
val track: String? = null,
|
||||
val checkedAt: String? = null,
|
||||
)
|
||||
|
||||
data class DriverAppSettingsDto(
|
||||
val minDate: String,
|
||||
val maxDate: String,
|
||||
val today: String,
|
||||
val selectedDate: String,
|
||||
val maxPastDays: Int,
|
||||
val autoRefreshSeconds: Int,
|
||||
val allowGalleryUploads: Boolean?,
|
||||
val allowRouteCompletion: Boolean?,
|
||||
val requirePreciseLocationForPhotos: Boolean?,
|
||||
val routeLocationMode: String? = null,
|
||||
val loadingPhotoRequirement: String? = null,
|
||||
val loadingWeightRequirement: String? = null,
|
||||
val unloadingPhotoRequirement: String? = null,
|
||||
val unloadingWeightRequirement: String? = null,
|
||||
val dispatchSheetRemindersEnabled: Boolean? = null,
|
||||
val dispatchSheetOnFridays: Boolean? = null,
|
||||
val dispatchSheetOnLastWorkingDay: Boolean? = null,
|
||||
val tachographRemindersEnabled: Boolean? = null,
|
||||
val leaveRequests: LeaveRequestsConfigDto? = null,
|
||||
)
|
||||
|
||||
data class LeaveRequestsConfigDto(
|
||||
val enabled: Boolean = false,
|
||||
val types: List<String> = listOf("URLOP"),
|
||||
)
|
||||
|
||||
data class DispatchSheetReminderDto(
|
||||
val enabled: Boolean = false,
|
||||
val dueToday: Boolean = false,
|
||||
val workDate: String? = null,
|
||||
val reason: String? = null,
|
||||
val availableUntil: String? = null,
|
||||
val status: String = "not_required",
|
||||
val photo: DispatchSheetPhotoDto? = null,
|
||||
val canUpload: Boolean = false,
|
||||
)
|
||||
|
||||
data class TachographReminderDto(
|
||||
val enabled: Boolean = false,
|
||||
val visible: Boolean = false,
|
||||
val title: String? = null,
|
||||
val message: String? = null,
|
||||
val confirmationLabel: String? = null,
|
||||
val tasks: List<TachographReminderTaskDto>? = null,
|
||||
)
|
||||
|
||||
data class TachographReminderTaskDto(
|
||||
val id: String,
|
||||
val type: String,
|
||||
val label: String,
|
||||
)
|
||||
|
||||
data class AcknowledgeTachographReminderBody(
|
||||
val taskIds: List<String>,
|
||||
)
|
||||
|
||||
data class AcknowledgeTachographReminderResponse(
|
||||
val ok: Boolean,
|
||||
val tachographReminder: TachographReminderDto,
|
||||
)
|
||||
|
||||
data class DispatchSheetPhotoDto(
|
||||
val id: String,
|
||||
val driverId: String,
|
||||
val workDate: String?,
|
||||
val clientRequestId: String? = null,
|
||||
val contentSha256: String? = null,
|
||||
val source: String,
|
||||
val mimeType: String?,
|
||||
val size: Long,
|
||||
val takenAt: String?,
|
||||
val latitude: Double?,
|
||||
val longitude: Double?,
|
||||
val locationAccuracyMeters: Double?,
|
||||
val createdAt: String?,
|
||||
)
|
||||
|
||||
data class DriverSessionDto(
|
||||
@@ -37,16 +146,154 @@ data class DriverSessionDto(
|
||||
val lastSyncAt: String,
|
||||
)
|
||||
|
||||
data class NotificationPreferencesDto(
|
||||
val notifyNewRoutes: Boolean = false,
|
||||
)
|
||||
|
||||
data class RealtimeConfigDto(
|
||||
val reverbEnabled: Boolean = false,
|
||||
val reverbAppKey: String? = null,
|
||||
val reverbWsBaseUrl: String? = null,
|
||||
val reverbOrigin: String? = null,
|
||||
)
|
||||
|
||||
data class RoutesBucketDto(
|
||||
val today: List<DriverRouteDto> = emptyList(),
|
||||
)
|
||||
|
||||
data class RouteResponse(
|
||||
val route: DriverRouteDto,
|
||||
val syncState: SyncStateResponse? = null,
|
||||
)
|
||||
|
||||
data class CompleteRouteResponse(
|
||||
val ok: Boolean,
|
||||
val alreadyCompleted: Boolean,
|
||||
val message: String?,
|
||||
val completedAt: String?,
|
||||
val route: DriverRouteDto,
|
||||
)
|
||||
|
||||
data class SyncStateResponse(
|
||||
val scopes: List<SyncScopeDto> = emptyList(),
|
||||
)
|
||||
|
||||
data class SyncScopeDto(
|
||||
val scope: String,
|
||||
val date: String? = null,
|
||||
val routeId: String? = null,
|
||||
val version: Long,
|
||||
val checksum: String,
|
||||
val computedAt: String,
|
||||
)
|
||||
|
||||
data class BroadcastAuthBody(
|
||||
val socket_id: String,
|
||||
val channel_name: String,
|
||||
)
|
||||
|
||||
data class BroadcastAuthResponse(
|
||||
val auth: String,
|
||||
)
|
||||
|
||||
data class PushTokenBody(
|
||||
val token: String,
|
||||
val platform: String = "android",
|
||||
)
|
||||
|
||||
data class NotificationPreferencesBody(
|
||||
val notifyNewRoutes: Boolean,
|
||||
)
|
||||
|
||||
data class LeaveRequestListResponse(
|
||||
val data: List<DriverLeaveRequestDto> = emptyList(),
|
||||
)
|
||||
|
||||
data class LeaveCalendarResponse(
|
||||
val data: List<DriverLeaveCalendarEntryDto> = emptyList(),
|
||||
)
|
||||
|
||||
data class LeaveRequestResponse(
|
||||
val data: DriverLeaveRequestDto,
|
||||
)
|
||||
|
||||
data class LeaveRequestTypesResponse(
|
||||
val data: List<LeaveRequestTypeDto> = emptyList(),
|
||||
)
|
||||
|
||||
data class LeaveRequestTypeDto(
|
||||
val value: String,
|
||||
val label: String,
|
||||
)
|
||||
|
||||
data class CreateLeaveRequestBody(
|
||||
val dateFrom: String,
|
||||
val dateTo: String,
|
||||
val type: String,
|
||||
val note: String?,
|
||||
)
|
||||
|
||||
data class CancelLeaveRequestBody(
|
||||
val comment: String? = null,
|
||||
val expectedVersion: Long? = null,
|
||||
)
|
||||
|
||||
data class DriverLeaveRequestDto(
|
||||
val id: String,
|
||||
val driver: DriverDto? = null,
|
||||
val dateFrom: String?,
|
||||
val dateTo: String?,
|
||||
val type: String,
|
||||
val typeLabel: String? = null,
|
||||
val note: String? = null,
|
||||
val status: String,
|
||||
val version: Long = 1,
|
||||
val updatedAt: String? = null,
|
||||
val allowedDecisions: List<String> = emptyList(),
|
||||
val canCancel: Boolean = false,
|
||||
val submittedAt: String? = null,
|
||||
val decidedAt: String? = null,
|
||||
val decisionComment: String? = null,
|
||||
val events: List<DriverLeaveRequestEventDto> = emptyList(),
|
||||
)
|
||||
|
||||
data class DriverLeaveCalendarEntryDto(
|
||||
val id: String,
|
||||
val dateFrom: String?,
|
||||
val dateTo: String?,
|
||||
val type: String,
|
||||
val typeLabel: String? = null,
|
||||
val status: String,
|
||||
val driver: DriverLeaveCalendarDriverDto,
|
||||
)
|
||||
|
||||
data class DriverLeaveCalendarDriverDto(
|
||||
val id: String,
|
||||
val displayName: String?,
|
||||
val phoneNumber: String?,
|
||||
)
|
||||
|
||||
data class DriverLeaveRequestEventDto(
|
||||
val id: String,
|
||||
val action: String,
|
||||
val fromStatus: String? = null,
|
||||
val toStatus: String? = null,
|
||||
val comment: String? = null,
|
||||
val createdAt: String? = null,
|
||||
)
|
||||
|
||||
data class RealtimeStatusBody(
|
||||
val reverbStatus: String,
|
||||
val socketId: String? = null,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
data class DriverRouteDto(
|
||||
val id: String,
|
||||
val routeDate: String? = null,
|
||||
val unloadingDate: String? = null,
|
||||
val ordering: Int? = null,
|
||||
val dayOrderings: Map<String, Int>? = emptyMap(),
|
||||
val startsAt: String,
|
||||
val originName: String,
|
||||
val destinationName: String,
|
||||
@@ -55,28 +302,140 @@ data class DriverRouteDto(
|
||||
val contractCode: String?,
|
||||
val relationLabel: String,
|
||||
val status: String,
|
||||
val driverStatus: String? = null,
|
||||
val operationalStatus: String? = null,
|
||||
val loadingWeight: Double? = null,
|
||||
val loadingNotes: String? = null,
|
||||
val unloadingWeight: Double? = null,
|
||||
val unloadingNotes: String? = null,
|
||||
val trackingStatus: String? = null,
|
||||
val arrivedAt: String? = null,
|
||||
val distanceKm: Double?,
|
||||
val notes: String?,
|
||||
val truck: TruckDto?,
|
||||
val completedAt: String? = null,
|
||||
val operationalCompletedAt: String? = null,
|
||||
val completedByDriver: DriverDto? = null,
|
||||
val originNavigation: NavigationPointDto? = null,
|
||||
val destinationNavigation: NavigationPointDto? = null,
|
||||
val photos: List<RoutePhotoDto> = emptyList(),
|
||||
val photosByStage: RoutePhotosByStageDto? = null,
|
||||
)
|
||||
|
||||
fun DriverRouteDto.driverLifecycleStatus(): String =
|
||||
driverStatus?.takeIf { it in setOf("ZAPLANOWANA", "W TRAKCIE", "ZAKOŃCZONA") } ?: status
|
||||
|
||||
data class RoutePhotosByStageDto(
|
||||
val loading: List<RoutePhotoDto> = emptyList(),
|
||||
val unloading: List<RoutePhotoDto> = emptyList(),
|
||||
val other: List<RoutePhotoDto> = emptyList(),
|
||||
)
|
||||
|
||||
data class TruckDto(
|
||||
val id: String,
|
||||
val registration: String?,
|
||||
val trailerRegistration: String? = null,
|
||||
val name: String?,
|
||||
)
|
||||
|
||||
data class NavigationPointDto(
|
||||
val id: String,
|
||||
val label: String?,
|
||||
val latitude: Double?,
|
||||
val longitude: Double?,
|
||||
)
|
||||
|
||||
data class RoutePhotoDto(
|
||||
val id: String,
|
||||
val routeId: String,
|
||||
val clientRequestId: String? = null,
|
||||
val contentSha256: String? = null,
|
||||
val source: String,
|
||||
val stage: String = "other",
|
||||
val mimeType: String?,
|
||||
val size: Long,
|
||||
val url: String,
|
||||
val takenAt: String?,
|
||||
val latitude: Double?,
|
||||
val longitude: Double?,
|
||||
val locationAccuracyMeters: Double?,
|
||||
val createdAt: String?,
|
||||
val canDelete: Boolean = false,
|
||||
val deleteUntil: String? = null,
|
||||
)
|
||||
|
||||
data class PhotoUploadResponse(
|
||||
val photo: RoutePhotoDto,
|
||||
val receipt: PhotoUploadReceiptDto,
|
||||
)
|
||||
|
||||
data class PhotoUploadReceiptDto(
|
||||
val clientRequestId: String,
|
||||
val serverPhotoId: String,
|
||||
val contentSha256: String,
|
||||
val storedAt: String?,
|
||||
)
|
||||
|
||||
data class StartRouteBody(
|
||||
val clientActionId: String,
|
||||
val loadingWeight: Double?,
|
||||
val occurredAt: String,
|
||||
val photoClientRequestIds: List<String>,
|
||||
val loadingNotes: String? = null,
|
||||
)
|
||||
|
||||
data class FinishRouteBody(
|
||||
val clientActionId: String,
|
||||
val unloadingWeight: Double?,
|
||||
val occurredAt: String,
|
||||
val photoClientRequestIds: List<String>,
|
||||
val unloadingNotes: String? = null,
|
||||
)
|
||||
|
||||
data class RouteActionResponse(
|
||||
val ok: Boolean,
|
||||
val alreadyProcessed: Boolean,
|
||||
val route: DriverRouteDto,
|
||||
)
|
||||
|
||||
data class RoutePointBatchBody(
|
||||
val clientBatchId: String,
|
||||
val points: List<RoutePointDto>,
|
||||
)
|
||||
|
||||
data class RoutePointDto(
|
||||
val clientPointId: String,
|
||||
val trip_id: String,
|
||||
val driver_id: String,
|
||||
val lat: Double,
|
||||
val lon: Double,
|
||||
val accuracy: Double,
|
||||
val speed: Double?,
|
||||
val bearing: Double?,
|
||||
val timestamp: Long,
|
||||
val battery: Int?,
|
||||
val charging: Boolean,
|
||||
)
|
||||
|
||||
data class RoutePointsResponse(
|
||||
val ok: Boolean,
|
||||
val stored: Int,
|
||||
val progress: Double?,
|
||||
val remainingDistanceMeters: Int?,
|
||||
val arrived: Boolean,
|
||||
val offRoute: Boolean,
|
||||
val routeVersion: Long?,
|
||||
)
|
||||
|
||||
data class DispatchSheetUploadResponse(
|
||||
val photo: DispatchSheetPhotoDto,
|
||||
val reminder: DispatchSheetReminderDto,
|
||||
val receipt: DispatchSheetUploadReceiptDto,
|
||||
)
|
||||
|
||||
data class DispatchSheetUploadReceiptDto(
|
||||
val clientRequestId: String,
|
||||
val serverPhotoId: String,
|
||||
val contentSha256: String,
|
||||
val storedAt: String?,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package pl.firmatpp.kierowca.data.sync
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
|
||||
@Dao
|
||||
interface DriverCacheDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertBootstrap(cache: DriverBootstrapCacheEntity)
|
||||
|
||||
@Query("SELECT * FROM driver_bootstrap_cache WHERE date = :date LIMIT 1")
|
||||
suspend fun bootstrap(date: String): DriverBootstrapCacheEntity?
|
||||
|
||||
@Query("SELECT * FROM driver_bootstrap_cache ORDER BY syncedAtEpochMillis DESC")
|
||||
suspend fun allBootstrapCaches(): List<DriverBootstrapCacheEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertRoute(cache: DriverRouteCacheEntity)
|
||||
|
||||
@Query("SELECT * FROM driver_route_cache WHERE routeId = :routeId LIMIT 1")
|
||||
suspend fun route(routeId: String): DriverRouteCacheEntity?
|
||||
|
||||
@Query("SELECT * FROM driver_route_cache ORDER BY syncedAtEpochMillis DESC")
|
||||
suspend fun allRouteCaches(): List<DriverRouteCacheEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertSyncState(state: DriverSyncStateEntity)
|
||||
|
||||
@Query("SELECT * FROM driver_sync_states WHERE scope = :scope AND ifnull(date, '-') = ifnull(:date, '-') AND ifnull(routeId, '-') = ifnull(:routeId, '-') LIMIT 1")
|
||||
suspend fun syncState(scope: String, date: String?, routeId: String?): DriverSyncStateEntity?
|
||||
|
||||
@Query("SELECT * FROM driver_sync_states ORDER BY syncedAtEpochMillis DESC")
|
||||
suspend fun allSyncStates(): List<DriverSyncStateEntity>
|
||||
|
||||
@Query("DELETE FROM driver_bootstrap_cache")
|
||||
suspend fun clearBootstrap()
|
||||
|
||||
@Query("DELETE FROM driver_route_cache")
|
||||
suspend fun clearRoutes()
|
||||
|
||||
@Query("DELETE FROM driver_sync_states")
|
||||
suspend fun clearSyncStates()
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package pl.firmatpp.kierowca.data.sync
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(tableName = "driver_bootstrap_cache")
|
||||
data class DriverBootstrapCacheEntity(
|
||||
@PrimaryKey val date: String,
|
||||
val payloadJson: String,
|
||||
val checksum: String?,
|
||||
val version: Long?,
|
||||
val syncedAtEpochMillis: Long,
|
||||
)
|
||||
|
||||
@Entity(tableName = "driver_route_cache")
|
||||
data class DriverRouteCacheEntity(
|
||||
@PrimaryKey val routeId: String,
|
||||
val payloadJson: String,
|
||||
val checksum: String?,
|
||||
val version: Long?,
|
||||
val syncedAtEpochMillis: Long,
|
||||
)
|
||||
|
||||
@Entity(
|
||||
tableName = "driver_sync_states",
|
||||
indices = [
|
||||
Index(value = ["scope", "date", "routeId"], unique = true),
|
||||
],
|
||||
)
|
||||
data class DriverSyncStateEntity(
|
||||
@PrimaryKey val key: String,
|
||||
val scope: String,
|
||||
val date: String?,
|
||||
val routeId: String?,
|
||||
val checksum: String,
|
||||
val version: Long,
|
||||
val computedAt: String,
|
||||
val syncedAtEpochMillis: Long,
|
||||
)
|
||||
|
||||
data class CachedValue<T>(
|
||||
val value: T,
|
||||
val stale: Boolean,
|
||||
val syncedAtEpochMillis: Long?,
|
||||
)
|
||||
|
||||
fun syncStateKey(scope: String, date: String?, routeId: String?): String =
|
||||
listOf(scope, date ?: "-", routeId ?: "-").joinToString(":")
|
||||
@@ -0,0 +1,197 @@
|
||||
package pl.firmatpp.kierowca.data.sync
|
||||
|
||||
import android.content.Context
|
||||
import com.google.gson.Gson
|
||||
import java.io.IOException
|
||||
import java.time.LocalDate
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.model.BootstrapResponse
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
import pl.firmatpp.kierowca.data.model.RouteResponse
|
||||
import pl.firmatpp.kierowca.data.model.SyncScopeDto
|
||||
import pl.firmatpp.kierowca.data.model.SyncStateResponse
|
||||
import pl.firmatpp.kierowca.data.upload.DriverDatabase
|
||||
import retrofit2.HttpException
|
||||
|
||||
class DriverSyncRepository(
|
||||
context: Context,
|
||||
private val repository: DriverRepository = DriverRepository(context),
|
||||
private val dao: DriverCacheDao = DriverDatabase.get(context).driverCacheDao(),
|
||||
private val gson: Gson = Gson(),
|
||||
) {
|
||||
suspend fun bootstrap(date: String?): CachedValue<BootstrapResponse> {
|
||||
val requestedDate = date ?: currentDateFallback()
|
||||
|
||||
return runCatching {
|
||||
val response = repository.bootstrap(date)
|
||||
val selectedDate = response.driverAppSettings?.selectedDate ?: requestedDate
|
||||
val routeState = response.syncState?.scopes?.firstOrNull { it.scope == SCOPE_ROUTES }
|
||||
dao.upsertBootstrap(
|
||||
DriverBootstrapCacheEntity(
|
||||
date = selectedDate,
|
||||
payloadJson = gson.toJson(response),
|
||||
checksum = routeState?.checksum,
|
||||
version = routeState?.version,
|
||||
syncedAtEpochMillis = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
saveSyncStates(response.syncState)
|
||||
CachedValue(response, stale = false, syncedAtEpochMillis = System.currentTimeMillis())
|
||||
}.getOrElse { throwable ->
|
||||
cachedBootstrap(requestedDate, throwable)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun route(routeId: String): CachedValue<RouteResponse> =
|
||||
runCatching {
|
||||
val response = repository.route(routeId)
|
||||
val routeState = response.syncState?.scopes?.firstOrNull { it.scope == SCOPE_ROUTE_DETAIL }
|
||||
dao.upsertRoute(
|
||||
DriverRouteCacheEntity(
|
||||
routeId = routeId,
|
||||
payloadJson = gson.toJson(response),
|
||||
checksum = routeState?.checksum,
|
||||
version = routeState?.version,
|
||||
syncedAtEpochMillis = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
saveSyncStates(response.syncState)
|
||||
CachedValue(response, stale = false, syncedAtEpochMillis = System.currentTimeMillis())
|
||||
}.getOrElse { throwable ->
|
||||
cachedRoute(routeId, throwable)
|
||||
}
|
||||
|
||||
suspend fun bootstrapFromCache(date: String?): CachedValue<BootstrapResponse>? {
|
||||
val cached = dao.bootstrap(date ?: currentDateFallback()) ?: return null
|
||||
return CachedValue(
|
||||
value = gson.fromJson(cached.payloadJson, BootstrapResponse::class.java),
|
||||
stale = true,
|
||||
syncedAtEpochMillis = cached.syncedAtEpochMillis,
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun hasBootstrapCache(date: String?): Boolean =
|
||||
dao.bootstrap(date ?: currentDateFallback()) != null
|
||||
|
||||
suspend fun routeFromCache(routeId: String): CachedValue<RouteResponse>? {
|
||||
val cached = dao.route(routeId) ?: return null
|
||||
return CachedValue(
|
||||
value = gson.fromJson(cached.payloadJson, RouteResponse::class.java),
|
||||
stale = true,
|
||||
syncedAtEpochMillis = cached.syncedAtEpochMillis,
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun cacheConfirmedRoute(route: DriverRouteDto, date: String?) {
|
||||
val syncedAt = System.currentTimeMillis()
|
||||
dao.upsertRoute(
|
||||
DriverRouteCacheEntity(
|
||||
routeId = route.id,
|
||||
payloadJson = gson.toJson(RouteResponse(route = route)),
|
||||
checksum = null,
|
||||
version = null,
|
||||
syncedAtEpochMillis = syncedAt,
|
||||
),
|
||||
)
|
||||
|
||||
(routeVisibleDates(route) + listOfNotNull(date)).distinct().forEach { selectedDate ->
|
||||
val cachedBootstrap = dao.bootstrap(selectedDate) ?: return@forEach
|
||||
val response = gson.fromJson(cachedBootstrap.payloadJson, BootstrapResponse::class.java)
|
||||
val updatedRoutes = response.routes.today.map { item -> if (item.id == route.id) route else item }
|
||||
dao.upsertBootstrap(
|
||||
cachedBootstrap.copy(
|
||||
payloadJson = gson.toJson(response.copy(routes = response.routes.copy(today = updatedRoutes))),
|
||||
checksum = null,
|
||||
version = null,
|
||||
syncedAtEpochMillis = syncedAt,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun fetchSyncState(date: String?, routeId: String?): SyncStateResponse =
|
||||
repository.syncState(date, routeId)
|
||||
|
||||
suspend fun shouldRefresh(scope: SyncScopeDto): Boolean {
|
||||
val local = dao.syncState(scope.scope, scope.date, scope.routeId)
|
||||
return local == null || local.checksum != scope.checksum || local.version < scope.version
|
||||
}
|
||||
|
||||
suspend fun saveSyncStates(response: SyncStateResponse?) {
|
||||
response?.scopes.orEmpty().forEach { scope ->
|
||||
saveSyncScope(scope)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveSyncScope(scope: SyncScopeDto) {
|
||||
dao.upsertSyncState(
|
||||
DriverSyncStateEntity(
|
||||
key = syncStateKey(scope.scope, scope.date, scope.routeId),
|
||||
scope = scope.scope,
|
||||
date = scope.date,
|
||||
routeId = scope.routeId,
|
||||
checksum = scope.checksum,
|
||||
version = scope.version,
|
||||
computedAt = scope.computedAt,
|
||||
syncedAtEpochMillis = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun clearCache() {
|
||||
dao.clearBootstrap()
|
||||
dao.clearRoutes()
|
||||
dao.clearSyncStates()
|
||||
}
|
||||
|
||||
private suspend fun cachedBootstrap(date: String, throwable: Throwable): CachedValue<BootstrapResponse> {
|
||||
val cached = dao.bootstrap(date)
|
||||
if (cached != null && throwable.isReadFallbackAllowed()) {
|
||||
return CachedValue(
|
||||
gson.fromJson(cached.payloadJson, BootstrapResponse::class.java),
|
||||
stale = true,
|
||||
syncedAtEpochMillis = cached.syncedAtEpochMillis,
|
||||
)
|
||||
}
|
||||
throw throwable
|
||||
}
|
||||
|
||||
private suspend fun cachedRoute(routeId: String, throwable: Throwable): CachedValue<RouteResponse> {
|
||||
val cached = dao.route(routeId)
|
||||
if (cached != null && throwable.isReadFallbackAllowed()) {
|
||||
return CachedValue(
|
||||
gson.fromJson(cached.payloadJson, RouteResponse::class.java),
|
||||
stale = true,
|
||||
syncedAtEpochMillis = cached.syncedAtEpochMillis,
|
||||
)
|
||||
}
|
||||
throw throwable
|
||||
}
|
||||
|
||||
private fun Throwable.isReadFallbackAllowed(): Boolean =
|
||||
this is IOException || (this is HttpException && code() in 500..599)
|
||||
|
||||
private fun currentDateFallback(): String = java.time.LocalDate.now().toString()
|
||||
|
||||
private fun routeVisibleDates(route: DriverRouteDto): List<String> {
|
||||
val start = route.routeDate?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: return emptyList()
|
||||
val end = route.unloadingDate
|
||||
?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
?.takeUnless { it.isBefore(start) }
|
||||
?: start
|
||||
|
||||
return generateSequence(start) { date -> date.plusDays(1).takeIf { !it.isAfter(end) } }
|
||||
.map(LocalDate::toString)
|
||||
.toList()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SCOPE_ROUTES = "routes"
|
||||
const val SCOPE_ROUTE_DETAIL = "route_detail"
|
||||
const val SCOPE_SETTINGS = "settings"
|
||||
const val SCOPE_DISPATCH_SHEET = "dispatch_sheet"
|
||||
const val SCOPE_LEAVE_REQUESTS = "leave_requests"
|
||||
const val SCOPE_LEAVE_CALENDAR = "leave_calendar"
|
||||
const val SCOPE_SESSION = "session"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package pl.firmatpp.kierowca.data.sync
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
|
||||
class NetworkMonitor(context: Context) {
|
||||
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
|
||||
val isOnline: Flow<Boolean> = callbackFlow {
|
||||
fun current(): Boolean = isCurrentlyValidated()
|
||||
|
||||
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
trySend(current())
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
trySend(current())
|
||||
}
|
||||
|
||||
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
|
||||
trySend(current())
|
||||
}
|
||||
}
|
||||
|
||||
trySend(current())
|
||||
connectivityManager.registerDefaultNetworkCallback(callback)
|
||||
awaitClose { connectivityManager.unregisterNetworkCallback(callback) }
|
||||
}.distinctUntilChanged()
|
||||
|
||||
fun isCurrentlyValidated(): Boolean = connectivityManager.activeNetwork
|
||||
?.let(connectivityManager::getNetworkCapabilities)
|
||||
?.let(::hasValidatedInternet) == true
|
||||
}
|
||||
|
||||
internal fun hasValidatedInternet(capabilities: NetworkCapabilities): Boolean =
|
||||
hasValidatedInternetCapabilities(
|
||||
hasInternet = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET),
|
||||
hasValidated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED),
|
||||
)
|
||||
|
||||
internal fun hasValidatedInternetCapabilities(hasInternet: Boolean, hasValidated: Boolean): Boolean =
|
||||
hasInternet && hasValidated
|
||||
@@ -0,0 +1,27 @@
|
||||
package pl.firmatpp.kierowca.data.sync
|
||||
|
||||
import java.io.IOException
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import pl.firmatpp.kierowca.domain.StartupSessionPolicy
|
||||
|
||||
class StartupOfflineFallbackLoader(
|
||||
private val timeoutMillis: Long = StartupSessionPolicy.OFFLINE_FALLBACK_MILLIS,
|
||||
) {
|
||||
suspend fun <T> load(
|
||||
onlineLoad: suspend () -> T,
|
||||
offlineLoad: suspend () -> T?,
|
||||
): T {
|
||||
val onlineValue = withTimeoutOrNull(timeoutMillis) {
|
||||
onlineLoad()
|
||||
}
|
||||
if (onlineValue != null) {
|
||||
return onlineValue
|
||||
}
|
||||
|
||||
return offlineLoad()
|
||||
?: throw IOException(
|
||||
"Serwer nie odpowiedział w ciągu ${StartupSessionPolicy.OFFLINE_FALLBACK_SECONDS} sekund " +
|
||||
"i w telefonie nie ma zapisanych danych offline.",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface DispatchSheetUploadDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsert(upload: DispatchSheetUploadEntity)
|
||||
|
||||
@Query("SELECT * FROM dispatch_sheet_uploads WHERE clientRequestId = :clientRequestId LIMIT 1")
|
||||
suspend fun find(clientRequestId: String): DispatchSheetUploadEntity?
|
||||
|
||||
@Query("SELECT * FROM dispatch_sheet_uploads WHERE status != 'CONFIRMED' AND status != 'CANCELLED'")
|
||||
suspend fun allUnsent(): List<DispatchSheetUploadEntity>
|
||||
|
||||
@Query("SELECT * FROM dispatch_sheet_uploads")
|
||||
suspend fun allRecords(): List<DispatchSheetUploadEntity>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM dispatch_sheet_uploads WHERE status != 'CONFIRMED' AND status != 'CANCELLED'")
|
||||
fun observeUnsentCount(): Flow<Int>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM dispatch_sheet_uploads
|
||||
WHERE workDate = :workDate
|
||||
AND status != 'CANCELLED'
|
||||
ORDER BY createdAtEpochMillis ASC
|
||||
""",
|
||||
)
|
||||
fun observeVisibleForWorkDate(workDate: String): Flow<List<DispatchSheetUploadEntity>>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
UPDATE dispatch_sheet_uploads
|
||||
SET status = :status,
|
||||
progress = :progress,
|
||||
lastError = :lastError,
|
||||
attemptCount = attemptCount + :attemptIncrement,
|
||||
updatedAtEpochMillis = :updatedAt
|
||||
WHERE clientRequestId = :clientRequestId
|
||||
""",
|
||||
)
|
||||
suspend fun updateStatus(
|
||||
clientRequestId: String,
|
||||
status: String,
|
||||
progress: Int,
|
||||
lastError: String?,
|
||||
attemptIncrement: Int,
|
||||
updatedAt: Long = System.currentTimeMillis(),
|
||||
)
|
||||
|
||||
@Query(
|
||||
"""
|
||||
UPDATE dispatch_sheet_uploads
|
||||
SET status = 'CONFIRMED',
|
||||
progress = 100,
|
||||
lastError = NULL,
|
||||
serverPhotoId = :serverPhotoId,
|
||||
updatedAtEpochMillis = :updatedAt
|
||||
WHERE clientRequestId = :clientRequestId
|
||||
""",
|
||||
)
|
||||
suspend fun markConfirmed(
|
||||
clientRequestId: String,
|
||||
serverPhotoId: String,
|
||||
updatedAt: Long = System.currentTimeMillis(),
|
||||
)
|
||||
|
||||
@Query("DELETE FROM dispatch_sheet_uploads WHERE clientRequestId = :clientRequestId")
|
||||
suspend fun delete(clientRequestId: String)
|
||||
|
||||
@Query("DELETE FROM dispatch_sheet_uploads")
|
||||
suspend fun deleteAll()
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(
|
||||
tableName = "dispatch_sheet_uploads",
|
||||
indices = [
|
||||
Index(value = ["workDate"]),
|
||||
Index(value = ["status"]),
|
||||
],
|
||||
)
|
||||
data class DispatchSheetUploadEntity(
|
||||
@PrimaryKey val clientRequestId: String,
|
||||
val workDate: String,
|
||||
val replacePhotoId: String?,
|
||||
val localPath: String,
|
||||
val source: String,
|
||||
val takenAt: String?,
|
||||
val latitude: Double?,
|
||||
val longitude: Double?,
|
||||
val locationAccuracyMeters: Double?,
|
||||
val mimeType: String,
|
||||
val size: Long,
|
||||
val contentSha256: String,
|
||||
val status: String = PhotoUploadStatus.Pending.storageValue,
|
||||
val progress: Int = 0,
|
||||
val attemptCount: Int = 0,
|
||||
val lastError: String? = null,
|
||||
val serverPhotoId: String? = null,
|
||||
val createdAtEpochMillis: Long = System.currentTimeMillis(),
|
||||
val updatedAtEpochMillis: Long = System.currentTimeMillis(),
|
||||
) {
|
||||
val statusType: PhotoUploadStatus
|
||||
get() = PhotoUploadStatus.fromStorage(status)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.work.BackoffPolicy
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.workDataOf
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import pl.firmatpp.kierowca.data.PhotoUploadMetadata
|
||||
|
||||
class DispatchSheetUploadOutbox(
|
||||
private val context: Context,
|
||||
private val dao: DispatchSheetUploadDao = DriverDatabase.get(context).dispatchSheetUploadDao(),
|
||||
private val workManager: WorkManager = WorkManager.getInstance(context),
|
||||
) {
|
||||
fun observeVisibleForWorkDate(workDate: String): Flow<List<DispatchSheetUploadEntity>> =
|
||||
dao.observeVisibleForWorkDate(workDate)
|
||||
|
||||
suspend fun enqueue(
|
||||
workDate: String,
|
||||
replacePhotoId: String?,
|
||||
uri: Uri,
|
||||
source: String,
|
||||
metadata: PhotoUploadMetadata,
|
||||
): DispatchSheetUploadEntity {
|
||||
val clientRequestId = UUID.randomUUID().toString()
|
||||
val mimeType = context.contentResolver.getType(uri) ?: "image/jpeg"
|
||||
val extension = when (mimeType) {
|
||||
"image/png" -> "png"
|
||||
"image/webp" -> "webp"
|
||||
else -> "jpg"
|
||||
}
|
||||
val uploadDir = File(context.filesDir, "dispatch-sheet-upload-outbox").apply { mkdirs() }
|
||||
val localFile = File(uploadDir, "$clientRequestId.$extension")
|
||||
val sha256 = copyAndHash(uri, localFile)
|
||||
val upload = DispatchSheetUploadEntity(
|
||||
clientRequestId = clientRequestId,
|
||||
workDate = workDate,
|
||||
replacePhotoId = replacePhotoId,
|
||||
localPath = localFile.absolutePath,
|
||||
source = source,
|
||||
takenAt = metadata.takenAt,
|
||||
latitude = metadata.latitude,
|
||||
longitude = metadata.longitude,
|
||||
locationAccuracyMeters = metadata.locationAccuracyMeters,
|
||||
mimeType = mimeType,
|
||||
size = localFile.length(),
|
||||
contentSha256 = sha256,
|
||||
)
|
||||
|
||||
dao.upsert(upload)
|
||||
enqueueWorker(clientRequestId)
|
||||
|
||||
return upload
|
||||
}
|
||||
|
||||
suspend fun discard(clientRequestId: String) {
|
||||
workManager.cancelUniqueWork(DispatchSheetUploadWorker.uniqueWorkName(clientRequestId))
|
||||
dao.find(clientRequestId)?.let { upload ->
|
||||
File(upload.localPath).delete()
|
||||
dao.delete(upload.clientRequestId)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun retry(clientRequestId: String) {
|
||||
val existing = dao.find(clientRequestId) ?: return
|
||||
dao.upsert(
|
||||
existing.copy(
|
||||
status = PhotoUploadStatus.Pending.storageValue,
|
||||
progress = 0,
|
||||
lastError = null,
|
||||
updatedAtEpochMillis = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
enqueueWorker(clientRequestId)
|
||||
}
|
||||
|
||||
private fun enqueueWorker(clientRequestId: String) {
|
||||
val request = OneTimeWorkRequestBuilder<DispatchSheetUploadWorker>()
|
||||
.setInputData(workDataOf(DispatchSheetUploadWorker.KEY_CLIENT_REQUEST_ID to clientRequestId))
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
workManager.enqueueUniqueWork(
|
||||
DispatchSheetUploadWorker.uniqueWorkName(clientRequestId),
|
||||
ExistingWorkPolicy.REPLACE,
|
||||
request,
|
||||
)
|
||||
}
|
||||
|
||||
private fun copyAndHash(uri: Uri, target: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
context.contentResolver.openInputStream(uri).use { input ->
|
||||
requireNotNull(input) { "Nie można odczytać zdjęcia karty spedycyjnej." }
|
||||
target.outputStream().use { output ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read == -1) break
|
||||
digest.update(buffer, 0, read)
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import pl.firmatpp.kierowca.data.model.DispatchSheetUploadReceiptDto
|
||||
|
||||
object DispatchSheetUploadReceiptVerifier {
|
||||
fun matches(upload: DispatchSheetUploadEntity, receipt: DispatchSheetUploadReceiptDto): Boolean =
|
||||
upload.clientRequestId == receipt.clientRequestId &&
|
||||
upload.contentSha256.equals(receipt.contentSha256, ignoreCase = true) &&
|
||||
receipt.serverPhotoId.isNotBlank()
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.workDataOf
|
||||
import java.io.File
|
||||
import pl.firmatpp.kierowca.data.ApiErrorKind
|
||||
import pl.firmatpp.kierowca.data.ApiErrorMapper
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.rethrowIfCancellation
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
import pl.firmatpp.kierowca.data.sync.NetworkMonitor
|
||||
|
||||
class DispatchSheetUploadWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters,
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
private val dao = DriverDatabase.get(appContext).dispatchSheetUploadDao()
|
||||
private val repository = DriverRepository(appContext)
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) return Result.retry()
|
||||
val clientRequestId = inputData.getString(KEY_CLIENT_REQUEST_ID) ?: return Result.failure()
|
||||
val upload = dao.find(clientRequestId) ?: return Result.failure()
|
||||
val file = File(upload.localPath)
|
||||
|
||||
if (!file.exists()) {
|
||||
val message = "Lokalny plik zdjęcia karty spedycyjnej nie istnieje. Zdjęcie nie zostało zapisane."
|
||||
dao.updateStatus(
|
||||
clientRequestId = clientRequestId,
|
||||
status = PhotoUploadStatus.FailedPermanent.storageValue,
|
||||
progress = 0,
|
||||
lastError = PhotoUploadFailureDetails.local(message),
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
return Result.failure()
|
||||
}
|
||||
|
||||
dao.updateStatus(
|
||||
clientRequestId = clientRequestId,
|
||||
status = PhotoUploadStatus.Uploading.storageValue,
|
||||
progress = 10,
|
||||
lastError = null,
|
||||
attemptIncrement = 1,
|
||||
)
|
||||
setProgress(workDataOf(KEY_PROGRESS to 10))
|
||||
|
||||
return runCatching {
|
||||
setProgress(workDataOf(KEY_PROGRESS to 70))
|
||||
val response = repository.uploadQueuedDispatchSheetPhoto(upload)
|
||||
|
||||
dao.updateStatus(
|
||||
clientRequestId = clientRequestId,
|
||||
status = PhotoUploadStatus.Verifying.storageValue,
|
||||
progress = 90,
|
||||
lastError = null,
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
setProgress(workDataOf(KEY_PROGRESS to 90))
|
||||
|
||||
val receipt = response.receipt
|
||||
if (!DispatchSheetUploadReceiptVerifier.matches(upload, receipt)) {
|
||||
error("Serwer nie potwierdził zgodności zdjęcia karty spedycyjnej. Zdjęcie nie zostało zapisane.")
|
||||
}
|
||||
|
||||
dao.markConfirmed(clientRequestId, receipt.serverPhotoId)
|
||||
file.delete()
|
||||
dao.delete(clientRequestId)
|
||||
Result.success()
|
||||
}.getOrElse { throwable ->
|
||||
throwable.rethrowIfCancellation()
|
||||
val error = ApiErrorMapper.map(throwable)
|
||||
AppDiagnostics.reportNonFatal(
|
||||
throwable = throwable,
|
||||
operation = "dispatch_sheet_upload_worker",
|
||||
keys = mapOf(
|
||||
"client_request_id" to clientRequestId,
|
||||
"api_error_kind" to error.kind.name,
|
||||
"api_error_code" to error.code,
|
||||
"api_status_code" to error.statusCode,
|
||||
"retryable" to error.retryable,
|
||||
),
|
||||
)
|
||||
val status = if (error.retryable) PhotoUploadStatus.FailedRetryable else PhotoUploadStatus.FailedPermanent
|
||||
dao.updateStatus(
|
||||
clientRequestId = clientRequestId,
|
||||
status = status.storageValue,
|
||||
progress = 0,
|
||||
lastError = PhotoUploadFailureDetails.fromApiError(error),
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
|
||||
if (error.retryable && error.kind != ApiErrorKind.Auth) Result.retry() else Result.failure()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val KEY_CLIENT_REQUEST_ID = "clientRequestId"
|
||||
const val KEY_PROGRESS = "progress"
|
||||
|
||||
fun uniqueWorkName(clientRequestId: String): String = "dispatch-sheet-upload-$clientRequestId"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import pl.firmatpp.kierowca.data.sync.DriverBootstrapCacheEntity
|
||||
import pl.firmatpp.kierowca.data.sync.DriverCacheDao
|
||||
import pl.firmatpp.kierowca.data.sync.DriverRouteCacheEntity
|
||||
import pl.firmatpp.kierowca.data.sync.DriverSyncStateEntity
|
||||
|
||||
@Database(
|
||||
entities = [
|
||||
PhotoUploadEntity::class,
|
||||
DispatchSheetUploadEntity::class,
|
||||
RouteActionEntity::class,
|
||||
RoutePointEntity::class,
|
||||
DriverBootstrapCacheEntity::class,
|
||||
DriverRouteCacheEntity::class,
|
||||
DriverSyncStateEntity::class,
|
||||
],
|
||||
version = 7,
|
||||
exportSchema = false,
|
||||
)
|
||||
abstract class DriverDatabase : RoomDatabase() {
|
||||
abstract fun photoUploadDao(): PhotoUploadDao
|
||||
abstract fun dispatchSheetUploadDao(): DispatchSheetUploadDao
|
||||
abstract fun routeActionDao(): RouteActionDao
|
||||
abstract fun routePointDao(): RoutePointDao
|
||||
abstract fun driverCacheDao(): DriverCacheDao
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
private var instance: DriverDatabase? = null
|
||||
|
||||
private val migration1To2 = object : Migration(1, 2) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS driver_bootstrap_cache (
|
||||
date TEXT NOT NULL PRIMARY KEY,
|
||||
payloadJson TEXT NOT NULL,
|
||||
checksum TEXT,
|
||||
version INTEGER,
|
||||
syncedAtEpochMillis INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS driver_route_cache (
|
||||
routeId TEXT NOT NULL PRIMARY KEY,
|
||||
payloadJson TEXT NOT NULL,
|
||||
checksum TEXT,
|
||||
version INTEGER,
|
||||
syncedAtEpochMillis INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS driver_sync_states (
|
||||
key TEXT NOT NULL PRIMARY KEY,
|
||||
scope TEXT NOT NULL,
|
||||
date TEXT,
|
||||
routeId TEXT,
|
||||
checksum TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
computedAt TEXT NOT NULL,
|
||||
syncedAtEpochMillis INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_driver_sync_states_scope_date_routeId ON driver_sync_states(scope, date, routeId)")
|
||||
}
|
||||
}
|
||||
|
||||
private val migration2To3 = object : Migration(2, 3) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS dispatch_sheet_uploads (
|
||||
clientRequestId TEXT NOT NULL PRIMARY KEY,
|
||||
workDate TEXT NOT NULL,
|
||||
replacePhotoId TEXT,
|
||||
localPath TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
takenAt TEXT,
|
||||
latitude REAL,
|
||||
longitude REAL,
|
||||
locationAccuracyMeters REAL,
|
||||
mimeType TEXT NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
contentSha256 TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
progress INTEGER NOT NULL,
|
||||
attemptCount INTEGER NOT NULL,
|
||||
lastError TEXT,
|
||||
serverPhotoId TEXT,
|
||||
createdAtEpochMillis INTEGER NOT NULL,
|
||||
updatedAtEpochMillis INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_dispatch_sheet_uploads_workDate ON dispatch_sheet_uploads(workDate)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_dispatch_sheet_uploads_status ON dispatch_sheet_uploads(status)")
|
||||
}
|
||||
}
|
||||
|
||||
private val migration3To4 = object : Migration(3, 4) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE photo_uploads ADD COLUMN stage TEXT NOT NULL DEFAULT 'other'")
|
||||
}
|
||||
}
|
||||
|
||||
private val migration4To5 = object : Migration(4, 5) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS route_actions (
|
||||
clientActionId TEXT NOT NULL PRIMARY KEY,
|
||||
routeId TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
weight REAL NOT NULL,
|
||||
occurredAt TEXT NOT NULL,
|
||||
photoClientRequestIdsJson TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
attemptCount INTEGER NOT NULL,
|
||||
lastError TEXT,
|
||||
createdAtEpochMillis INTEGER NOT NULL,
|
||||
updatedAtEpochMillis INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_route_actions_routeId ON route_actions(routeId)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_route_actions_status ON route_actions(status)")
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS route_points (
|
||||
clientPointId TEXT NOT NULL PRIMARY KEY,
|
||||
routeId TEXT NOT NULL,
|
||||
driverId TEXT NOT NULL,
|
||||
lat REAL NOT NULL,
|
||||
lon REAL NOT NULL,
|
||||
accuracy REAL NOT NULL,
|
||||
speed REAL,
|
||||
bearing REAL,
|
||||
timestamp INTEGER NOT NULL,
|
||||
battery INTEGER,
|
||||
charging INTEGER NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
attemptCount INTEGER NOT NULL,
|
||||
lastError TEXT,
|
||||
createdAtEpochMillis INTEGER NOT NULL,
|
||||
updatedAtEpochMillis INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_route_points_routeId ON route_points(routeId)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_route_points_status ON route_points(status)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_route_points_routeId_status ON route_points(routeId, status)")
|
||||
}
|
||||
}
|
||||
|
||||
private val migration5To6 = object : Migration(5, 6) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE route_actions_new (
|
||||
clientActionId TEXT NOT NULL PRIMARY KEY,
|
||||
routeId TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
weight REAL,
|
||||
occurredAt TEXT NOT NULL,
|
||||
photoClientRequestIdsJson TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
attemptCount INTEGER NOT NULL,
|
||||
lastError TEXT,
|
||||
createdAtEpochMillis INTEGER NOT NULL,
|
||||
updatedAtEpochMillis INTEGER NOT NULL
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL(
|
||||
"""
|
||||
INSERT INTO route_actions_new (
|
||||
clientActionId, routeId, action, weight, occurredAt, photoClientRequestIdsJson,
|
||||
status, attemptCount, lastError, createdAtEpochMillis, updatedAtEpochMillis
|
||||
)
|
||||
SELECT
|
||||
clientActionId, routeId, action, weight, occurredAt, photoClientRequestIdsJson,
|
||||
status, attemptCount, lastError, createdAtEpochMillis, updatedAtEpochMillis
|
||||
FROM route_actions
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL("DROP TABLE route_actions")
|
||||
db.execSQL("ALTER TABLE route_actions_new RENAME TO route_actions")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_route_actions_routeId ON route_actions(routeId)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS index_route_actions_status ON route_actions(status)")
|
||||
}
|
||||
}
|
||||
|
||||
private val migration6To7 = object : Migration(6, 7) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE route_actions ADD COLUMN notes TEXT")
|
||||
}
|
||||
}
|
||||
|
||||
fun get(context: Context): DriverDatabase =
|
||||
instance ?: synchronized(this) {
|
||||
instance ?: Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
DriverDatabase::class.java,
|
||||
"driver-local-outbox.db",
|
||||
).addMigrations(
|
||||
migration1To2,
|
||||
migration2To3,
|
||||
migration3To4,
|
||||
migration4To5,
|
||||
migration5To6,
|
||||
migration6To7,
|
||||
).build().also { instance = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.WorkManager
|
||||
import java.io.File
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class OfflineOutboxManager(private val context: Context) {
|
||||
private val database = DriverDatabase.get(context)
|
||||
private val workManager = WorkManager.getInstance(context)
|
||||
|
||||
suspend fun pendingCount(): Int =
|
||||
database.photoUploadDao().allUnsent().size +
|
||||
database.dispatchSheetUploadDao().allUnsent().size +
|
||||
database.routeActionDao().allUnsent().size +
|
||||
database.routePointDao().allUnsent().size
|
||||
|
||||
suspend fun repairGpsQueue() {
|
||||
val retryableStatuses = setOf(
|
||||
RoutePointStatus.Pending,
|
||||
RoutePointStatus.Syncing,
|
||||
RoutePointStatus.FailedRetryable,
|
||||
)
|
||||
val routeIds = database.routePointDao().allUnsent()
|
||||
.filter { it.status in retryableStatuses }
|
||||
.map { it.routeId }
|
||||
.distinct()
|
||||
|
||||
routeIds.forEach { routeId ->
|
||||
runCatching {
|
||||
workManager.cancelUniqueWork(RoutePointWorker.uniqueWorkName(routeId))
|
||||
.result
|
||||
.get(5, TimeUnit.SECONDS)
|
||||
}
|
||||
RoutePointOutbox(context).enqueueWorker(routeId, delaySeconds = 0L)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun repairOperationalQueues() {
|
||||
val photoOutbox = PhotoUploadOutbox(context)
|
||||
val dispatchSheetOutbox = DispatchSheetUploadOutbox(context)
|
||||
val routeActionOutbox = RouteActionOutbox(context)
|
||||
|
||||
database.photoUploadDao().allUnsent()
|
||||
.filter { shouldRepairPhotoUpload(it.status, it.lastError) }
|
||||
.forEach { photoOutbox.retry(it.clientRequestId) }
|
||||
|
||||
database.dispatchSheetUploadDao().allUnsent()
|
||||
.filter { shouldRepairPhotoUpload(it.status, it.lastError) }
|
||||
.forEach { dispatchSheetOutbox.retry(it.clientRequestId) }
|
||||
|
||||
database.routeActionDao().allUnsent()
|
||||
.filter { shouldRepairRouteAction(it.status, it.lastError) }
|
||||
.forEach { routeActionOutbox.retry(it.clientActionId) }
|
||||
}
|
||||
|
||||
suspend fun clearAll() {
|
||||
val photos = database.photoUploadDao().allRecords()
|
||||
val dispatchSheets = database.dispatchSheetUploadDao().allRecords()
|
||||
val actions = database.routeActionDao().allUnsent()
|
||||
val points = database.routePointDao().allUnsent()
|
||||
|
||||
photos.forEach {
|
||||
workManager.cancelUniqueWork(PhotoUploadWorker.uniqueWorkName(it.clientRequestId))
|
||||
File(it.localPath).delete()
|
||||
}
|
||||
dispatchSheets.forEach {
|
||||
workManager.cancelUniqueWork(DispatchSheetUploadWorker.uniqueWorkName(it.clientRequestId))
|
||||
File(it.localPath).delete()
|
||||
}
|
||||
actions.forEach { workManager.cancelUniqueWork(RouteActionWorker.uniqueWorkName(it.clientActionId)) }
|
||||
points.map { it.routeId }.distinct().forEach {
|
||||
workManager.cancelUniqueWork(RoutePointWorker.uniqueWorkName(it))
|
||||
}
|
||||
|
||||
database.photoUploadDao().deleteAll()
|
||||
database.dispatchSheetUploadDao().deleteAll()
|
||||
database.routeActionDao().deleteAll()
|
||||
database.routePointDao().deleteAll()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isWorkerCancellationFailure(lastError: String?): Boolean =
|
||||
lastError?.let { error ->
|
||||
error.contains("Job was cancelled", ignoreCase = true) ||
|
||||
error.contains("CancellationException", ignoreCase = true)
|
||||
} == true
|
||||
|
||||
internal fun isPhotoDependencyFailure(lastError: String?): Boolean =
|
||||
lastError?.contains("Wymagane zdjęcie nie zostało wysłane", ignoreCase = true) == true
|
||||
|
||||
internal fun shouldRepairPhotoUpload(status: String, lastError: String?): Boolean =
|
||||
status in setOf(
|
||||
PhotoUploadStatus.Pending.storageValue,
|
||||
PhotoUploadStatus.Uploading.storageValue,
|
||||
PhotoUploadStatus.Verifying.storageValue,
|
||||
PhotoUploadStatus.FailedRetryable.storageValue,
|
||||
) || (status == PhotoUploadStatus.FailedPermanent.storageValue && isWorkerCancellationFailure(lastError))
|
||||
|
||||
internal fun shouldRepairRouteAction(status: String, lastError: String?): Boolean =
|
||||
status in setOf(
|
||||
RouteActionStatus.Pending,
|
||||
RouteActionStatus.WaitingForPhotos,
|
||||
RouteActionStatus.Syncing,
|
||||
RouteActionStatus.FailedRetryable,
|
||||
) || (
|
||||
status == RouteActionStatus.FailedPermanent &&
|
||||
(isWorkerCancellationFailure(lastError) || isPhotoDependencyFailure(lastError))
|
||||
)
|
||||
@@ -0,0 +1,94 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface PhotoUploadDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsert(upload: PhotoUploadEntity)
|
||||
|
||||
@Query("SELECT * FROM photo_uploads WHERE clientRequestId = :clientRequestId LIMIT 1")
|
||||
suspend fun find(clientRequestId: String): PhotoUploadEntity?
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM photo_uploads
|
||||
WHERE routeId = :routeId
|
||||
AND status != 'CANCELLED'
|
||||
ORDER BY createdAtEpochMillis ASC
|
||||
""",
|
||||
)
|
||||
fun observeVisibleForRoute(routeId: String): Flow<List<PhotoUploadEntity>>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM photo_uploads
|
||||
WHERE status != 'CONFIRMED'
|
||||
AND status != 'CANCELLED'
|
||||
ORDER BY createdAtEpochMillis ASC
|
||||
""",
|
||||
)
|
||||
fun observeQueuedUploads(): Flow<List<PhotoUploadEntity>>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM photo_uploads
|
||||
WHERE routeId = :routeId
|
||||
AND status = 'CONFIRMED'
|
||||
""",
|
||||
)
|
||||
suspend fun confirmedForRoute(routeId: String): List<PhotoUploadEntity>
|
||||
|
||||
@Query("SELECT * FROM photo_uploads WHERE status != 'CONFIRMED' AND status != 'CANCELLED'")
|
||||
suspend fun allUnsent(): List<PhotoUploadEntity>
|
||||
|
||||
@Query("SELECT * FROM photo_uploads")
|
||||
suspend fun allRecords(): List<PhotoUploadEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
UPDATE photo_uploads
|
||||
SET status = :status,
|
||||
progress = :progress,
|
||||
lastError = :lastError,
|
||||
attemptCount = attemptCount + :attemptIncrement,
|
||||
updatedAtEpochMillis = :updatedAt
|
||||
WHERE clientRequestId = :clientRequestId
|
||||
""",
|
||||
)
|
||||
suspend fun updateStatus(
|
||||
clientRequestId: String,
|
||||
status: String,
|
||||
progress: Int,
|
||||
lastError: String?,
|
||||
attemptIncrement: Int,
|
||||
updatedAt: Long = System.currentTimeMillis(),
|
||||
)
|
||||
|
||||
@Query(
|
||||
"""
|
||||
UPDATE photo_uploads
|
||||
SET status = 'CONFIRMED',
|
||||
progress = 100,
|
||||
lastError = NULL,
|
||||
serverPhotoId = :serverPhotoId,
|
||||
updatedAtEpochMillis = :updatedAt
|
||||
WHERE clientRequestId = :clientRequestId
|
||||
""",
|
||||
)
|
||||
suspend fun markConfirmed(
|
||||
clientRequestId: String,
|
||||
serverPhotoId: String,
|
||||
updatedAt: Long = System.currentTimeMillis(),
|
||||
)
|
||||
|
||||
@Query("DELETE FROM photo_uploads WHERE clientRequestId = :clientRequestId")
|
||||
suspend fun delete(clientRequestId: String)
|
||||
|
||||
@Query("DELETE FROM photo_uploads")
|
||||
suspend fun deleteAll()
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(
|
||||
tableName = "photo_uploads",
|
||||
indices = [
|
||||
Index(value = ["routeId"]),
|
||||
Index(value = ["status"]),
|
||||
],
|
||||
)
|
||||
data class PhotoUploadEntity(
|
||||
@PrimaryKey val clientRequestId: String,
|
||||
val routeId: String,
|
||||
val localPath: String,
|
||||
val source: String,
|
||||
val stage: String = "other",
|
||||
val takenAt: String?,
|
||||
val latitude: Double?,
|
||||
val longitude: Double?,
|
||||
val locationAccuracyMeters: Double?,
|
||||
val mimeType: String,
|
||||
val size: Long,
|
||||
val contentSha256: String,
|
||||
val status: String = PhotoUploadStatus.Pending.storageValue,
|
||||
val progress: Int = 0,
|
||||
val attemptCount: Int = 0,
|
||||
val lastError: String? = null,
|
||||
val serverPhotoId: String? = null,
|
||||
val createdAtEpochMillis: Long = System.currentTimeMillis(),
|
||||
val updatedAtEpochMillis: Long = System.currentTimeMillis(),
|
||||
) {
|
||||
val statusType: PhotoUploadStatus
|
||||
get() = PhotoUploadStatus.fromStorage(status)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import pl.firmatpp.kierowca.data.ApiError
|
||||
import pl.firmatpp.kierowca.data.ApiErrorKind
|
||||
|
||||
object PhotoUploadFailureDetails {
|
||||
fun fromApiError(error: ApiError): String {
|
||||
val type = when (error.kind) {
|
||||
ApiErrorKind.Network -> "błąd komunikacji"
|
||||
ApiErrorKind.Server,
|
||||
ApiErrorKind.RateLimited,
|
||||
ApiErrorKind.Validation,
|
||||
ApiErrorKind.Forbidden,
|
||||
ApiErrorKind.Auth,
|
||||
ApiErrorKind.Conflict,
|
||||
-> "błąd serwera"
|
||||
ApiErrorKind.Unknown -> "błąd aplikacji"
|
||||
}
|
||||
|
||||
return buildString {
|
||||
appendLine("Typ: $type")
|
||||
appendLine("Komunikat: ${error.message}")
|
||||
error.statusCode?.let { appendLine("HTTP: $it") }
|
||||
error.code?.takeIf { it.isNotBlank() }?.let { appendLine("Kod: $it") }
|
||||
error.responseBody
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?.let {
|
||||
appendLine("Odpowiedź serwera:")
|
||||
append(it.take(MAX_RESPONSE_CHARS))
|
||||
if (it.length > MAX_RESPONSE_CHARS) append("...")
|
||||
}
|
||||
}.trim()
|
||||
}
|
||||
|
||||
fun local(message: String): String =
|
||||
"Typ: błąd aplikacji\nKomunikat: $message"
|
||||
|
||||
private const val MAX_RESPONSE_CHARS = 1200
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.work.BackoffPolicy
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.workDataOf
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import pl.firmatpp.kierowca.data.PhotoUploadMetadata
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
import pl.firmatpp.kierowca.data.model.RoutePhotoDto
|
||||
|
||||
class PhotoUploadOutbox(
|
||||
private val context: Context,
|
||||
private val dao: PhotoUploadDao = DriverDatabase.get(context).photoUploadDao(),
|
||||
private val workManager: WorkManager = WorkManager.getInstance(context),
|
||||
) {
|
||||
fun observeVisibleForRoute(routeId: String): Flow<List<PhotoUploadEntity>> =
|
||||
dao.observeVisibleForRoute(routeId)
|
||||
|
||||
fun observeQueuedUploads(): Flow<List<PhotoUploadEntity>> =
|
||||
dao.observeQueuedUploads()
|
||||
|
||||
suspend fun enqueue(routeId: String, uri: Uri, source: String, metadata: PhotoUploadMetadata, stage: String = "other"): PhotoUploadEntity {
|
||||
val clientRequestId = UUID.randomUUID().toString()
|
||||
val mimeType = context.contentResolver.getType(uri) ?: "image/jpeg"
|
||||
val extension = when (mimeType) {
|
||||
"image/png" -> "png"
|
||||
"image/webp" -> "webp"
|
||||
else -> "jpg"
|
||||
}
|
||||
val uploadDir = File(context.filesDir, "photo-upload-outbox").apply { mkdirs() }
|
||||
val localFile = File(uploadDir, "$clientRequestId.$extension")
|
||||
val sha256 = copyAndHash(uri, localFile)
|
||||
val upload = PhotoUploadEntity(
|
||||
clientRequestId = clientRequestId,
|
||||
routeId = routeId,
|
||||
localPath = localFile.absolutePath,
|
||||
source = source,
|
||||
stage = stage,
|
||||
takenAt = metadata.takenAt,
|
||||
latitude = metadata.latitude,
|
||||
longitude = metadata.longitude,
|
||||
locationAccuracyMeters = metadata.locationAccuracyMeters,
|
||||
mimeType = mimeType,
|
||||
size = localFile.length(),
|
||||
contentSha256 = sha256,
|
||||
)
|
||||
|
||||
dao.upsert(upload)
|
||||
enqueueWorker(clientRequestId)
|
||||
|
||||
return upload
|
||||
}
|
||||
|
||||
suspend fun retry(clientRequestId: String) {
|
||||
val existing = dao.find(clientRequestId) ?: return
|
||||
dao.upsert(
|
||||
existing.copy(
|
||||
status = PhotoUploadStatus.Pending.storageValue,
|
||||
progress = 0,
|
||||
lastError = null,
|
||||
updatedAtEpochMillis = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
enqueueWorker(clientRequestId)
|
||||
}
|
||||
|
||||
suspend fun discard(clientRequestId: String) {
|
||||
workManager.cancelUniqueWork(PhotoUploadWorker.uniqueWorkName(clientRequestId))
|
||||
dao.find(clientRequestId)?.let { upload ->
|
||||
File(upload.localPath).delete()
|
||||
dao.delete(upload.clientRequestId)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun discardConfirmedServerPhotos(route: DriverRouteDto) {
|
||||
dao.allRecords()
|
||||
.filter { it.routeId == route.id }
|
||||
.filter { upload ->
|
||||
upload.status == PhotoUploadStatus.Confirmed.storageValue ||
|
||||
route.photos.orEmpty().any { serverPhoto -> serverPhotoConfirmsUpload(upload, serverPhoto) }
|
||||
}
|
||||
.forEach { upload -> discard(upload.clientRequestId) }
|
||||
}
|
||||
|
||||
private fun enqueueWorker(clientRequestId: String) {
|
||||
val request = OneTimeWorkRequestBuilder<PhotoUploadWorker>()
|
||||
.setInputData(workDataOf(PhotoUploadWorker.KEY_CLIENT_REQUEST_ID to clientRequestId))
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
workManager.enqueueUniqueWork(
|
||||
PhotoUploadWorker.uniqueWorkName(clientRequestId),
|
||||
ExistingWorkPolicy.REPLACE,
|
||||
request,
|
||||
)
|
||||
}
|
||||
|
||||
private fun copyAndHash(uri: Uri, target: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
context.contentResolver.openInputStream(uri).use { input ->
|
||||
requireNotNull(input) { "Nie można odczytać zdjęcia." }
|
||||
target.outputStream().use { output ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read == -1) break
|
||||
digest.update(buffer, 0, read)
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
|
||||
internal fun serverPhotoConfirmsUpload(upload: PhotoUploadEntity, serverPhoto: RoutePhotoDto): Boolean =
|
||||
serverPhoto.clientRequestId == upload.clientRequestId && (
|
||||
serverPhoto.contentSha256.isNullOrBlank() ||
|
||||
serverPhoto.contentSha256.equals(upload.contentSha256, ignoreCase = true)
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import pl.firmatpp.kierowca.data.model.PhotoUploadReceiptDto
|
||||
|
||||
object PhotoUploadReceiptVerifier {
|
||||
fun matches(upload: PhotoUploadEntity, receipt: PhotoUploadReceiptDto): Boolean =
|
||||
receipt.clientRequestId == upload.clientRequestId &&
|
||||
receipt.contentSha256.lowercase() == upload.contentSha256.lowercase()
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
enum class PhotoUploadStatus(
|
||||
val storageValue: String,
|
||||
val label: String,
|
||||
val isStoredOnServer: Boolean,
|
||||
) {
|
||||
Pending("PENDING", "Czeka na wysłanie", false),
|
||||
Uploading("UPLOADING", "Wysyłam zdjęcie", false),
|
||||
Verifying("VERIFYING", "Sprawdzam zapis", false),
|
||||
Confirmed("CONFIRMED", "Zapisane", true),
|
||||
FailedRetryable("FAILED_RETRYABLE", "Nie wysłano, ponów", false),
|
||||
FailedPermanent("FAILED_PERMANENT", "Zdjęcie nie zostało zapisane", false),
|
||||
Cancelled("CANCELLED", "Anulowano", false);
|
||||
|
||||
companion object {
|
||||
fun fromStorage(value: String): PhotoUploadStatus =
|
||||
entries.firstOrNull { it.storageValue == value } ?: Pending
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.workDataOf
|
||||
import java.io.File
|
||||
import pl.firmatpp.kierowca.data.ApiErrorKind
|
||||
import pl.firmatpp.kierowca.data.ApiErrorMapper
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.rethrowIfCancellation
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
import pl.firmatpp.kierowca.data.sync.NetworkMonitor
|
||||
|
||||
class PhotoUploadWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters,
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
private val database = DriverDatabase.get(appContext)
|
||||
private val dao = database.photoUploadDao()
|
||||
private val routeActionDao = database.routeActionDao()
|
||||
private val routeActionOutbox = RouteActionOutbox(appContext)
|
||||
private val repository = DriverRepository(appContext)
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) return Result.retry()
|
||||
val clientRequestId = inputData.getString(KEY_CLIENT_REQUEST_ID) ?: return Result.failure()
|
||||
val upload = dao.find(clientRequestId) ?: return Result.failure()
|
||||
val file = File(upload.localPath)
|
||||
|
||||
if (!file.exists()) {
|
||||
val message = "Lokalny plik zdjęcia nie istnieje. Zdjęcie nie zostało zapisane."
|
||||
dao.updateStatus(
|
||||
clientRequestId = clientRequestId,
|
||||
status = PhotoUploadStatus.FailedPermanent.storageValue,
|
||||
progress = 0,
|
||||
lastError = PhotoUploadFailureDetails.local(message),
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
return Result.failure()
|
||||
}
|
||||
|
||||
dao.updateStatus(
|
||||
clientRequestId = clientRequestId,
|
||||
status = PhotoUploadStatus.Uploading.storageValue,
|
||||
progress = 10,
|
||||
lastError = null,
|
||||
attemptIncrement = 1,
|
||||
)
|
||||
setProgress(workDataOf(KEY_PROGRESS to 10))
|
||||
|
||||
return runCatching {
|
||||
setProgress(workDataOf(KEY_PROGRESS to 70))
|
||||
val response = repository.uploadQueuedPhoto(upload)
|
||||
|
||||
dao.updateStatus(
|
||||
clientRequestId = clientRequestId,
|
||||
status = PhotoUploadStatus.Verifying.storageValue,
|
||||
progress = 90,
|
||||
lastError = null,
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
setProgress(workDataOf(KEY_PROGRESS to 90))
|
||||
|
||||
val receipt = response.receipt
|
||||
if (!PhotoUploadReceiptVerifier.matches(upload, receipt)) {
|
||||
error("Serwer nie potwierdził zgodności zdjęcia. Zdjęcie nie zostało zapisane.")
|
||||
}
|
||||
|
||||
dao.markConfirmed(clientRequestId, receipt.serverPhotoId)
|
||||
enqueueRouteActionsWaitingForPhoto(clientRequestId)
|
||||
Result.success()
|
||||
}.getOrElse { throwable ->
|
||||
throwable.rethrowIfCancellation()
|
||||
val error = ApiErrorMapper.map(throwable)
|
||||
AppDiagnostics.reportNonFatal(
|
||||
throwable = throwable,
|
||||
operation = "photo_upload_worker",
|
||||
keys = mapOf(
|
||||
"client_request_id" to clientRequestId,
|
||||
"route_id" to upload.routeId,
|
||||
"api_error_kind" to error.kind.name,
|
||||
"api_error_code" to error.code,
|
||||
"api_status_code" to error.statusCode,
|
||||
"retryable" to error.retryable,
|
||||
),
|
||||
)
|
||||
val status = if (error.retryable) PhotoUploadStatus.FailedRetryable else PhotoUploadStatus.FailedPermanent
|
||||
dao.updateStatus(
|
||||
clientRequestId = clientRequestId,
|
||||
status = status.storageValue,
|
||||
progress = 0,
|
||||
lastError = PhotoUploadFailureDetails.fromApiError(error),
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
|
||||
if (error.retryable && error.kind != ApiErrorKind.Auth) Result.retry() else Result.failure()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun enqueueRouteActionsWaitingForPhoto(clientRequestId: String) {
|
||||
routeActionDao.waitingForPhotosActions()
|
||||
.filter { routeActionReferencesPhotoClientRequest(it, clientRequestId) }
|
||||
.forEach { routeActionOutbox.enqueueWorker(it.clientActionId) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val KEY_CLIENT_REQUEST_ID = "clientRequestId"
|
||||
const val KEY_PROGRESS = "progress"
|
||||
|
||||
fun uniqueWorkName(clientRequestId: String): String = "photo-upload-$clientRequestId"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface RouteActionDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsert(action: RouteActionEntity)
|
||||
|
||||
@Query("SELECT * FROM route_actions WHERE clientActionId = :clientActionId LIMIT 1")
|
||||
suspend fun find(clientActionId: String): RouteActionEntity?
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM route_actions
|
||||
WHERE routeId = :routeId
|
||||
AND action = 'start'
|
||||
AND createdAtEpochMillis < :beforeEpochMillis
|
||||
ORDER BY createdAtEpochMillis DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
)
|
||||
suspend fun latestStartBefore(routeId: String, beforeEpochMillis: Long): RouteActionEntity?
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM route_actions
|
||||
WHERE routeId = :routeId
|
||||
AND action = 'finish'
|
||||
AND createdAtEpochMillis > :afterEpochMillis
|
||||
AND status != 'CONFIRMED'
|
||||
ORDER BY createdAtEpochMillis ASC
|
||||
""",
|
||||
)
|
||||
suspend fun unconfirmedFinishesAfter(routeId: String, afterEpochMillis: Long): List<RouteActionEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM route_actions
|
||||
WHERE routeId = :routeId
|
||||
AND action = 'finish'
|
||||
AND status = 'CONFIRMED'
|
||||
AND createdAtEpochMillis > :afterEpochMillis
|
||||
)
|
||||
""",
|
||||
)
|
||||
suspend fun hasConfirmedFinishAfter(routeId: String, afterEpochMillis: Long): Boolean
|
||||
|
||||
@Query(
|
||||
"""
|
||||
UPDATE route_actions
|
||||
SET status = 'CONFIRMED',
|
||||
lastError = NULL,
|
||||
updatedAtEpochMillis = :updatedAt
|
||||
WHERE routeId = :routeId
|
||||
AND action = 'finish'
|
||||
AND createdAtEpochMillis < :beforeEpochMillis
|
||||
AND status != 'CONFIRMED'
|
||||
""",
|
||||
)
|
||||
suspend fun confirmSupersededFinishes(
|
||||
routeId: String,
|
||||
beforeEpochMillis: Long,
|
||||
updatedAt: Long = System.currentTimeMillis(),
|
||||
)
|
||||
|
||||
@Query("SELECT * FROM route_actions WHERE status != 'CONFIRMED'")
|
||||
suspend fun allUnsent(): List<RouteActionEntity>
|
||||
|
||||
@Query("DELETE FROM route_actions WHERE clientActionId = :clientActionId")
|
||||
suspend fun delete(clientActionId: String)
|
||||
|
||||
@Query("DELETE FROM route_actions")
|
||||
suspend fun deleteAll()
|
||||
|
||||
@Query("DELETE FROM route_actions WHERE status = 'CONFIRMED' AND updatedAtEpochMillis < :beforeEpochMillis")
|
||||
suspend fun pruneConfirmed(beforeEpochMillis: Long)
|
||||
|
||||
@Query("SELECT * FROM route_actions WHERE status = 'WAITING_FOR_PHOTOS'")
|
||||
suspend fun waitingForPhotosActions(): List<RouteActionEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM route_actions
|
||||
WHERE routeId = :routeId
|
||||
AND status IN ('PENDING', 'WAITING_FOR_PHOTOS', 'SYNCING', 'CONFIRMED', 'FAILED_RETRYABLE', 'FAILED_CONFLICT', 'FAILED_PERMANENT')
|
||||
ORDER BY createdAtEpochMillis DESC
|
||||
""",
|
||||
)
|
||||
fun observeUnresolvedForRoute(routeId: String): Flow<List<RouteActionEntity>>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM route_actions
|
||||
WHERE status IN ('PENDING', 'WAITING_FOR_PHOTOS', 'SYNCING', 'FAILED_RETRYABLE', 'FAILED_CONFLICT', 'FAILED_PERMANENT')
|
||||
OR clientActionId IN (
|
||||
SELECT confirmed.clientActionId
|
||||
FROM route_actions AS confirmed
|
||||
WHERE confirmed.status = 'CONFIRMED'
|
||||
AND confirmed.routeId = route_actions.routeId
|
||||
ORDER BY confirmed.createdAtEpochMillis DESC
|
||||
LIMIT 2
|
||||
)
|
||||
ORDER BY createdAtEpochMillis DESC
|
||||
""",
|
||||
)
|
||||
fun observeVisibleActions(): Flow<List<RouteActionEntity>>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
UPDATE route_actions
|
||||
SET status = :status,
|
||||
lastError = :lastError,
|
||||
attemptCount = attemptCount + :attemptIncrement,
|
||||
updatedAtEpochMillis = :updatedAt
|
||||
WHERE clientActionId = :clientActionId
|
||||
""",
|
||||
)
|
||||
suspend fun updateStatus(
|
||||
clientActionId: String,
|
||||
status: String,
|
||||
lastError: String?,
|
||||
attemptIncrement: Int,
|
||||
updatedAt: Long = System.currentTimeMillis(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
object RouteActionStatus {
|
||||
const val Pending = "PENDING"
|
||||
const val WaitingForPhotos = "WAITING_FOR_PHOTOS"
|
||||
const val Syncing = "SYNCING"
|
||||
const val Confirmed = "CONFIRMED"
|
||||
const val FailedRetryable = "FAILED_RETRYABLE"
|
||||
const val FailedPermanent = "FAILED_PERMANENT"
|
||||
const val FailedConflict = "FAILED_CONFLICT"
|
||||
}
|
||||
|
||||
object RouteActionType {
|
||||
const val Start = "start"
|
||||
const val Finish = "finish"
|
||||
}
|
||||
|
||||
@Entity(
|
||||
tableName = "route_actions",
|
||||
indices = [
|
||||
Index(value = ["routeId"]),
|
||||
Index(value = ["status"]),
|
||||
],
|
||||
)
|
||||
data class RouteActionEntity(
|
||||
@PrimaryKey val clientActionId: String,
|
||||
val routeId: String,
|
||||
val action: String,
|
||||
val weight: Double?,
|
||||
val occurredAt: String,
|
||||
val photoClientRequestIdsJson: String,
|
||||
val status: String = RouteActionStatus.Pending,
|
||||
val attemptCount: Int = 0,
|
||||
val lastError: String? = null,
|
||||
val createdAtEpochMillis: Long = System.currentTimeMillis(),
|
||||
val updatedAtEpochMillis: Long = System.currentTimeMillis(),
|
||||
val notes: String? = null,
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.BackoffPolicy
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.workDataOf
|
||||
import com.google.gson.Gson
|
||||
import java.time.Instant
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
class RouteActionOutbox(
|
||||
private val context: Context,
|
||||
private val dao: RouteActionDao = DriverDatabase.get(context).routeActionDao(),
|
||||
private val workManager: WorkManager = WorkManager.getInstance(context),
|
||||
private val gson: Gson = Gson(),
|
||||
) {
|
||||
fun observeUnresolvedForRoute(routeId: String): Flow<List<RouteActionEntity>> =
|
||||
dao.observeUnresolvedForRoute(routeId)
|
||||
|
||||
fun observeVisibleActions(): Flow<List<RouteActionEntity>> =
|
||||
dao.observeVisibleActions()
|
||||
|
||||
suspend fun discard(clientActionId: String) {
|
||||
workManager.cancelUniqueWork(RouteActionWorker.uniqueWorkName(clientActionId))
|
||||
dao.delete(clientActionId)
|
||||
}
|
||||
|
||||
suspend fun retry(clientActionId: String) {
|
||||
val existing = dao.find(clientActionId) ?: return
|
||||
dao.upsert(
|
||||
existing.copy(
|
||||
status = RouteActionStatus.Pending,
|
||||
lastError = null,
|
||||
updatedAtEpochMillis = System.currentTimeMillis(),
|
||||
),
|
||||
)
|
||||
enqueueWorker(clientActionId)
|
||||
}
|
||||
|
||||
suspend fun enqueueStart(
|
||||
routeId: String,
|
||||
loadingWeight: Double?,
|
||||
photoClientRequestIds: List<String>,
|
||||
notes: String? = null,
|
||||
): RouteActionEntity =
|
||||
enqueue(RouteActionType.Start, routeId, loadingWeight, photoClientRequestIds, notes)
|
||||
|
||||
suspend fun enqueueFinish(
|
||||
routeId: String,
|
||||
unloadingWeight: Double?,
|
||||
photoClientRequestIds: List<String>,
|
||||
notes: String? = null,
|
||||
): RouteActionEntity =
|
||||
enqueue(RouteActionType.Finish, routeId, unloadingWeight, photoClientRequestIds, notes)
|
||||
|
||||
private suspend fun enqueue(
|
||||
action: String,
|
||||
routeId: String,
|
||||
weight: Double?,
|
||||
photoClientRequestIds: List<String>,
|
||||
notes: String?,
|
||||
): RouteActionEntity {
|
||||
dao.pruneConfirmed(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
|
||||
val entity = RouteActionEntity(
|
||||
clientActionId = UUID.randomUUID().toString(),
|
||||
routeId = routeId,
|
||||
action = action,
|
||||
weight = weight,
|
||||
occurredAt = Instant.now().toString(),
|
||||
photoClientRequestIdsJson = gson.toJson(photoClientRequestIds.distinct()),
|
||||
notes = notes?.trim()?.takeIf { it.isNotEmpty() },
|
||||
)
|
||||
|
||||
dao.upsert(entity)
|
||||
enqueueWorker(entity.clientActionId)
|
||||
|
||||
return entity
|
||||
}
|
||||
|
||||
fun enqueueWorker(clientActionId: String) {
|
||||
val request = OneTimeWorkRequestBuilder<RouteActionWorker>()
|
||||
.setInputData(workDataOf(RouteActionWorker.KEY_CLIENT_ACTION_ID to clientActionId))
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
workManager.enqueueUniqueWork(
|
||||
RouteActionWorker.uniqueWorkName(clientActionId),
|
||||
ExistingWorkPolicy.REPLACE,
|
||||
request,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import com.google.gson.Gson
|
||||
|
||||
private val routeActionPhotoDependencyGson = Gson()
|
||||
|
||||
fun routeActionReferencesPhotoClientRequest(action: RouteActionEntity, clientRequestId: String): Boolean {
|
||||
val needle = clientRequestId.trim()
|
||||
if (needle.isBlank()) return false
|
||||
|
||||
return runCatching {
|
||||
routeActionPhotoDependencyGson
|
||||
.fromJson(action.photoClientRequestIdsJson, Array<String>::class.java)
|
||||
?.any { it.trim() == needle }
|
||||
?: false
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.google.gson.Gson
|
||||
import pl.firmatpp.kierowca.data.ApiErrorKind
|
||||
import pl.firmatpp.kierowca.data.ApiErrorMapper
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.rethrowIfCancellation
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
import pl.firmatpp.kierowca.data.model.FinishRouteBody
|
||||
import pl.firmatpp.kierowca.data.model.RouteActionResponse
|
||||
import pl.firmatpp.kierowca.data.model.StartRouteBody
|
||||
import pl.firmatpp.kierowca.data.model.driverLifecycleStatus
|
||||
import pl.firmatpp.kierowca.data.sync.DriverSyncRepository
|
||||
import pl.firmatpp.kierowca.data.sync.NetworkMonitor
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
import pl.firmatpp.kierowca.sync.DriverSyncWorker
|
||||
|
||||
class RouteActionWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters,
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
private val database = DriverDatabase.get(appContext)
|
||||
private val dao = database.routeActionDao()
|
||||
private val photoDao = database.photoUploadDao()
|
||||
private val repository = DriverRepository(appContext)
|
||||
private val syncRepository = DriverSyncRepository(appContext, repository)
|
||||
private val gson = Gson()
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) return Result.retry()
|
||||
val clientActionId = inputData.getString(KEY_CLIENT_ACTION_ID) ?: return Result.failure()
|
||||
val action = dao.find(clientActionId) ?: return Result.failure()
|
||||
if (action.status == RouteActionStatus.Confirmed) return Result.success()
|
||||
val startPrerequisite = if (action.action == RouteActionType.Finish) {
|
||||
dao.latestStartBefore(action.routeId, action.createdAtEpochMillis)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
when (routeActionPrerequisiteState(action, startPrerequisite)) {
|
||||
RouteActionPrerequisiteState.Waiting -> {
|
||||
dao.updateStatus(
|
||||
clientActionId = clientActionId,
|
||||
status = RouteActionStatus.Pending,
|
||||
lastError = "Czekam na potwierdzenie rozpoczęcia kursu.",
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
return Result.retry()
|
||||
}
|
||||
RouteActionPrerequisiteState.Failed -> {
|
||||
dao.updateStatus(
|
||||
clientActionId = clientActionId,
|
||||
status = RouteActionStatus.FailedConflict,
|
||||
lastError = "Najpierw trzeba potwierdzić rozpoczęcie kursu.",
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
return Result.failure()
|
||||
}
|
||||
RouteActionPrerequisiteState.Ready -> Unit
|
||||
}
|
||||
val photoClientRequestIds = photoClientRequestIds(action)
|
||||
|
||||
val photoDependencies = photoClientRequestIds.mapNotNull { photoDao.find(it) }
|
||||
val permanentlyFailedPhoto = photoDependencies.firstOrNull { it.status == PhotoUploadStatus.FailedPermanent.storageValue }
|
||||
if (permanentlyFailedPhoto != null) {
|
||||
dao.updateStatus(
|
||||
clientActionId = clientActionId,
|
||||
status = RouteActionStatus.FailedPermanent,
|
||||
lastError = "Wymagane zdjęcie nie zostało wysłane. Popraw zdjęcie i ponów potwierdzenie etapu.",
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
return Result.failure()
|
||||
}
|
||||
|
||||
val waitingForPhotos = photoDependencies.any { it.status != PhotoUploadStatus.Confirmed.storageValue }
|
||||
|
||||
if (waitingForPhotos) {
|
||||
dao.updateStatus(
|
||||
clientActionId = clientActionId,
|
||||
status = RouteActionStatus.WaitingForPhotos,
|
||||
lastError = "Czekam na wysłanie zdjęć etapu.",
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
return Result.retry()
|
||||
}
|
||||
|
||||
dao.updateStatus(
|
||||
clientActionId = clientActionId,
|
||||
status = RouteActionStatus.Syncing,
|
||||
lastError = null,
|
||||
attemptIncrement = 1,
|
||||
)
|
||||
|
||||
return runCatching {
|
||||
val response = sendAction(action, photoClientRequestIds)
|
||||
dao.updateStatus(
|
||||
clientActionId = clientActionId,
|
||||
status = RouteActionStatus.Confirmed,
|
||||
lastError = null,
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
if (action.action == RouteActionType.Finish) {
|
||||
dao.confirmSupersededFinishes(action.routeId, action.createdAtEpochMillis)
|
||||
}
|
||||
syncRepository.cacheConfirmedRoute(response.route, response.route.routeDate)
|
||||
DriverSyncWorker.enqueue(applicationContext, response.route.routeDate, response.route.id)
|
||||
if (action.action == RouteActionType.Start) {
|
||||
val outbox = RouteActionOutbox(applicationContext)
|
||||
dao.unconfirmedFinishesAfter(action.routeId, action.createdAtEpochMillis)
|
||||
.forEach { outbox.enqueueWorker(it.clientActionId) }
|
||||
}
|
||||
Result.success()
|
||||
}.getOrElse { throwable ->
|
||||
throwable.rethrowIfCancellation()
|
||||
val error = ApiErrorMapper.map(throwable)
|
||||
val serverRoute = if (error.kind == ApiErrorKind.Conflict) {
|
||||
runCatching { repository.route(action.routeId).route }.getOrNull()
|
||||
} else {
|
||||
null
|
||||
}
|
||||
AppDiagnostics.reportNonFatal(
|
||||
throwable = throwable,
|
||||
operation = "route_action_worker",
|
||||
keys = mapOf(
|
||||
"client_action_id" to clientActionId,
|
||||
"route_id" to action.routeId,
|
||||
"route_action" to action.action,
|
||||
"api_error_kind" to error.kind.name,
|
||||
"api_error_code" to error.code,
|
||||
"api_status_code" to error.statusCode,
|
||||
"retryable" to error.retryable,
|
||||
"server_route_status" to serverRoute?.driverLifecycleStatus(),
|
||||
),
|
||||
)
|
||||
val supersededByConfirmedFinish = action.action == RouteActionType.Finish &&
|
||||
dao.hasConfirmedFinishAfter(action.routeId, action.createdAtEpochMillis)
|
||||
if (serverRoute != null &&
|
||||
(
|
||||
routeActionMatchesServer(action, photoClientRequestIds, serverRoute) ||
|
||||
routeActionWasSuperseded(action, supersededByConfirmedFinish, serverRoute)
|
||||
)
|
||||
) {
|
||||
dao.updateStatus(
|
||||
clientActionId = clientActionId,
|
||||
status = RouteActionStatus.Confirmed,
|
||||
lastError = null,
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
if (action.action == RouteActionType.Finish) {
|
||||
dao.confirmSupersededFinishes(action.routeId, action.createdAtEpochMillis)
|
||||
}
|
||||
syncRepository.cacheConfirmedRoute(serverRoute, serverRoute.routeDate)
|
||||
DriverSyncWorker.enqueue(applicationContext, serverRoute.routeDate, serverRoute.id)
|
||||
return@getOrElse Result.success()
|
||||
}
|
||||
val status = when {
|
||||
error.kind == ApiErrorKind.Conflict -> RouteActionStatus.FailedConflict
|
||||
error.retryable -> RouteActionStatus.FailedRetryable
|
||||
else -> RouteActionStatus.FailedPermanent
|
||||
}
|
||||
dao.updateStatus(
|
||||
clientActionId = clientActionId,
|
||||
status = status,
|
||||
lastError = routeActionConflictMessage(error.message, serverRoute),
|
||||
attemptIncrement = 0,
|
||||
)
|
||||
|
||||
if (error.retryable && error.kind != ApiErrorKind.Auth) Result.retry() else Result.failure()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun sendAction(action: RouteActionEntity, photoClientRequestIds: List<String>): RouteActionResponse =
|
||||
when (action.action) {
|
||||
RouteActionType.Start -> repository.startRoute(
|
||||
routeId = action.routeId,
|
||||
body = StartRouteBody(
|
||||
clientActionId = action.clientActionId,
|
||||
loadingWeight = action.weight,
|
||||
occurredAt = action.occurredAt,
|
||||
photoClientRequestIds = photoClientRequestIds,
|
||||
loadingNotes = action.notes,
|
||||
),
|
||||
)
|
||||
RouteActionType.Finish -> repository.finishRoute(
|
||||
routeId = action.routeId,
|
||||
body = FinishRouteBody(
|
||||
clientActionId = action.clientActionId,
|
||||
unloadingWeight = action.weight,
|
||||
occurredAt = action.occurredAt,
|
||||
photoClientRequestIds = photoClientRequestIds,
|
||||
unloadingNotes = action.notes,
|
||||
),
|
||||
)
|
||||
else -> error("Nieznana akcja kursu: ${action.action}")
|
||||
}
|
||||
|
||||
private fun photoClientRequestIds(action: RouteActionEntity): List<String> =
|
||||
runCatching {
|
||||
gson.fromJson(action.photoClientRequestIdsJson, Array<String>::class.java)?.toList().orEmpty()
|
||||
}.getOrDefault(emptyList())
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
|
||||
companion object {
|
||||
const val KEY_CLIENT_ACTION_ID = "clientActionId"
|
||||
|
||||
fun uniqueWorkName(clientActionId: String): String = "route-action-$clientActionId"
|
||||
}
|
||||
}
|
||||
|
||||
internal fun routeActionMatchesServer(
|
||||
action: RouteActionEntity,
|
||||
photoClientRequestIds: List<String>,
|
||||
serverRoute: DriverRouteDto,
|
||||
): Boolean {
|
||||
val lifecycleMatches = when (action.action) {
|
||||
RouteActionType.Start -> serverRoute.driverLifecycleStatus() in setOf("W TRAKCIE", "ZAKOŃCZONA")
|
||||
RouteActionType.Finish -> serverRoute.driverLifecycleStatus() == "ZAKOŃCZONA"
|
||||
else -> false
|
||||
}
|
||||
if (!lifecycleMatches) return false
|
||||
|
||||
val serverWeight = when (action.action) {
|
||||
RouteActionType.Start -> serverRoute.loadingWeight
|
||||
RouteActionType.Finish -> serverRoute.unloadingWeight
|
||||
else -> null
|
||||
}
|
||||
val serverNotes = when (action.action) {
|
||||
RouteActionType.Start -> serverRoute.loadingNotes
|
||||
RouteActionType.Finish -> serverRoute.unloadingNotes
|
||||
else -> null
|
||||
}
|
||||
val weightMatches = when {
|
||||
action.weight == null && serverWeight == null -> true
|
||||
action.weight == null || serverWeight == null -> false
|
||||
else -> kotlin.math.abs(action.weight - serverWeight) < 0.0005
|
||||
}
|
||||
val notesMatch = action.notes.normalizedRouteActionNotes() == serverNotes.normalizedRouteActionNotes()
|
||||
val serverPhotoRequestIds = serverRoute.photos
|
||||
.mapNotNull { it.clientRequestId?.trim()?.takeIf(String::isNotBlank) }
|
||||
.toSet()
|
||||
val photosMatch = photoClientRequestIds.all(serverPhotoRequestIds::contains)
|
||||
|
||||
return weightMatches && notesMatch && photosMatch
|
||||
}
|
||||
|
||||
internal fun routeActionWasSuperseded(
|
||||
action: RouteActionEntity,
|
||||
hasConfirmedFinishAfter: Boolean,
|
||||
serverRoute: DriverRouteDto,
|
||||
): Boolean =
|
||||
action.action == RouteActionType.Finish &&
|
||||
hasConfirmedFinishAfter &&
|
||||
serverRoute.driverLifecycleStatus() == "ZAKOŃCZONA"
|
||||
|
||||
internal fun routeActionConflictMessage(message: String, serverRoute: DriverRouteDto?): String {
|
||||
val serverStatus = serverRoute?.driverLifecycleStatus() ?: return message
|
||||
val operationalStatus = serverRoute.operationalStatus
|
||||
?.takeIf(String::isNotBlank)
|
||||
?.let { ", status operacyjny: $it" }
|
||||
.orEmpty()
|
||||
|
||||
return "$message Status kursu na serwerze: $serverStatus$operationalStatus. Dane w telefonie pozostają zachowane."
|
||||
}
|
||||
|
||||
private fun String?.normalizedRouteActionNotes(): String? =
|
||||
this?.trim()?.takeIf(String::isNotEmpty)
|
||||
|
||||
internal enum class RouteActionPrerequisiteState {
|
||||
Ready,
|
||||
Waiting,
|
||||
Failed,
|
||||
}
|
||||
|
||||
internal fun routeActionPrerequisiteState(
|
||||
action: RouteActionEntity,
|
||||
precedingStart: RouteActionEntity?,
|
||||
): RouteActionPrerequisiteState {
|
||||
if (action.action != RouteActionType.Finish || precedingStart == null) {
|
||||
return RouteActionPrerequisiteState.Ready
|
||||
}
|
||||
|
||||
return when (precedingStart.status) {
|
||||
RouteActionStatus.Confirmed -> RouteActionPrerequisiteState.Ready
|
||||
RouteActionStatus.FailedConflict,
|
||||
RouteActionStatus.FailedPermanent,
|
||||
-> RouteActionPrerequisiteState.Failed
|
||||
else -> RouteActionPrerequisiteState.Waiting
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface RoutePointDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsert(point: RoutePointEntity)
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM route_points
|
||||
WHERE routeId = :routeId
|
||||
AND status IN ('PENDING', 'SYNCING', 'FAILED_RETRYABLE')
|
||||
ORDER BY timestamp ASC
|
||||
LIMIT :limit
|
||||
""",
|
||||
)
|
||||
suspend fun pendingForRoute(routeId: String, limit: Int): List<RoutePointEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT COUNT(*) FROM route_points
|
||||
WHERE routeId = :routeId
|
||||
AND status IN ('PENDING', 'SYNCING', 'FAILED_RETRYABLE')
|
||||
""",
|
||||
)
|
||||
suspend fun pendingCount(routeId: String): Int
|
||||
|
||||
@Query("SELECT * FROM route_points WHERE status != 'CONFIRMED'")
|
||||
suspend fun allUnsent(): List<RoutePointEntity>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM route_points WHERE status IN ('PENDING', 'SYNCING', 'FAILED_RETRYABLE')")
|
||||
fun observeUnsentCount(): Flow<Int>
|
||||
|
||||
@Query("SELECT MIN(createdAtEpochMillis) FROM route_points WHERE status IN ('PENDING', 'SYNCING', 'FAILED_RETRYABLE')")
|
||||
fun observeOldestUnsentAt(): Flow<Long?>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
UPDATE route_points
|
||||
SET status = :status,
|
||||
lastError = :lastError,
|
||||
attemptCount = attemptCount + :attemptIncrement,
|
||||
updatedAtEpochMillis = :updatedAt
|
||||
WHERE clientPointId IN (:clientPointIds)
|
||||
""",
|
||||
)
|
||||
suspend fun updateStatus(
|
||||
clientPointIds: List<String>,
|
||||
status: String,
|
||||
lastError: String?,
|
||||
attemptIncrement: Int,
|
||||
updatedAt: Long = System.currentTimeMillis(),
|
||||
)
|
||||
|
||||
@Query("DELETE FROM route_points WHERE clientPointId IN (:clientPointIds)")
|
||||
suspend fun delete(clientPointIds: List<String>)
|
||||
|
||||
@Query("DELETE FROM route_points")
|
||||
suspend fun deleteAll()
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
object RoutePointStatus {
|
||||
const val Pending = "PENDING"
|
||||
const val Syncing = "SYNCING"
|
||||
const val Confirmed = "CONFIRMED"
|
||||
const val FailedRetryable = "FAILED_RETRYABLE"
|
||||
const val FailedPermanent = "FAILED_PERMANENT"
|
||||
}
|
||||
|
||||
@Entity(
|
||||
tableName = "route_points",
|
||||
indices = [
|
||||
Index(value = ["routeId"]),
|
||||
Index(value = ["status"]),
|
||||
Index(value = ["routeId", "status"]),
|
||||
],
|
||||
)
|
||||
data class RoutePointEntity(
|
||||
@PrimaryKey val clientPointId: String,
|
||||
val routeId: String,
|
||||
val driverId: String,
|
||||
val lat: Double,
|
||||
val lon: Double,
|
||||
val accuracy: Double,
|
||||
val speed: Double?,
|
||||
val bearing: Double?,
|
||||
val timestamp: Long,
|
||||
val battery: Int?,
|
||||
val charging: Boolean,
|
||||
val status: String = RoutePointStatus.Pending,
|
||||
val attemptCount: Int = 0,
|
||||
val lastError: String? = null,
|
||||
val createdAtEpochMillis: Long = System.currentTimeMillis(),
|
||||
val updatedAtEpochMillis: Long = System.currentTimeMillis(),
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import android.location.Location
|
||||
import androidx.work.BackoffPolicy
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.workDataOf
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class RoutePointOutbox(
|
||||
private val context: Context,
|
||||
private val dao: RoutePointDao = DriverDatabase.get(context).routePointDao(),
|
||||
private val workManager: WorkManager = WorkManager.getInstance(context),
|
||||
) {
|
||||
suspend fun enqueue(
|
||||
routeId: String,
|
||||
driverId: String,
|
||||
location: Location,
|
||||
battery: Int?,
|
||||
charging: Boolean,
|
||||
uploadDelaySeconds: Long,
|
||||
) {
|
||||
dao.upsert(
|
||||
RoutePointEntity(
|
||||
clientPointId = UUID.randomUUID().toString(),
|
||||
routeId = routeId,
|
||||
driverId = driverId,
|
||||
lat = location.latitude,
|
||||
lon = location.longitude,
|
||||
accuracy = if (location.hasAccuracy()) location.accuracy.toDouble() else 0.0,
|
||||
speed = if (location.hasSpeed()) location.speed.toDouble() else null,
|
||||
bearing = if (location.hasBearing()) location.bearing.toDouble() else null,
|
||||
timestamp = ((location.time.takeIf { it > 0L } ?: System.currentTimeMillis()) / 1000L),
|
||||
battery = battery,
|
||||
charging = charging,
|
||||
),
|
||||
)
|
||||
|
||||
enqueueWorker(routeId, uploadDelaySeconds)
|
||||
}
|
||||
|
||||
fun enqueueWorker(routeId: String, delaySeconds: Long = 20L) {
|
||||
val request = OneTimeWorkRequestBuilder<RoutePointWorker>()
|
||||
.setInputData(workDataOf(RoutePointWorker.KEY_ROUTE_ID to routeId))
|
||||
.setInitialDelay(delaySeconds.coerceAtLeast(0L), TimeUnit.SECONDS)
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
workManager.enqueueUniqueWork(
|
||||
RoutePointWorker.uniqueWorkName(routeId),
|
||||
ExistingWorkPolicy.KEEP,
|
||||
request,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package pl.firmatpp.kierowca.data.upload
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import java.util.UUID
|
||||
import kotlinx.coroutines.delay
|
||||
import pl.firmatpp.kierowca.data.ApiErrorKind
|
||||
import pl.firmatpp.kierowca.data.ApiErrorMapper
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.rethrowIfCancellation
|
||||
import pl.firmatpp.kierowca.data.model.RoutePointBatchBody
|
||||
import pl.firmatpp.kierowca.data.model.RoutePointDto
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
import pl.firmatpp.kierowca.data.sync.NetworkMonitor
|
||||
import pl.firmatpp.kierowca.tracking.ActiveRouteTrackingService
|
||||
|
||||
class RoutePointWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters,
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
private val dao = DriverDatabase.get(appContext).routePointDao()
|
||||
private val repository = DriverRepository(appContext)
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) return Result.retry()
|
||||
val routeId = inputData.getString(KEY_ROUTE_ID) ?: return Result.failure()
|
||||
while (!isStopped) {
|
||||
val points = dao.pendingForRoute(routeId, BATCH_LIMIT)
|
||||
if (points.isEmpty()) return Result.success()
|
||||
|
||||
val pointIds = points.map { it.clientPointId }
|
||||
dao.updateStatus(pointIds, RoutePointStatus.Syncing, null, attemptIncrement = 1)
|
||||
|
||||
val outcome = runCatching {
|
||||
repository.storeRoutePoints(
|
||||
routeId = routeId,
|
||||
body = RoutePointBatchBody(
|
||||
clientBatchId = UUID.randomUUID().toString(),
|
||||
points = points.map { it.toDto() },
|
||||
),
|
||||
)
|
||||
}
|
||||
val response = outcome.getOrNull()
|
||||
if (response != null) {
|
||||
dao.delete(pointIds)
|
||||
if (response.arrived) ActiveRouteTrackingService.markArrived(applicationContext, routeId)
|
||||
if (dao.pendingCount(routeId) == 0) {
|
||||
delay(750L)
|
||||
if (dao.pendingCount(routeId) == 0) return Result.success()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
val throwable = outcome.exceptionOrNull() ?: return Result.retry()
|
||||
throwable.rethrowIfCancellation()
|
||||
val error = ApiErrorMapper.map(throwable)
|
||||
AppDiagnostics.reportNonFatal(
|
||||
throwable = throwable,
|
||||
operation = "route_point_worker",
|
||||
keys = mapOf(
|
||||
"route_id" to routeId,
|
||||
"batch_size" to points.size,
|
||||
"api_error_kind" to error.kind.name,
|
||||
"api_error_code" to error.code,
|
||||
"api_status_code" to error.statusCode,
|
||||
"retryable" to error.retryable,
|
||||
),
|
||||
)
|
||||
if (shouldStopRouteTrackingAfterPointError(error.kind, error.code)) {
|
||||
ActiveRouteTrackingService.stop(applicationContext, routeId)
|
||||
}
|
||||
if (isInactiveRoutePointError(error.code)) {
|
||||
dao.delete(pointIds)
|
||||
continue
|
||||
}
|
||||
|
||||
val status = if (error.retryable) RoutePointStatus.FailedRetryable else RoutePointStatus.FailedPermanent
|
||||
dao.updateStatus(pointIds, status, error.message, attemptIncrement = 0)
|
||||
return if (error.retryable && error.kind != ApiErrorKind.Auth) Result.retry() else Result.failure()
|
||||
}
|
||||
|
||||
return Result.retry()
|
||||
}
|
||||
|
||||
private fun RoutePointEntity.toDto(): RoutePointDto =
|
||||
RoutePointDto(
|
||||
clientPointId = clientPointId,
|
||||
trip_id = routeId,
|
||||
driver_id = driverId,
|
||||
lat = lat,
|
||||
lon = lon,
|
||||
accuracy = accuracy,
|
||||
speed = speed,
|
||||
bearing = bearing,
|
||||
timestamp = timestamp,
|
||||
battery = battery,
|
||||
charging = charging,
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val KEY_ROUTE_ID = "routeId"
|
||||
private const val BATCH_LIMIT = 100
|
||||
|
||||
fun uniqueWorkName(routeId: String): String = "route-point-sync-$routeId"
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isInactiveRoutePointError(code: String?): Boolean = code == "ROUTE_POINTS_INVALID_STATUS"
|
||||
|
||||
internal fun shouldStopRouteTrackingAfterPointError(kind: ApiErrorKind, code: String?): Boolean =
|
||||
kind == ApiErrorKind.Auth || isInactiveRoutePointError(code)
|
||||
@@ -0,0 +1,75 @@
|
||||
package pl.firmatpp.kierowca.diagnostics
|
||||
|
||||
import com.google.firebase.crashlytics.FirebaseCrashlytics
|
||||
|
||||
interface DiagnosticsSink {
|
||||
fun log(message: String)
|
||||
fun setUserId(userId: String)
|
||||
fun setCustomKey(key: String, value: String)
|
||||
fun recordException(throwable: Throwable)
|
||||
}
|
||||
|
||||
object NoOpDiagnosticsSink : DiagnosticsSink {
|
||||
override fun log(message: String) = Unit
|
||||
override fun setUserId(userId: String) = Unit
|
||||
override fun setCustomKey(key: String, value: String) = Unit
|
||||
override fun recordException(throwable: Throwable) = Unit
|
||||
}
|
||||
|
||||
class FirebaseCrashlyticsDiagnosticsSink(
|
||||
private val crashlytics: FirebaseCrashlytics = FirebaseCrashlytics.getInstance(),
|
||||
) : DiagnosticsSink {
|
||||
override fun log(message: String) {
|
||||
crashlytics.log(message)
|
||||
}
|
||||
|
||||
override fun setUserId(userId: String) {
|
||||
crashlytics.setUserId(userId)
|
||||
}
|
||||
|
||||
override fun setCustomKey(key: String, value: String) {
|
||||
crashlytics.setCustomKey(key, value)
|
||||
}
|
||||
|
||||
override fun recordException(throwable: Throwable) {
|
||||
crashlytics.recordException(throwable)
|
||||
}
|
||||
}
|
||||
|
||||
object AppDiagnostics {
|
||||
@Volatile
|
||||
private var sink: DiagnosticsSink = NoOpDiagnosticsSink
|
||||
|
||||
fun installFirebaseCrashlytics() {
|
||||
installSink(FirebaseCrashlyticsDiagnosticsSink())
|
||||
}
|
||||
|
||||
fun installSink(nextSink: DiagnosticsSink) {
|
||||
sink = nextSink
|
||||
}
|
||||
|
||||
fun setDriverId(driverId: String) {
|
||||
sink.setUserId(driverId)
|
||||
}
|
||||
|
||||
fun clearDriverId() {
|
||||
sink.setUserId("")
|
||||
}
|
||||
|
||||
fun log(message: String) {
|
||||
sink.log(message)
|
||||
}
|
||||
|
||||
fun reportNonFatal(
|
||||
throwable: Throwable,
|
||||
operation: String,
|
||||
keys: Map<String, Any?> = emptyMap(),
|
||||
) {
|
||||
sink.setCustomKey("operation", operation)
|
||||
keys.forEach { (key, value) ->
|
||||
sink.setCustomKey(key, value?.toString().orEmpty())
|
||||
}
|
||||
sink.log("non_fatal: $operation: ${throwable.message ?: throwable::class.java.simpleName}")
|
||||
sink.recordException(throwable)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
package pl.firmatpp.kierowca.diagnostics
|
||||
|
||||
import android.Manifest
|
||||
import android.app.ActivityManager
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.Build
|
||||
import android.os.BatteryManager
|
||||
import android.os.Environment
|
||||
import android.os.PowerManager
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkQuery
|
||||
import com.google.firebase.FirebaseApp
|
||||
import com.google.firebase.messaging.FirebaseMessaging
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resume
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import pl.firmatpp.kierowca.BuildConfig
|
||||
import pl.firmatpp.kierowca.data.DeviceInfoProvider
|
||||
import pl.firmatpp.kierowca.data.TokenStore
|
||||
import pl.firmatpp.kierowca.data.upload.DriverDatabase
|
||||
|
||||
data class DiagnosticEntry(
|
||||
val label: String,
|
||||
val value: String,
|
||||
val severity: DiagnosticSeverity = DiagnosticSeverity.Neutral,
|
||||
)
|
||||
|
||||
enum class DiagnosticSeverity { Neutral, Good, Warning, Error }
|
||||
|
||||
data class DiagnosticSection(
|
||||
val title: String,
|
||||
val entries: List<DiagnosticEntry>,
|
||||
)
|
||||
|
||||
data class DiagnosticSnapshot(
|
||||
val generatedAtEpochMillis: Long,
|
||||
val sections: List<DiagnosticSection>,
|
||||
) {
|
||||
fun asPlainText(): String = buildString {
|
||||
appendLine("TPP Kierowca, raport diagnostyczny")
|
||||
appendLine("Wygenerowano: ${Instant.ofEpochMilli(generatedAtEpochMillis)}")
|
||||
sections.forEach { section ->
|
||||
appendLine()
|
||||
appendLine("[${section.title}]")
|
||||
section.entries.forEach { entry -> appendLine("${entry.label}: ${entry.value}") }
|
||||
}
|
||||
appendLine()
|
||||
append("Tokeny są celowo przedstawione jako fingerprinty, raport nie zawiera danych pozwalających przejąć sesję.")
|
||||
}
|
||||
}
|
||||
|
||||
class DiagnosticSnapshotProvider(private val context: Context) {
|
||||
private val database = DriverDatabase.get(context)
|
||||
private val tokenStore = TokenStore(context)
|
||||
|
||||
suspend fun capture(runtimeSections: List<DiagnosticSection>): DiagnosticSnapshot = withContext(Dispatchers.IO) {
|
||||
val token = tokenStore.read()
|
||||
val fcmToken = withTimeoutOrNull(5_000L) { readFirebaseToken() }
|
||||
?: Result.failure(IllegalStateException("timeout po 5 s"))
|
||||
val device = DeviceInfoProvider(context, tokenStore).currentDeviceInfo()
|
||||
val network = currentNetworkEntries()
|
||||
val photos = database.photoUploadDao().allRecords()
|
||||
val dispatchSheets = database.dispatchSheetUploadDao().allRecords()
|
||||
val actions = database.routeActionDao().allUnsent()
|
||||
val points = database.routePointDao().allUnsent()
|
||||
val cacheDao = database.driverCacheDao()
|
||||
val bootstrapCaches = cacheDao.allBootstrapCaches()
|
||||
val routeCaches = cacheDao.allRouteCaches()
|
||||
val syncStates = cacheDao.allSyncStates()
|
||||
val queuedFiles = (photos.map { it.localPath } + dispatchSheets.map { it.localPath }).map(::File)
|
||||
val activeWork = activeWorkInfo()
|
||||
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
|
||||
val firebaseOptions = FirebaseApp.getApps(context).firstOrNull()?.options
|
||||
val databaseFile = context.getDatabasePath("driver-local-outbox.db")
|
||||
|
||||
val sections = buildList {
|
||||
add(
|
||||
DiagnosticSection(
|
||||
"Aplikacja",
|
||||
listOf(
|
||||
DiagnosticEntry("Pakiet", BuildConfig.APPLICATION_ID),
|
||||
DiagnosticEntry("Wersja", "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})"),
|
||||
DiagnosticEntry("Typ buildu", BuildConfig.BUILD_TYPE),
|
||||
DiagnosticEntry("Debug", yesNo(BuildConfig.DEBUG)),
|
||||
DiagnosticEntry("API", BuildConfig.API_BASE_URL),
|
||||
DiagnosticEntry("Reverb URL", BuildConfig.REVERB_WS_BASE_URL),
|
||||
DiagnosticEntry("Reverb app key", secureIdentifierSummary(BuildConfig.REVERB_APP_KEY)),
|
||||
DiagnosticEntry("Firebase App ID", firebaseOptions?.applicationId ?: "brak"),
|
||||
DiagnosticEntry("Firebase Project ID", firebaseOptions?.projectId ?: "brak"),
|
||||
DiagnosticEntry("Firebase Sender ID", firebaseOptions?.gcmSenderId ?: "brak"),
|
||||
DiagnosticEntry("Pierwsza instalacja", Instant.ofEpochMilli(packageInfo.firstInstallTime).toString()),
|
||||
DiagnosticEntry("Ostatnia aktualizacja", Instant.ofEpochMilli(packageInfo.lastUpdateTime).toString()),
|
||||
),
|
||||
),
|
||||
)
|
||||
add(
|
||||
DiagnosticSection(
|
||||
"Sesja i identyfikatory",
|
||||
listOf(
|
||||
DiagnosticEntry("Token sesji", secureIdentifierSummary(token), if (token == null) DiagnosticSeverity.Error else DiagnosticSeverity.Good),
|
||||
DiagnosticEntry("Token FCM", fcmToken.fold(::secureIdentifierSummary) { "Błąd odczytu: ${it.message ?: it::class.java.simpleName}" }),
|
||||
DiagnosticEntry("Device ID", secureIdentifierSummary(device.deviceId)),
|
||||
DiagnosticEntry("Android ID", secureIdentifierSummary(device.androidId)),
|
||||
DiagnosticEntry("Numer seryjny", secureIdentifierSummary(device.serialNumber)),
|
||||
),
|
||||
),
|
||||
)
|
||||
add(
|
||||
DiagnosticSection(
|
||||
"Urządzenie",
|
||||
listOf(
|
||||
DiagnosticEntry("Producent", device.manufacturer.orEmpty().ifBlank { "brak" }),
|
||||
DiagnosticEntry("Marka / model", listOfNotNull(device.brand, device.model).joinToString(" ").ifBlank { "brak" }),
|
||||
DiagnosticEntry("Device / product", listOfNotNull(device.device, device.product).joinToString(" / ").ifBlank { "brak" }),
|
||||
DiagnosticEntry("Android", "${device.androidVersion ?: "?"}, API ${device.sdkInt}"),
|
||||
DiagnosticEntry("Build fingerprint", Build.FINGERPRINT),
|
||||
DiagnosticEntry("Sprzęt / bootloader", "${Build.HARDWARE} / ${Build.BOOTLOADER}"),
|
||||
DiagnosticEntry("ABI", Build.SUPPORTED_ABIS.joinToString()),
|
||||
DiagnosticEntry("Język", context.resources.configuration.locales.toLanguageTags().ifBlank { "brak" }),
|
||||
DiagnosticEntry("Strefa czasowa", java.util.TimeZone.getDefault().id),
|
||||
DiagnosticEntry("Pamięć aplikacji", storageSummary(context.filesDir)),
|
||||
DiagnosticEntry("Pamięć współdzielona", storageSummary(Environment.getExternalStorageDirectory())),
|
||||
DiagnosticEntry("RAM", memorySummary()),
|
||||
DiagnosticEntry("Bateria", batterySummary()),
|
||||
),
|
||||
),
|
||||
)
|
||||
add(DiagnosticSection("Sieć urządzenia", network))
|
||||
add(
|
||||
DiagnosticSection(
|
||||
"Uprawnienia i system",
|
||||
listOf(
|
||||
permissionEntry("Aparat", Manifest.permission.CAMERA),
|
||||
permissionEntry("Lokalizacja dokładna", Manifest.permission.ACCESS_FINE_LOCATION),
|
||||
permissionEntry("Lokalizacja przybliżona", Manifest.permission.ACCESS_COARSE_LOCATION),
|
||||
notificationPermissionEntry(),
|
||||
DiagnosticEntry("Powiadomienia systemowe", yesNo(NotificationManagerCompat.from(context).areNotificationsEnabled())),
|
||||
DiagnosticEntry("Optymalizacja baterii wyłączona", yesNo(isIgnoringBatteryOptimizations())),
|
||||
DiagnosticEntry("Kanały powiadomień", notificationChannelSummary()),
|
||||
),
|
||||
),
|
||||
)
|
||||
addAll(runtimeSections)
|
||||
add(
|
||||
DiagnosticSection(
|
||||
"WorkManager",
|
||||
buildList {
|
||||
add(DiagnosticEntry("Aktywne zadania", activeWork.size.toString(), if (activeWork.isEmpty()) DiagnosticSeverity.Good else DiagnosticSeverity.Warning))
|
||||
activeWork.forEach { work ->
|
||||
add(
|
||||
DiagnosticEntry(
|
||||
work.tags.map { it.substringAfterLast('.') }.sorted().joinToString().ifBlank { work.id.toString() },
|
||||
"${work.state}, próba ${work.runAttemptCount}, id ${work.id}",
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
),
|
||||
)
|
||||
add(
|
||||
DiagnosticSection(
|
||||
"Lokalna kolejka",
|
||||
buildList {
|
||||
add(DiagnosticEntry("Zdjęcia", statusSummary(photos.map { it.status }), queueSeverity(photos.map { it.status })))
|
||||
add(DiagnosticEntry("Karty spedycyjne", statusSummary(dispatchSheets.map { it.status }), queueSeverity(dispatchSheets.map { it.status })))
|
||||
add(DiagnosticEntry("Akcje kursu", statusSummary(actions.map { it.status }), queueSeverity(actions.map { it.status })))
|
||||
add(DiagnosticEntry("Punkty GPS", statusSummary(points.map { it.status }), queueSeverity(points.map { it.status })))
|
||||
add(DiagnosticEntry("Pliki lokalne", "${queuedFiles.count(File::exists)}/${queuedFiles.size} obecnych, ${formatBytes(queuedFiles.filter(File::exists).sumOf(File::length))}"))
|
||||
add(DiagnosticEntry("Brakujące pliki", queuedFiles.filterNot(File::exists).joinToString { it.name }.ifBlank { "brak" }, if (queuedFiles.any { !it.exists() }) DiagnosticSeverity.Error else DiagnosticSeverity.Good))
|
||||
val errors = (photos.mapNotNull { it.lastError } + dispatchSheets.mapNotNull { it.lastError } + actions.mapNotNull { it.lastError } + points.mapNotNull { it.lastError }).distinct()
|
||||
add(DiagnosticEntry("Błędy kolejki", errors.joinToString(" | ").ifBlank { "brak" }, if (errors.isEmpty()) DiagnosticSeverity.Good else DiagnosticSeverity.Warning))
|
||||
},
|
||||
),
|
||||
)
|
||||
add(
|
||||
DiagnosticSection(
|
||||
"Cache i rewizje",
|
||||
buildList {
|
||||
add(DiagnosticEntry("Wersja schematu Room", databaseSchemaVersion().toString()))
|
||||
add(DiagnosticEntry("Plik bazy", "${if (databaseFile.exists()) formatBytes(databaseFile.length()) else "brak"}, ${databaseFile.absolutePath}"))
|
||||
add(DiagnosticEntry("Snapshoty list tras", "${bootstrapCaches.size}: ${bootstrapCaches.joinToString { "${it.date}@v${it.version ?: "?"}" }.ifBlank { "brak" }}"))
|
||||
add(DiagnosticEntry("Snapshoty tras", "${routeCaches.size}: ${routeCaches.joinToString { "${it.routeId}@v${it.version ?: "?"}" }.ifBlank { "brak" }}"))
|
||||
add(DiagnosticEntry("Scope synchronizacji", syncStates.size.toString()))
|
||||
syncStates.forEach { sync ->
|
||||
add(
|
||||
DiagnosticEntry(
|
||||
sync.scope,
|
||||
listOfNotNull(sync.date, sync.routeId).joinToString(" / ").let { target ->
|
||||
"${target.ifBlank { "globalny" }}, v${sync.version}, checksum ${shortFingerprint(sync.checksum)}, zapis ${Instant.ofEpochMilli(sync.syncedAtEpochMillis)}"
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
DiagnosticSnapshot(System.currentTimeMillis(), sections)
|
||||
}
|
||||
|
||||
private fun currentNetworkEntries(): List<DiagnosticEntry> {
|
||||
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val activeNetwork = manager.activeNetwork
|
||||
val capabilities = activeNetwork?.let(manager::getNetworkCapabilities)
|
||||
if (capabilities == null) {
|
||||
return listOf(DiagnosticEntry("Aktywna sieć", "brak", DiagnosticSeverity.Error))
|
||||
}
|
||||
val transports = buildList {
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) add("Wi-Fi")
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) add("sieć komórkowa")
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) add("Ethernet")
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) add("VPN")
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)) add("Bluetooth")
|
||||
}.ifEmpty { listOf("inny") }
|
||||
val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
|
||||
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||
val links = activeNetwork?.let(manager::getLinkProperties)
|
||||
val roaming = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
yesNo(!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING))
|
||||
} else {
|
||||
"niedostępne"
|
||||
}
|
||||
val mtu = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
links?.mtu?.toString() ?: "brak"
|
||||
} else {
|
||||
"niedostępne"
|
||||
}
|
||||
return listOf(
|
||||
DiagnosticEntry("Transport", transports.joinToString()),
|
||||
DiagnosticEntry("Internet zweryfikowany", yesNo(validated), if (validated) DiagnosticSeverity.Good else DiagnosticSeverity.Error),
|
||||
DiagnosticEntry("NET_CAPABILITY_INTERNET", yesNo(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET))),
|
||||
DiagnosticEntry("NET_CAPABILITY_VALIDATED", yesNo(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED))),
|
||||
DiagnosticEntry("Sieć mierzona", yesNo(!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED))),
|
||||
DiagnosticEntry("Roaming", roaming),
|
||||
DiagnosticEntry("Pasmo downstream / upstream", "${capabilities.linkDownstreamBandwidthKbps} / ${capabilities.linkUpstreamBandwidthKbps} kb/s"),
|
||||
DiagnosticEntry("Interfejs", links?.interfaceName ?: "brak"),
|
||||
DiagnosticEntry("Adresy IP", links?.linkAddresses?.joinToString { it.toString() }?.ifBlank { "brak" } ?: "brak"),
|
||||
DiagnosticEntry("DNS", links?.dnsServers?.joinToString { it.hostAddress ?: it.toString() }?.ifBlank { "brak" } ?: "brak"),
|
||||
DiagnosticEntry("MTU", mtu),
|
||||
DiagnosticEntry("Proxy", links?.httpProxy?.toString() ?: "brak"),
|
||||
)
|
||||
}
|
||||
|
||||
private fun activeWorkInfo(): List<WorkInfo> = runCatching {
|
||||
val query = WorkQuery.Builder.fromStates(
|
||||
listOf(WorkInfo.State.ENQUEUED, WorkInfo.State.RUNNING, WorkInfo.State.BLOCKED),
|
||||
).build()
|
||||
WorkManager.getInstance(context).getWorkInfos(query).get(3, TimeUnit.SECONDS)
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
private fun databaseSchemaVersion(): Int = runCatching {
|
||||
database.openHelper.readableDatabase.query("PRAGMA user_version").use { cursor ->
|
||||
if (cursor.moveToFirst()) cursor.getInt(0) else -1
|
||||
}
|
||||
}.getOrDefault(-1)
|
||||
|
||||
private fun memorySummary(): String {
|
||||
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
val info = ActivityManager.MemoryInfo()
|
||||
manager.getMemoryInfo(info)
|
||||
return "wolne ${formatBytes(info.availMem)} z ${formatBytes(info.totalMem)}, niski stan: ${yesNo(info.lowMemory)}"
|
||||
}
|
||||
|
||||
private fun batterySummary(): String {
|
||||
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
|
||||
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).takeIf { it >= 0 }?.let { "$it%" } ?: "brak"
|
||||
return "$level, ładowanie: ${yesNo(manager.isCharging)}"
|
||||
}
|
||||
|
||||
private fun notificationChannelSummary(): String {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return "niewspierane"
|
||||
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
val channels = manager.notificationChannels
|
||||
return if (channels.isEmpty()) "0" else channels.joinToString { "${it.id}:${it.importance}" }
|
||||
}
|
||||
|
||||
private fun permissionEntry(label: String, permission: String): DiagnosticEntry {
|
||||
val granted = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
|
||||
return DiagnosticEntry(label, if (granted) "przyznane" else "brak", if (granted) DiagnosticSeverity.Good else DiagnosticSeverity.Warning)
|
||||
}
|
||||
|
||||
private fun notificationPermissionEntry(): DiagnosticEntry =
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
||||
DiagnosticEntry("Uprawnienie powiadomień", "niewymagane na tej wersji Androida")
|
||||
} else {
|
||||
permissionEntry("Uprawnienie powiadomień", Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
|
||||
private fun isIgnoringBatteryOptimizations(): Boolean {
|
||||
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}
|
||||
|
||||
private suspend fun readFirebaseToken(): Result<String?> = suspendCancellableCoroutine { continuation ->
|
||||
runCatching { FirebaseMessaging.getInstance().token }
|
||||
.onFailure { continuation.resume(Result.failure(it)) }
|
||||
.onSuccess { task ->
|
||||
task.addOnCompleteListener { completed ->
|
||||
if (!continuation.isActive) return@addOnCompleteListener
|
||||
if (completed.isSuccessful) continuation.resume(Result.success(completed.result))
|
||||
else continuation.resume(Result.failure(completed.exception ?: IllegalStateException("Nieznany błąd FCM")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun secureIdentifierSummary(value: String?): String {
|
||||
if (value.isNullOrBlank()) return "brak"
|
||||
val fingerprint = MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.toByteArray())
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
.take(12)
|
||||
val suffix = value.takeLast(4)
|
||||
return "obecny, długość ${value.length}, SHA-256 $fingerprint, końcówka …$suffix"
|
||||
}
|
||||
|
||||
private fun shortFingerprint(value: String): String =
|
||||
MessageDigest.getInstance("SHA-256").digest(value.toByteArray()).joinToString("") { "%02x".format(it) }.take(10)
|
||||
|
||||
private fun statusSummary(statuses: List<String>): String =
|
||||
if (statuses.isEmpty()) "0" else statuses.groupingBy { it }.eachCount().entries.sortedBy { it.key }.joinToString { "${it.key}: ${it.value}" }
|
||||
|
||||
private fun queueSeverity(statuses: List<String>): DiagnosticSeverity = when {
|
||||
statuses.any { it.contains("PERMANENT") || it.contains("CONFLICT") } -> DiagnosticSeverity.Error
|
||||
statuses.any { it.contains("FAILED") } -> DiagnosticSeverity.Warning
|
||||
statuses.isNotEmpty() -> DiagnosticSeverity.Warning
|
||||
else -> DiagnosticSeverity.Good
|
||||
}
|
||||
|
||||
private fun storageSummary(directory: File): String =
|
||||
"wolne ${formatBytes(directory.usableSpace)} z ${formatBytes(directory.totalSpace)}"
|
||||
|
||||
private fun formatBytes(bytes: Long): String {
|
||||
if (bytes < 1024) return "$bytes B"
|
||||
val units = listOf("KB", "MB", "GB", "TB")
|
||||
var value = bytes.toDouble()
|
||||
var unit = -1
|
||||
while (value >= 1024 && unit < units.lastIndex) {
|
||||
value /= 1024
|
||||
unit++
|
||||
}
|
||||
return "%.1f %s".format(java.util.Locale.US, value, units[unit])
|
||||
}
|
||||
|
||||
private fun yesNo(value: Boolean): String = if (value) "tak" else "nie"
|
||||
@@ -2,6 +2,7 @@ package pl.firmatpp.kierowca.domain
|
||||
|
||||
import kotlin.math.roundToInt
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
import pl.firmatpp.kierowca.data.model.driverLifecycleStatus
|
||||
|
||||
data class RouteCardDisplay(
|
||||
val id: String,
|
||||
@@ -32,7 +33,7 @@ object RouteDisplayMapper {
|
||||
destination = route.destinationName.ifBlank { "Cel" },
|
||||
contractLabel = contract,
|
||||
time = route.startsAt.ifBlank { "--:--" },
|
||||
status = route.status,
|
||||
status = route.driverLifecycleStatus(),
|
||||
distanceLabel = distance,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package pl.firmatpp.kierowca.domain
|
||||
|
||||
data class StartupSessionMessage(
|
||||
val title: String,
|
||||
val detail: String,
|
||||
)
|
||||
|
||||
object StartupSessionPolicy {
|
||||
const val OFFLINE_BUTTON_DELAY_SECONDS = 4
|
||||
const val OFFLINE_FALLBACK_SECONDS = 15
|
||||
const val OFFLINE_FALLBACK_MILLIS = OFFLINE_FALLBACK_SECONDS * 1_000L
|
||||
|
||||
fun remainingSeconds(elapsedSeconds: Int): Int =
|
||||
(OFFLINE_FALLBACK_SECONDS - elapsedSeconds).coerceAtLeast(0)
|
||||
|
||||
fun shouldShowOfflineButton(elapsedSeconds: Int, offlineDataAvailable: Boolean): Boolean =
|
||||
offlineDataAvailable && elapsedSeconds >= OFFLINE_BUTTON_DELAY_SECONDS
|
||||
|
||||
fun message(elapsedSeconds: Int): StartupSessionMessage = when {
|
||||
elapsedSeconds < 3 -> StartupSessionMessage(
|
||||
title = "Sprawdzamy zapisaną sesję",
|
||||
detail = "Odczytujemy bezpieczne logowanie kierowcy.",
|
||||
)
|
||||
elapsedSeconds < 6 -> StartupSessionMessage(
|
||||
title = "Potwierdzamy logowanie",
|
||||
detail = "Łączymy telefon z serwerem.",
|
||||
)
|
||||
elapsedSeconds < 9 -> StartupSessionMessage(
|
||||
title = "Pobieramy aktualne kursy",
|
||||
detail = "Synchronizujemy plan dnia i ustawienia aplikacji.",
|
||||
)
|
||||
elapsedSeconds < 12 -> StartupSessionMessage(
|
||||
title = "To trwa dłużej niż zwykle",
|
||||
detail = "Przy słabym zasięgu skorzystamy z danych zapisanych w telefonie.",
|
||||
)
|
||||
else -> StartupSessionMessage(
|
||||
title = "Przygotowujemy tryb offline",
|
||||
detail = "Za chwilę pokażemy ostatnie zapisane kursy.",
|
||||
)
|
||||
}
|
||||
|
||||
fun countdownLabel(elapsedSeconds: Int): String {
|
||||
val remaining = remainingSeconds(elapsedSeconds)
|
||||
|
||||
return if (remaining > 0) {
|
||||
"Tryb offline najpóźniej za $remaining s"
|
||||
} else {
|
||||
"Otwieramy zapisane dane offline"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package pl.firmatpp.kierowca.sync
|
||||
|
||||
import com.google.firebase.messaging.FirebaseMessagingService
|
||||
import com.google.firebase.messaging.RemoteMessage
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.sync.NetworkMonitor
|
||||
|
||||
class DriverFirebaseMessagingService : FirebaseMessagingService() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
override fun onNewToken(token: String) {
|
||||
scope.launch {
|
||||
val repository = DriverRepository(applicationContext)
|
||||
if (repository.hasToken() && NetworkMonitor(applicationContext).isCurrentlyValidated()) {
|
||||
runCatching { repository.storePushToken(token) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessageReceived(message: RemoteMessage) {
|
||||
val data = message.data
|
||||
if (data["type"] == "driver_new_route_notification") {
|
||||
NewRouteNotificationWorker.enqueue(
|
||||
context = applicationContext,
|
||||
routeId = data["routeId"],
|
||||
date = data["date"],
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (data["type"] == "driver_leave_request_decision") {
|
||||
LeaveRequestDecisionNotificationWorker.enqueue(
|
||||
context = applicationContext,
|
||||
leaveRequestId = data["leaveRequestId"],
|
||||
title = data["title"],
|
||||
body = data["body"],
|
||||
)
|
||||
if (!DriverRuntimeSyncState.websocketOwnsForegroundHints()) {
|
||||
DriverSyncWorker.enqueue(
|
||||
context = applicationContext,
|
||||
date = data["date"],
|
||||
routeId = data["routeId"],
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (data["type"] != "driver_sync_hint") return
|
||||
if (DriverRuntimeSyncState.websocketOwnsForegroundHints()) return
|
||||
|
||||
DriverSyncWorker.enqueue(
|
||||
context = applicationContext,
|
||||
date = data["date"],
|
||||
routeId = data["routeId"],
|
||||
scope = data["scope"],
|
||||
version = data["version"]?.toLongOrNull(),
|
||||
checksum = data["checksum"],
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
package pl.firmatpp.kierowca.sync
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParser
|
||||
import java.net.URI
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.model.BroadcastAuthResponse
|
||||
import pl.firmatpp.kierowca.data.model.RealtimeConfigDto
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
import pl.firmatpp.kierowca.data.ApiErrorKind
|
||||
import pl.firmatpp.kierowca.data.ApiErrorMapper
|
||||
|
||||
interface DriverLiveSyncGateway {
|
||||
suspend fun broadcastAuth(socketId: String, channelName: String): BroadcastAuthResponse
|
||||
suspend fun storeRealtimeStatus(status: String, socketId: String?, error: String?)
|
||||
}
|
||||
|
||||
class DriverRepositoryLiveSyncGateway(
|
||||
private val repository: DriverRepository,
|
||||
) : DriverLiveSyncGateway {
|
||||
override suspend fun broadcastAuth(socketId: String, channelName: String): BroadcastAuthResponse =
|
||||
repository.broadcastAuth(socketId, channelName)
|
||||
|
||||
override suspend fun storeRealtimeStatus(status: String, socketId: String?, error: String?) {
|
||||
repository.storeRealtimeStatus(status, socketId, error)
|
||||
}
|
||||
}
|
||||
|
||||
interface LiveWebSocketFactory {
|
||||
fun newWebSocket(url: String, origin: String?, listener: WebSocketListener): WebSocket
|
||||
}
|
||||
|
||||
class OkHttpLiveWebSocketFactory(
|
||||
private val client: OkHttpClient,
|
||||
) : LiveWebSocketFactory {
|
||||
override fun newWebSocket(url: String, origin: String?, listener: WebSocketListener): WebSocket =
|
||||
client.newWebSocket(
|
||||
Request.Builder()
|
||||
.url(url)
|
||||
.header("Origin", origin?.takeIf { it.isNotBlank() } ?: websocketOrigin(url))
|
||||
.build(),
|
||||
listener,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun websocketOrigin(url: String): String =
|
||||
URI(
|
||||
url
|
||||
.replaceFirst("wss://", "https://")
|
||||
.replaceFirst("ws://", "http://")
|
||||
).let { uri ->
|
||||
val defaultPort = (uri.scheme == "https" && uri.port == 443) || (uri.scheme == "http" && uri.port == 80)
|
||||
val port = if (uri.port > 0 && !defaultPort) ":${uri.port}" else ""
|
||||
"${uri.scheme}://${uri.host}$port"
|
||||
}
|
||||
|
||||
enum class LiveSyncConnectionState {
|
||||
Stopped,
|
||||
WaitingForNetwork,
|
||||
Disconnected,
|
||||
Connecting,
|
||||
Subscribing,
|
||||
Connected,
|
||||
}
|
||||
|
||||
data class LiveSyncDiagnostics(
|
||||
val state: LiveSyncConnectionState,
|
||||
val desiredActive: Boolean,
|
||||
val networkAvailable: Boolean,
|
||||
val foregroundActive: Boolean,
|
||||
val configured: Boolean,
|
||||
val socketId: String?,
|
||||
val reconnectAttempt: Int,
|
||||
val messageVersion: Long,
|
||||
val lastMessageAtEpochMillis: Long?,
|
||||
val lastDisconnectReason: String?,
|
||||
)
|
||||
|
||||
class DriverLiveSyncClient(
|
||||
private val gateway: DriverLiveSyncGateway,
|
||||
private val onConnected: () -> Unit,
|
||||
private val onHint: (DriverSyncHint) -> Unit,
|
||||
private val onAuthenticationFailed: () -> Unit = {},
|
||||
private val webSocketFactory: LiveWebSocketFactory = OkHttpLiveWebSocketFactory(defaultOkHttpClient()),
|
||||
private val gson: Gson = Gson(),
|
||||
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO),
|
||||
private val reconnectDelaysMs: List<Long> = DEFAULT_RECONNECT_DELAYS_MS,
|
||||
private val staleTimeoutMs: Long = STALE_TIMEOUT_MS,
|
||||
) {
|
||||
constructor(
|
||||
repository: DriverRepository,
|
||||
onConnected: () -> Unit,
|
||||
onHint: (DriverSyncHint) -> Unit,
|
||||
onAuthenticationFailed: () -> Unit = {},
|
||||
client: OkHttpClient = defaultOkHttpClient(),
|
||||
gson: Gson = Gson(),
|
||||
) : this(
|
||||
gateway = DriverRepositoryLiveSyncGateway(repository),
|
||||
onConnected = onConnected,
|
||||
onHint = onHint,
|
||||
onAuthenticationFailed = onAuthenticationFailed,
|
||||
webSocketFactory = OkHttpLiveWebSocketFactory(client),
|
||||
gson = gson,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val HEARTBEAT_INTERVAL_MS = 10_000L
|
||||
const val STALE_TIMEOUT_MS = 30_000L
|
||||
val DEFAULT_RECONNECT_DELAYS_MS = listOf(1_000L, 2_000L, 5_000L, 10_000L, 30_000L)
|
||||
|
||||
fun defaultOkHttpClient(): OkHttpClient =
|
||||
OkHttpClient.Builder()
|
||||
.pingInterval(15, TimeUnit.SECONDS)
|
||||
.build()
|
||||
}
|
||||
|
||||
private val lock = Any()
|
||||
private var desiredActive: Boolean = false
|
||||
private var networkAvailable: Boolean = true
|
||||
private var state: LiveSyncConnectionState = LiveSyncConnectionState.Stopped
|
||||
private var webSocket: WebSocket? = null
|
||||
private var driverId: String? = null
|
||||
private var realtimeConfig: RealtimeConfigDto? = null
|
||||
private var socketId: String? = null
|
||||
private var reconnectJob: Job? = null
|
||||
private var heartbeatJob: Job? = null
|
||||
private var staleWatchdogJob: Job? = null
|
||||
private var reconnectAttempt: Int = 0
|
||||
private var messageVersion: Long = 0
|
||||
private var lastMessageAtEpochMillis: Long? = null
|
||||
private var lastDisconnectReason: String? = null
|
||||
private var foregroundActive: Boolean = true
|
||||
private val _connectionState = MutableStateFlow(LiveSyncConnectionState.Stopped)
|
||||
val connectionState: StateFlow<LiveSyncConnectionState> = _connectionState.asStateFlow()
|
||||
|
||||
fun diagnostics(): LiveSyncDiagnostics = synchronized(lock) {
|
||||
LiveSyncDiagnostics(
|
||||
state = state,
|
||||
desiredActive = desiredActive,
|
||||
networkAvailable = networkAvailable,
|
||||
foregroundActive = foregroundActive,
|
||||
configured = realtimeConfig != null,
|
||||
socketId = socketId,
|
||||
reconnectAttempt = reconnectAttempt,
|
||||
messageVersion = messageVersion,
|
||||
lastMessageAtEpochMillis = lastMessageAtEpochMillis,
|
||||
lastDisconnectReason = lastDisconnectReason,
|
||||
)
|
||||
}
|
||||
|
||||
private fun updateState(next: LiveSyncConnectionState) {
|
||||
state = next
|
||||
_connectionState.value = next
|
||||
}
|
||||
|
||||
fun start(driverId: String, config: RealtimeConfigDto?) {
|
||||
if (!isConfigUsable(config)) return
|
||||
|
||||
synchronized(lock) {
|
||||
realtimeConfig = config
|
||||
this.driverId = driverId
|
||||
desiredActive = true
|
||||
}
|
||||
ensureConnected()
|
||||
}
|
||||
|
||||
fun ensureConnected() {
|
||||
val shouldConnect = synchronized(lock) {
|
||||
desiredActive &&
|
||||
foregroundActive &&
|
||||
networkAvailable &&
|
||||
state !in setOf(
|
||||
LiveSyncConnectionState.Connecting,
|
||||
LiveSyncConnectionState.Subscribing,
|
||||
LiveSyncConnectionState.Connected,
|
||||
)
|
||||
}
|
||||
if (shouldConnect) connectNow()
|
||||
}
|
||||
|
||||
fun onNetworkAvailable(available: Boolean) {
|
||||
val shouldReconnect = synchronized(lock) {
|
||||
networkAvailable = available
|
||||
if (!available) {
|
||||
reconnectJob?.cancel()
|
||||
reconnectJob = null
|
||||
closeSocketLocked("network_lost")
|
||||
updateState(if (desiredActive) LiveSyncConnectionState.WaitingForNetwork else LiveSyncConnectionState.Stopped)
|
||||
false
|
||||
} else {
|
||||
desiredActive && state == LiveSyncConnectionState.WaitingForNetwork
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldReconnect) connectNow(resetAttempt = true)
|
||||
}
|
||||
|
||||
fun setForeground(active: Boolean) {
|
||||
val shouldConnect = synchronized(lock) {
|
||||
foregroundActive = active
|
||||
if (!active) {
|
||||
reconnectJob?.cancel()
|
||||
reconnectJob = null
|
||||
closeSocketLocked("app_background")
|
||||
updateState(LiveSyncConnectionState.Stopped)
|
||||
false
|
||||
} else {
|
||||
desiredActive && networkAvailable
|
||||
}
|
||||
}
|
||||
if (shouldConnect) connectNow(resetAttempt = true)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
synchronized(lock) {
|
||||
desiredActive = false
|
||||
reconnectJob?.cancel()
|
||||
reconnectJob = null
|
||||
closeSocketLocked("client_stop")
|
||||
driverId = null
|
||||
realtimeConfig = null
|
||||
socketId = null
|
||||
reconnectAttempt = 0
|
||||
updateState(LiveSyncConnectionState.Stopped)
|
||||
}
|
||||
reportRealtimeStatus("disconnected", "client_stop")
|
||||
}
|
||||
|
||||
fun close() {
|
||||
stop()
|
||||
scope.cancel()
|
||||
}
|
||||
|
||||
private fun connectNow(resetAttempt: Boolean = false) {
|
||||
val (wsUrl, origin) = synchronized(lock) {
|
||||
val config = realtimeConfig ?: return
|
||||
val id = driverId ?: return
|
||||
if (!desiredActive || !foregroundActive || !networkAvailable || !isConfigUsable(config)) return
|
||||
if (state == LiveSyncConnectionState.Connecting || state == LiveSyncConnectionState.Subscribing || state == LiveSyncConnectionState.Connected) return
|
||||
|
||||
if (resetAttempt) reconnectAttempt = 0
|
||||
reconnectJob?.cancel()
|
||||
reconnectJob = null
|
||||
socketId = null
|
||||
updateState(LiveSyncConnectionState.Connecting)
|
||||
|
||||
val appKey = config.reverbAppKey.orEmpty()
|
||||
val wsBaseUrl = config.reverbWsBaseUrl.orEmpty()
|
||||
Pair(
|
||||
wsBaseUrl.trimEnd('/') + "/" + appKey + "?protocol=7&client=android&version=1.0&flash=false",
|
||||
config.reverbOrigin,
|
||||
)
|
||||
}
|
||||
|
||||
val socket = webSocketFactory.newWebSocket(
|
||||
wsUrl,
|
||||
origin,
|
||||
object : WebSocketListener() {
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
handleMessage(webSocket, text)
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
handleDisconnect(
|
||||
status = "disconnected",
|
||||
reason = reason.takeIf { it.isNotBlank() } ?: "closed",
|
||||
socket = webSocket,
|
||||
)
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
|
||||
AppDiagnostics.log("realtime_error: ${t.message ?: response?.message ?: "unknown"}")
|
||||
handleDisconnect(
|
||||
status = "error",
|
||||
reason = t.message ?: response?.message ?: "failure",
|
||||
socket = webSocket,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
synchronized(lock) {
|
||||
webSocket = socket
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleMessage(socket: WebSocket, text: String) {
|
||||
val isCurrentSocket = synchronized(lock) {
|
||||
if (webSocket !== socket) {
|
||||
false
|
||||
} else {
|
||||
messageVersion += 1
|
||||
lastMessageAtEpochMillis = System.currentTimeMillis()
|
||||
true
|
||||
}
|
||||
}
|
||||
if (!isCurrentSocket) return
|
||||
|
||||
val root = runCatching { JsonParser.parseString(text).asJsonObject }.getOrNull() ?: return
|
||||
val event = root.string("event") ?: return
|
||||
|
||||
when (event) {
|
||||
"pusher:ping" -> {
|
||||
socket.send("""{"event":"pusher:pong","data":{}}""")
|
||||
restartStaleWatchdogIfConnected()
|
||||
}
|
||||
"pusher:connection_established" -> {
|
||||
val nextSocketId = root.dataObject()?.string("socket_id") ?: return
|
||||
synchronized(lock) {
|
||||
socketId = nextSocketId
|
||||
updateState(LiveSyncConnectionState.Subscribing)
|
||||
}
|
||||
subscribe(socket, nextSocketId)
|
||||
}
|
||||
"pusher_internal:subscription_succeeded" -> {
|
||||
val channel = root.string("channel")
|
||||
val id = synchronized(lock) { driverId } ?: return
|
||||
if (channel == "private-driver-mobile.$id") {
|
||||
synchronized(lock) {
|
||||
reconnectAttempt = 0
|
||||
updateState(LiveSyncConnectionState.Connected)
|
||||
}
|
||||
reportRealtimeStatus("connected")
|
||||
startHeartbeat()
|
||||
startStaleWatchdog()
|
||||
onConnected()
|
||||
}
|
||||
}
|
||||
"DriverMobileSyncHint" -> {
|
||||
restartStaleWatchdogIfConnected()
|
||||
parseHint(root.dataObject())?.let(onHint)
|
||||
}
|
||||
else -> restartStaleWatchdogIfConnected()
|
||||
}
|
||||
}
|
||||
|
||||
private fun subscribe(socket: WebSocket, socketId: String) {
|
||||
val id = synchronized(lock) { driverId } ?: return
|
||||
val channels = listOf("private-driver-mobile.$id", "private-driver-mobile.0")
|
||||
|
||||
scope.launch {
|
||||
runCatching {
|
||||
channels.forEach { channel ->
|
||||
val auth = gateway.broadcastAuth(socketId, channel).auth
|
||||
if (!isCurrentSocket(socket)) return@launch
|
||||
val payload = mapOf(
|
||||
"event" to "pusher:subscribe",
|
||||
"data" to mapOf(
|
||||
"channel" to channel,
|
||||
"auth" to auth,
|
||||
),
|
||||
)
|
||||
check(socket.send(gson.toJson(payload))) { "WebSocket send returned false" }
|
||||
}
|
||||
}.onFailure { throwable ->
|
||||
AppDiagnostics.log("realtime_subscription_error: ${throwable.message ?: throwable::class.java.simpleName}")
|
||||
if (ApiErrorMapper.map(throwable).kind == ApiErrorKind.Auth) {
|
||||
handleAuthenticationFailure(socket)
|
||||
return@onFailure
|
||||
}
|
||||
socket.close(1000, "subscription_failed")
|
||||
handleDisconnect("error", "subscription_failed", socket)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleDisconnect(status: String, reason: String?, socket: WebSocket? = null) {
|
||||
val shouldSchedule = synchronized(lock) {
|
||||
if (socket != null && webSocket !== socket) return
|
||||
|
||||
stopHeartbeatLocked()
|
||||
stopStaleWatchdogLocked()
|
||||
webSocket = null
|
||||
socketId = null
|
||||
lastDisconnectReason = reason
|
||||
|
||||
if (!desiredActive) {
|
||||
updateState(LiveSyncConnectionState.Stopped)
|
||||
false
|
||||
} else if (!networkAvailable) {
|
||||
updateState(LiveSyncConnectionState.WaitingForNetwork)
|
||||
false
|
||||
} else {
|
||||
updateState(LiveSyncConnectionState.Disconnected)
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
reportRealtimeStatus(status, reason)
|
||||
if (shouldSchedule) scheduleReconnect()
|
||||
}
|
||||
|
||||
private fun scheduleReconnect() {
|
||||
val delayMs = synchronized(lock) {
|
||||
if (!desiredActive || !foregroundActive || !networkAvailable || state == LiveSyncConnectionState.Stopped) return
|
||||
if (reconnectJob?.isActive == true) return
|
||||
val delay = reconnectDelaysMs.getOrElse(reconnectAttempt) { reconnectDelaysMs.last() }
|
||||
reconnectAttempt += 1
|
||||
delay
|
||||
}
|
||||
|
||||
reconnectJob = scope.launch {
|
||||
delay(delayMs)
|
||||
connectNow()
|
||||
}
|
||||
}
|
||||
|
||||
private fun startHeartbeat() {
|
||||
synchronized(lock) {
|
||||
heartbeatJob?.cancel()
|
||||
heartbeatJob = scope.launch {
|
||||
while (true) {
|
||||
reportRealtimeStatus("connected")
|
||||
delay(HEARTBEAT_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun startStaleWatchdog() {
|
||||
synchronized(lock) {
|
||||
stopStaleWatchdogLocked()
|
||||
val observedVersion = messageVersion
|
||||
staleWatchdogJob = scope.launch {
|
||||
delay(staleTimeoutMs)
|
||||
val socketToClose = synchronized(lock) {
|
||||
if (state == LiveSyncConnectionState.Connected && messageVersion == observedVersion) {
|
||||
webSocket
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
if (socketToClose != null) {
|
||||
socketToClose.close(1001, "stale_connection")
|
||||
handleDisconnect("error", "stale_connection", socketToClose)
|
||||
ensureConnected()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun restartStaleWatchdogIfConnected() {
|
||||
val connected = synchronized(lock) { state == LiveSyncConnectionState.Connected }
|
||||
if (connected) startStaleWatchdog()
|
||||
}
|
||||
|
||||
private fun isCurrentSocket(socket: WebSocket): Boolean =
|
||||
synchronized(lock) { webSocket === socket }
|
||||
|
||||
private fun closeSocketLocked(reason: String) {
|
||||
stopHeartbeatLocked()
|
||||
stopStaleWatchdogLocked()
|
||||
webSocket?.close(1000, reason)
|
||||
webSocket = null
|
||||
socketId = null
|
||||
}
|
||||
|
||||
private fun stopHeartbeatLocked() {
|
||||
heartbeatJob?.cancel()
|
||||
heartbeatJob = null
|
||||
}
|
||||
|
||||
private fun stopStaleWatchdogLocked() {
|
||||
staleWatchdogJob?.cancel()
|
||||
staleWatchdogJob = null
|
||||
}
|
||||
|
||||
private fun reportRealtimeStatus(status: String, error: String? = null) {
|
||||
scope.launch {
|
||||
runCatching {
|
||||
gateway.storeRealtimeStatus(status, socketId, error)
|
||||
}.onFailure { throwable ->
|
||||
if (ApiErrorMapper.map(throwable).kind == ApiErrorKind.Auth) handleAuthenticationFailure()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleAuthenticationFailure(socket: WebSocket? = null) {
|
||||
val notify = synchronized(lock) {
|
||||
if (socket != null && webSocket !== socket) return
|
||||
val wasActive = desiredActive
|
||||
desiredActive = false
|
||||
reconnectJob?.cancel()
|
||||
reconnectJob = null
|
||||
closeSocketLocked("authentication_failed")
|
||||
updateState(LiveSyncConnectionState.Stopped)
|
||||
wasActive
|
||||
}
|
||||
if (notify) onAuthenticationFailed()
|
||||
}
|
||||
|
||||
private fun isConfigUsable(config: RealtimeConfigDto?): Boolean =
|
||||
config?.reverbEnabled == true &&
|
||||
!config.reverbAppKey.isNullOrBlank() &&
|
||||
!config.reverbWsBaseUrl.isNullOrBlank()
|
||||
|
||||
private fun parseHint(data: JsonObject?): DriverSyncHint? {
|
||||
if (data == null || data.string("type") != "driver_sync_hint") return null
|
||||
|
||||
return DriverSyncHint(
|
||||
scope = data.string("scope") ?: return null,
|
||||
date = data.string("date"),
|
||||
routeId = data.string("routeId"),
|
||||
version = data.string("version")?.toLongOrNull() ?: data.get("version")?.asLong ?: return null,
|
||||
checksum = data.string("checksum") ?: return null,
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject.dataObject(): JsonObject? {
|
||||
val data = get("data") ?: return null
|
||||
return if (data.isJsonObject) data.asJsonObject else runCatching { JsonParser.parseString(data.asString).asJsonObject }.getOrNull()
|
||||
}
|
||||
|
||||
private fun JsonObject.string(name: String): String? =
|
||||
get(name)?.takeIf { !it.isJsonNull }?.asString
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package pl.firmatpp.kierowca.sync
|
||||
|
||||
object DriverRuntimeSyncState {
|
||||
@Volatile var foreground: Boolean = false
|
||||
@Volatile var realtimeConnected: Boolean = false
|
||||
|
||||
fun websocketOwnsForegroundHints(): Boolean = foreground && realtimeConnected
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package pl.firmatpp.kierowca.sync
|
||||
|
||||
import pl.firmatpp.kierowca.data.model.SyncScopeDto
|
||||
|
||||
data class DriverSyncHint(
|
||||
val scope: String,
|
||||
val date: String?,
|
||||
val routeId: String?,
|
||||
val version: Long,
|
||||
val checksum: String,
|
||||
) {
|
||||
fun asScope(): SyncScopeDto =
|
||||
SyncScopeDto(
|
||||
scope = scope,
|
||||
date = date,
|
||||
routeId = routeId,
|
||||
version = version,
|
||||
checksum = checksum,
|
||||
computedAt = "",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package pl.firmatpp.kierowca.sync
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.BackoffPolicy
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.workDataOf
|
||||
import java.util.concurrent.TimeUnit
|
||||
import pl.firmatpp.kierowca.data.ApiErrorKind
|
||||
import pl.firmatpp.kierowca.data.ApiErrorMapper
|
||||
import pl.firmatpp.kierowca.data.rethrowIfCancellation
|
||||
import pl.firmatpp.kierowca.data.sync.DriverSyncRepository
|
||||
import pl.firmatpp.kierowca.data.sync.NetworkMonitor
|
||||
import pl.firmatpp.kierowca.data.model.SyncScopeDto
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
|
||||
class DriverSyncWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters,
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
private val syncRepository = DriverSyncRepository(appContext)
|
||||
|
||||
override suspend fun doWork(): Result =
|
||||
if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) Result.retry() else
|
||||
runCatching {
|
||||
val date = inputData.getString(KEY_DATE)
|
||||
val routeId = inputData.getString(KEY_ROUTE_ID)
|
||||
val hintedScope = inputData.getString(KEY_SCOPE)?.let { scope ->
|
||||
val version = inputData.getLong(KEY_VERSION, -1L)
|
||||
val checksum = inputData.getString(KEY_CHECKSUM)
|
||||
if (version >= 0L && !checksum.isNullOrBlank()) {
|
||||
SyncScopeDto(scope, date, routeId, version, checksum, computedAt = "")
|
||||
} else null
|
||||
}
|
||||
if (hintedScope != null && !syncRepository.shouldRefresh(hintedScope)) {
|
||||
return@runCatching Result.success()
|
||||
}
|
||||
val response = syncRepository.fetchSyncState(date, routeId)
|
||||
var refreshed = false
|
||||
|
||||
response.scopes.forEach { scope ->
|
||||
if (syncRepository.shouldRefresh(scope)) {
|
||||
when (scope.scope) {
|
||||
DriverSyncRepository.SCOPE_ROUTES -> {
|
||||
syncRepository.bootstrap(scope.date ?: date)
|
||||
refreshed = true
|
||||
}
|
||||
DriverSyncRepository.SCOPE_ROUTE_DETAIL -> {
|
||||
val id = scope.routeId ?: routeId
|
||||
if (!id.isNullOrBlank()) {
|
||||
syncRepository.route(id)
|
||||
refreshed = true
|
||||
}
|
||||
}
|
||||
DriverSyncRepository.SCOPE_SETTINGS,
|
||||
DriverSyncRepository.SCOPE_DISPATCH_SHEET -> {
|
||||
syncRepository.bootstrap(scope.date ?: date)
|
||||
refreshed = true
|
||||
}
|
||||
DriverSyncRepository.SCOPE_LEAVE_REQUESTS -> {
|
||||
syncRepository.saveSyncStates(response)
|
||||
refreshed = true
|
||||
}
|
||||
DriverSyncRepository.SCOPE_LEAVE_CALENDAR -> {
|
||||
syncRepository.saveSyncStates(response)
|
||||
refreshed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!refreshed) {
|
||||
syncRepository.saveSyncStates(response)
|
||||
}
|
||||
|
||||
Result.success()
|
||||
}.getOrElse { throwable ->
|
||||
throwable.rethrowIfCancellation()
|
||||
val error = ApiErrorMapper.map(throwable)
|
||||
AppDiagnostics.reportNonFatal(
|
||||
throwable = throwable,
|
||||
operation = "driver_sync_worker",
|
||||
keys = mapOf(
|
||||
"date" to inputData.getString(KEY_DATE),
|
||||
"route_id" to inputData.getString(KEY_ROUTE_ID),
|
||||
"api_error_kind" to error.kind.name,
|
||||
"api_error_code" to error.code,
|
||||
"api_status_code" to error.statusCode,
|
||||
"retryable" to error.retryable,
|
||||
),
|
||||
)
|
||||
if (error.retryable && error.kind != ApiErrorKind.Auth) Result.retry() else Result.failure()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val KEY_DATE = "date"
|
||||
private const val KEY_ROUTE_ID = "routeId"
|
||||
private const val KEY_SCOPE = "scope"
|
||||
private const val KEY_VERSION = "version"
|
||||
private const val KEY_CHECKSUM = "checksum"
|
||||
|
||||
fun enqueue(
|
||||
context: Context,
|
||||
date: String?,
|
||||
routeId: String?,
|
||||
scope: String? = null,
|
||||
version: Long? = null,
|
||||
checksum: String? = null,
|
||||
) {
|
||||
val request = OneTimeWorkRequestBuilder<DriverSyncWorker>()
|
||||
.setInputData(workDataOf(
|
||||
KEY_DATE to date,
|
||||
KEY_ROUTE_ID to routeId,
|
||||
KEY_SCOPE to scope,
|
||||
KEY_VERSION to version,
|
||||
KEY_CHECKSUM to checksum,
|
||||
))
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||
listOf("driver-sync", scope ?: "all", date ?: "-", routeId ?: "-").joinToString("-"),
|
||||
ExistingWorkPolicy.KEEP,
|
||||
request,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package pl.firmatpp.kierowca.sync
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.workDataOf
|
||||
import pl.firmatpp.kierowca.MainActivity
|
||||
import pl.firmatpp.kierowca.R
|
||||
|
||||
class LeaveRequestDecisionNotificationWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters,
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
override suspend fun doWork(): Result {
|
||||
val leaveRequestId = inputData.getString(KEY_LEAVE_REQUEST_ID)?.takeIf(String::isNotBlank)
|
||||
?: return Result.success()
|
||||
|
||||
if (!canShowNotifications(applicationContext)) {
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
createChannel(applicationContext)
|
||||
val title = inputData.getString(KEY_TITLE)?.takeIf(String::isNotBlank) ?: "Decyzja w sprawie urlopu"
|
||||
val body = inputData.getString(KEY_BODY)?.takeIf(String::isNotBlank) ?: "Status wniosku urlopowego został zmieniony."
|
||||
val intent = Intent(applicationContext, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||||
putExtra(MainActivity.EXTRA_LEAVE_REQUEST_ID, leaveRequestId)
|
||||
}
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
applicationContext,
|
||||
leaveRequestId.hashCode(),
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentTitle(title)
|
||||
.setContentText(body)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_STATUS)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.build()
|
||||
|
||||
try {
|
||||
NotificationManagerCompat.from(applicationContext).notify(leaveRequestId.hashCode(), notification)
|
||||
} catch (_: SecurityException) {
|
||||
return Result.success()
|
||||
}
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
private fun createChannel(context: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Wnioski urlopowe",
|
||||
NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "Powiadomienia o decyzjach w sprawie wniosków urlopowych."
|
||||
}
|
||||
context.getSystemService(NotificationManager::class.java)?.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private fun canShowNotifications(context: Context): Boolean {
|
||||
val hasRuntimePermission = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
return hasRuntimePermission && NotificationManagerCompat.from(context).areNotificationsEnabled()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "leave_request_decisions"
|
||||
private const val KEY_LEAVE_REQUEST_ID = "leaveRequestId"
|
||||
private const val KEY_TITLE = "title"
|
||||
private const val KEY_BODY = "body"
|
||||
|
||||
fun enqueue(context: Context, leaveRequestId: String?, title: String?, body: String?) {
|
||||
if (leaveRequestId.isNullOrBlank()) return
|
||||
|
||||
val request = OneTimeWorkRequestBuilder<LeaveRequestDecisionNotificationWorker>()
|
||||
.setInputData(
|
||||
workDataOf(
|
||||
KEY_LEAVE_REQUEST_ID to leaveRequestId,
|
||||
KEY_TITLE to title,
|
||||
KEY_BODY to body,
|
||||
),
|
||||
)
|
||||
.build()
|
||||
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||
"driver-leave-request-decision-$leaveRequestId",
|
||||
ExistingWorkPolicy.REPLACE,
|
||||
request,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package pl.firmatpp.kierowca.sync
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.util.Locale
|
||||
import java.time.DayOfWeek
|
||||
import java.time.format.DateTimeFormatter
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
|
||||
object NewRouteNotificationFormatter {
|
||||
private val polishLocale = Locale("pl", "PL")
|
||||
private val monthFormatter = DateTimeFormatter.ofPattern("d MMMM", polishLocale)
|
||||
|
||||
fun title(routeDate: String?, today: LocalDate = LocalDate.now()): String {
|
||||
val label = humanDate(routeDate, today) ?: return "Nowy kurs"
|
||||
|
||||
return "Nowy kurs: $label"
|
||||
}
|
||||
|
||||
fun collapsedText(route: DriverRouteDto): String =
|
||||
listOf(route.originName, route.destinationName)
|
||||
.filter(String::isNotBlank)
|
||||
.joinToString(" → ")
|
||||
.ifBlank { route.relationLabel }
|
||||
.let { relation ->
|
||||
val contract = route.contractName?.takeIf(String::isNotBlank) ?: route.contractCode
|
||||
if (contract.isNullOrBlank()) relation else "$relation · $contract"
|
||||
}
|
||||
|
||||
fun expandedText(route: DriverRouteDto): String {
|
||||
val contract = route.contractName?.takeIf(String::isNotBlank) ?: route.contractCode ?: "Brak nazwy kontraktu"
|
||||
|
||||
return listOf(
|
||||
"Skąd: ${route.originName.ifBlank { "Nie podano" }}",
|
||||
"Dokąd: ${route.destinationName.ifBlank { "Nie podano" }}",
|
||||
"Kontrakt: $contract",
|
||||
).joinToString("\n")
|
||||
}
|
||||
|
||||
private fun humanDate(routeDate: String?, today: LocalDate): String? {
|
||||
val date = runCatching { routeDate?.let(LocalDate::parse) }.getOrNull() ?: return null
|
||||
|
||||
return when {
|
||||
date == today -> "dzisiaj"
|
||||
date == today.plusDays(1) -> "jutro"
|
||||
date.isAfter(today.plusDays(1)) && !date.isAfter(today.plusDays(7)) ->
|
||||
"w ${weekdayAccusative(date.dayOfWeek)}"
|
||||
else -> date.format(monthFormatter).lowercase(polishLocale)
|
||||
}
|
||||
}
|
||||
|
||||
private fun weekdayAccusative(dayOfWeek: DayOfWeek): String =
|
||||
when (dayOfWeek) {
|
||||
DayOfWeek.MONDAY -> "poniedziałek"
|
||||
DayOfWeek.TUESDAY -> "wtorek"
|
||||
DayOfWeek.WEDNESDAY -> "środę"
|
||||
DayOfWeek.THURSDAY -> "czwartek"
|
||||
DayOfWeek.FRIDAY -> "piątek"
|
||||
DayOfWeek.SATURDAY -> "sobotę"
|
||||
DayOfWeek.SUNDAY -> "niedzielę"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package pl.firmatpp.kierowca.sync
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.work.BackoffPolicy
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.workDataOf
|
||||
import java.util.concurrent.TimeUnit
|
||||
import pl.firmatpp.kierowca.MainActivity
|
||||
import pl.firmatpp.kierowca.R
|
||||
import pl.firmatpp.kierowca.data.ApiErrorKind
|
||||
import pl.firmatpp.kierowca.data.ApiErrorMapper
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.rethrowIfCancellation
|
||||
import pl.firmatpp.kierowca.data.sync.NetworkMonitor
|
||||
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
|
||||
import retrofit2.HttpException
|
||||
|
||||
class NewRouteNotificationWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters,
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
private val repository = DriverRepository(appContext)
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) return Result.retry()
|
||||
val routeId = inputData.getString(KEY_ROUTE_ID)?.takeIf(String::isNotBlank) ?: return Result.success()
|
||||
|
||||
return runCatching {
|
||||
val route = repository.route(routeId).route
|
||||
if (!canShowNotifications(applicationContext)) {
|
||||
return@runCatching Result.success()
|
||||
}
|
||||
|
||||
createChannel(applicationContext)
|
||||
val contentTitle = NewRouteNotificationFormatter.title(route.routeDate ?: inputData.getString(KEY_DATE))
|
||||
val contentText = NewRouteNotificationFormatter.collapsedText(route)
|
||||
val expandedText = NewRouteNotificationFormatter.expandedText(route)
|
||||
val intent = Intent(applicationContext, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||||
putExtra(MainActivity.EXTRA_ROUTE_ID, route.id)
|
||||
}
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
applicationContext,
|
||||
route.id.hashCode(),
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentTitle(contentTitle)
|
||||
.setContentText(contentText)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(expandedText))
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_REMINDER)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.build()
|
||||
|
||||
try {
|
||||
NotificationManagerCompat.from(applicationContext).notify(route.id.hashCode(), notification)
|
||||
} catch (_: SecurityException) {
|
||||
return@runCatching Result.success()
|
||||
}
|
||||
Result.success()
|
||||
}.getOrElse { throwable ->
|
||||
throwable.rethrowIfCancellation()
|
||||
if (throwable is HttpException && throwable.code() == 404) {
|
||||
Result.success()
|
||||
} else {
|
||||
val error = ApiErrorMapper.map(throwable)
|
||||
AppDiagnostics.reportNonFatal(
|
||||
throwable = throwable,
|
||||
operation = "new_route_notification_worker",
|
||||
keys = mapOf(
|
||||
"route_id" to routeId,
|
||||
"api_error_kind" to error.kind.name,
|
||||
"api_error_code" to error.code,
|
||||
"api_status_code" to error.statusCode,
|
||||
"retryable" to error.retryable,
|
||||
),
|
||||
)
|
||||
if (error.retryable && error.kind != ApiErrorKind.Auth) Result.retry() else Result.success()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createChannel(context: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Nowe kursy",
|
||||
NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "Powiadomienia o nowych kursach dodanych przez spedytora."
|
||||
}
|
||||
context.getSystemService(NotificationManager::class.java)?.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private fun canShowNotifications(context: Context): Boolean {
|
||||
val hasRuntimePermission = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
return hasRuntimePermission && NotificationManagerCompat.from(context).areNotificationsEnabled()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "new_routes"
|
||||
private const val KEY_ROUTE_ID = "routeId"
|
||||
private const val KEY_DATE = "date"
|
||||
|
||||
fun enqueue(context: Context, routeId: String?, date: String?) {
|
||||
if (routeId.isNullOrBlank()) return
|
||||
|
||||
val request = OneTimeWorkRequestBuilder<NewRouteNotificationWorker>()
|
||||
.setInputData(workDataOf(KEY_ROUTE_ID to routeId, KEY_DATE to date))
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||
"driver-new-route-notification-$routeId",
|
||||
ExistingWorkPolicy.REPLACE,
|
||||
request,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
package pl.firmatpp.kierowca.tracking
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import java.util.Locale
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.firmatpp.kierowca.MainActivity
|
||||
import pl.firmatpp.kierowca.R
|
||||
import pl.firmatpp.kierowca.data.model.DriverDto
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
import pl.firmatpp.kierowca.data.upload.RoutePointOutbox
|
||||
|
||||
class ActiveRouteTrackingService : Service(), LocationListener {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private lateinit var locationManager: LocationManager
|
||||
private lateinit var routePointOutbox: RoutePointOutbox
|
||||
|
||||
private var routeId: String? = null
|
||||
private var driverId: String? = null
|
||||
private var routeLabel: String = "Kurs aktywny"
|
||||
private var destinationLat: Double? = null
|
||||
private var destinationLon: Double? = null
|
||||
private var totalDistanceMeters: Double? = null
|
||||
private var progressEnabled: Boolean = true
|
||||
private var arrived: Boolean = false
|
||||
private var lastRemainingMeters: Float? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
locationManager = getSystemService(LocationManager::class.java)
|
||||
routePointOutbox = RoutePointOutbox(this)
|
||||
ensureNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action != ACTION_STOP && !hasLocationPermission()) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
when (intent?.action) {
|
||||
ACTION_STOP -> {
|
||||
val requestedRouteId = intent.getStringExtra(EXTRA_ROUTE_ID)
|
||||
if (!requestedRouteId.isNullOrBlank() && routeId != requestedRouteId) {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_MARK_ARRIVED -> {
|
||||
val id = intent.getStringExtra(EXTRA_ROUTE_ID)
|
||||
if (!id.isNullOrBlank() && (routeId == null || id == routeId)) {
|
||||
routeId = id
|
||||
arrived = true
|
||||
runCatching { locationManager.removeUpdates(this) }
|
||||
if (!startForegroundCompat(buildNotification())) {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
else -> {
|
||||
val nextRouteId = intent?.getStringExtra(EXTRA_ROUTE_ID) ?: routeId
|
||||
val nextDriverId = intent?.getStringExtra(EXTRA_DRIVER_ID) ?: driverId
|
||||
if (nextRouteId.isNullOrBlank() || nextDriverId.isNullOrBlank()) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val routeChanged = nextRouteId != routeId
|
||||
routeId = nextRouteId
|
||||
driverId = nextDriverId
|
||||
getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString(ACTIVE_ROUTE_ID, nextRouteId)
|
||||
.apply()
|
||||
routeLabel = intent?.getStringExtra(EXTRA_ROUTE_LABEL) ?: routeLabel
|
||||
destinationLat = intent?.takeIf { it.hasExtra(EXTRA_DESTINATION_LAT) }?.getDoubleExtra(EXTRA_DESTINATION_LAT, 0.0)
|
||||
?: destinationLat
|
||||
destinationLon = intent?.takeIf { it.hasExtra(EXTRA_DESTINATION_LON) }?.getDoubleExtra(EXTRA_DESTINATION_LON, 0.0)
|
||||
?: destinationLon
|
||||
totalDistanceMeters = intent?.takeIf { it.hasExtra(EXTRA_TOTAL_DISTANCE_METERS) }?.getDoubleExtra(EXTRA_TOTAL_DISTANCE_METERS, 0.0)
|
||||
?.takeIf { it > 0.0 }
|
||||
?: totalDistanceMeters
|
||||
progressEnabled = intent?.getBooleanExtra(EXTRA_PROGRESS_ENABLED, true) ?: progressEnabled
|
||||
if (routeChanged) arrived = false
|
||||
if (!startForegroundCompat(buildNotification())) {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
if (!arrived) requestLocationUpdates()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLocationChanged(location: Location) {
|
||||
val activeRouteId = routeId ?: return
|
||||
val activeDriverId = driverId ?: return
|
||||
val remaining = remainingMeters(location)
|
||||
lastRemainingMeters = remaining
|
||||
|
||||
if (!arrived && remaining != null && remaining <= arrivalRadiusMeters(location)) {
|
||||
arrived = true
|
||||
runCatching { locationManager.removeUpdates(this) }
|
||||
if (!startForegroundCompat(buildNotification())) return
|
||||
} else {
|
||||
if (!startForegroundCompat(buildNotification())) return
|
||||
}
|
||||
|
||||
val (battery, charging) = batterySnapshot()
|
||||
val uploadDelaySeconds = uploadDelaySeconds(location, remaining)
|
||||
scope.launch {
|
||||
routePointOutbox.enqueue(
|
||||
routeId = activeRouteId,
|
||||
driverId = activeDriverId,
|
||||
location = location,
|
||||
battery = battery,
|
||||
charging = charging,
|
||||
uploadDelaySeconds = uploadDelaySeconds,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onDestroy() {
|
||||
runCatching { locationManager.removeUpdates(this) }
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
stopForeground(true)
|
||||
}
|
||||
getSystemService(NotificationManager::class.java).cancel(NOTIFICATION_ID)
|
||||
getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.remove(ACTIVE_ROUTE_ID)
|
||||
.apply()
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun requestLocationUpdates() {
|
||||
if (!hasLocationPermission() || routeId.isNullOrBlank() || driverId.isNullOrBlank()) {
|
||||
return
|
||||
}
|
||||
runCatching { locationManager.removeUpdates(this) }
|
||||
runCatching {
|
||||
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL_MS, 0f, this)
|
||||
}
|
||||
runCatching {
|
||||
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL_MS, 0f, this)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
val activeRouteId = routeId
|
||||
val target = if (arrived) MainActivity.ROUTE_TARGET_FINISH else MainActivity.ROUTE_TARGET_DETAIL
|
||||
val contentIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
if (arrived) 202 else 201,
|
||||
Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||||
putExtra(MainActivity.EXTRA_ROUTE_ID, activeRouteId)
|
||||
putExtra(MainActivity.EXTRA_ROUTE_TARGET, target)
|
||||
},
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
val title = if (arrived) "Jesteś u celu" else routeLabel
|
||||
val text = when {
|
||||
arrived -> "Otwórz zakończenie kursu i dodaj wagę oraz zdjęcia."
|
||||
!progressEnabled -> "Kurs aktywny"
|
||||
lastRemainingMeters != null -> "Do celu: ${formatDistance(lastRemainingMeters!!.toDouble())}"
|
||||
else -> "Kurs aktywny"
|
||||
}
|
||||
|
||||
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setContentIntent(contentIntent)
|
||||
.setOngoing(!arrived)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
|
||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||
|
||||
val progress = progressPercent()
|
||||
if (!arrived && progressEnabled && progress != null) {
|
||||
builder.setProgress(100, progress, false)
|
||||
}
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
private fun startForegroundCompat(notification: Notification): Boolean {
|
||||
if (!hasLocationPermission()) {
|
||||
stopSelf()
|
||||
return false
|
||||
}
|
||||
|
||||
return try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)
|
||||
} else {
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
}
|
||||
true
|
||||
} catch (_: SecurityException) {
|
||||
stopSelf()
|
||||
false
|
||||
} catch (_: IllegalStateException) {
|
||||
stopSelf()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Aktywny kurs",
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
).apply {
|
||||
description = "Informacje o aktywnym kursie"
|
||||
}
|
||||
manager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private fun remainingMeters(location: Location): Float? {
|
||||
val lat = destinationLat ?: return null
|
||||
val lon = destinationLon ?: return null
|
||||
val target = Location("destination").apply {
|
||||
latitude = lat
|
||||
longitude = lon
|
||||
}
|
||||
return location.distanceTo(target)
|
||||
}
|
||||
|
||||
private fun arrivalRadiusMeters(location: Location): Float =
|
||||
maxOf(120f, if (location.hasAccuracy()) location.accuracy * 2f else 0f)
|
||||
|
||||
private fun progressPercent(): Int? {
|
||||
val total = totalDistanceMeters ?: return null
|
||||
val remaining = lastRemainingMeters ?: return null
|
||||
if (total <= 0.0) return null
|
||||
|
||||
return ((1.0 - (remaining / total)).coerceIn(0.0, 1.0) * 100).toInt()
|
||||
}
|
||||
|
||||
private fun uploadDelaySeconds(location: Location, remaining: Float?): Long {
|
||||
val speed = if (location.hasSpeed()) location.speed else 0f
|
||||
return when {
|
||||
arrived || remaining != null && remaining <= 2_500f -> 5L
|
||||
speed < 0.8f -> 45L
|
||||
speed > 22f -> 20L
|
||||
else -> 20L
|
||||
}
|
||||
}
|
||||
|
||||
private fun batterySnapshot(): Pair<Int?, Boolean> {
|
||||
val batteryIntent = 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
|
||||
val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
|
||||
val percent = if (level >= 0 && scale > 0) ((level * 100f) / scale).toInt().coerceIn(0, 100) else null
|
||||
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
|
||||
status == BatteryManager.BATTERY_STATUS_FULL
|
||||
|
||||
return percent to charging
|
||||
}
|
||||
|
||||
private fun hasLocationPermission(): Boolean =
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private fun formatDistance(meters: Double): String =
|
||||
if (meters >= 1000.0) {
|
||||
String.format(Locale("pl", "PL"), "%.1f km", meters / 1000.0)
|
||||
} else {
|
||||
"${meters.toInt().coerceAtLeast(0)} m"
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "active_route_tracking"
|
||||
private const val NOTIFICATION_ID = 7401
|
||||
private const val LOCATION_INTERVAL_MS = 5_000L
|
||||
|
||||
private const val ACTION_START = "pl.firmatpp.kierowca.tracking.START"
|
||||
private const val ACTION_STOP = "pl.firmatpp.kierowca.tracking.STOP"
|
||||
private const val ACTION_MARK_ARRIVED = "pl.firmatpp.kierowca.tracking.MARK_ARRIVED"
|
||||
|
||||
private const val EXTRA_ROUTE_ID = "routeId"
|
||||
private const val EXTRA_DRIVER_ID = "driverId"
|
||||
private const val EXTRA_ROUTE_LABEL = "routeLabel"
|
||||
private const val EXTRA_DESTINATION_LAT = "destinationLat"
|
||||
private const val EXTRA_DESTINATION_LON = "destinationLon"
|
||||
private const val EXTRA_TOTAL_DISTANCE_METERS = "totalDistanceMeters"
|
||||
private const val EXTRA_PROGRESS_ENABLED = "progressEnabled"
|
||||
private const val TRACKING_PREFERENCES = "active_route_tracking"
|
||||
private const val ACTIVE_ROUTE_ID = "active_route_id"
|
||||
|
||||
fun start(context: Context, route: DriverRouteDto, driver: DriverDto, progressEnabled: Boolean = true) {
|
||||
if (!hasLocationPermission(context)) return
|
||||
|
||||
val intent = Intent(context, ActiveRouteTrackingService::class.java).apply {
|
||||
action = ACTION_START
|
||||
putExtra(EXTRA_ROUTE_ID, route.id)
|
||||
putExtra(EXTRA_DRIVER_ID, driver.id)
|
||||
putExtra(EXTRA_ROUTE_LABEL, route.contractCode?.let { "Kurs #$it" } ?: route.relationLabel)
|
||||
putExtra(EXTRA_PROGRESS_ENABLED, progressEnabled)
|
||||
route.destinationNavigation?.latitude?.let { putExtra(EXTRA_DESTINATION_LAT, it) }
|
||||
route.destinationNavigation?.longitude?.let { putExtra(EXTRA_DESTINATION_LON, it) }
|
||||
route.distanceKm?.takeIf { it > 0.0 }?.let { putExtra(EXTRA_TOTAL_DISTANCE_METERS, it * 1000.0) }
|
||||
}
|
||||
runCatching { ContextCompat.startForegroundService(context, intent) }
|
||||
}
|
||||
|
||||
fun stop(context: Context, routeId: String? = null) {
|
||||
val activeRouteId = context.getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
|
||||
.getString(ACTIVE_ROUTE_ID, null)
|
||||
if (routeId == null || routeId == activeRouteId) {
|
||||
context.stopService(Intent(context, ActiveRouteTrackingService::class.java))
|
||||
context.getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.remove(ACTIVE_ROUTE_ID)
|
||||
.apply()
|
||||
}
|
||||
}
|
||||
|
||||
fun markArrived(context: Context, routeId: String) {
|
||||
if (!hasLocationPermission(context)) return
|
||||
val activeRouteId = context.getSharedPreferences(TRACKING_PREFERENCES, Context.MODE_PRIVATE)
|
||||
.getString(ACTIVE_ROUTE_ID, null)
|
||||
if (activeRouteId != routeId) return
|
||||
|
||||
val intent = Intent(context, ActiveRouteTrackingService::class.java).apply {
|
||||
action = ACTION_MARK_ARRIVED
|
||||
putExtra(EXTRA_ROUTE_ID, routeId)
|
||||
}
|
||||
runCatching { ContextCompat.startForegroundService(context, intent) }
|
||||
}
|
||||
|
||||
private fun hasLocationPermission(context: Context): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package pl.firmatpp.kierowca.ui
|
||||
|
||||
import java.time.LocalDate
|
||||
import pl.firmatpp.kierowca.data.model.DriverLeaveCalendarEntryDto
|
||||
|
||||
data class LeaveRequestsConfig(
|
||||
val enabled: Boolean = false,
|
||||
val types: List<String> = listOf("URLOP"),
|
||||
)
|
||||
|
||||
object DriverLeaveRequestUiRules {
|
||||
fun isFeatureVisible(config: LeaveRequestsConfig?): Boolean =
|
||||
config?.enabled == true && config.types.isNotEmpty()
|
||||
|
||||
fun statusLabel(status: String): String =
|
||||
when (status) {
|
||||
"pending" -> "Oczekuje"
|
||||
"approved" -> "Zatwierdzony"
|
||||
"rejected" -> "Odrzucony"
|
||||
"cancel_requested" -> "Anulowanie do decyzji"
|
||||
"cancelled" -> "Anulowany"
|
||||
"revoked" -> "Cofnięto decyzję"
|
||||
else -> "Nieznany status"
|
||||
}
|
||||
|
||||
fun eventActionLabel(action: String): String =
|
||||
when (action) {
|
||||
"submitted" -> "Wniosek złożony"
|
||||
"approved" -> "Wniosek zatwierdzony"
|
||||
"rejected" -> "Wniosek odrzucony"
|
||||
"revoked" -> "Decyzja cofnięta"
|
||||
"cancelled_by_driver" -> "Wniosek anulowany przez kierowcę"
|
||||
"cancellation_requested" -> "Kierowca poprosił o anulowanie"
|
||||
"cancellation_approved" -> "Anulowanie zatwierdzone"
|
||||
"cancellation_rejected" -> "Anulowanie odrzucone"
|
||||
else -> "Aktualizacja wniosku"
|
||||
}
|
||||
|
||||
fun typeLabel(type: String): String =
|
||||
when (type) {
|
||||
"URLOP" -> "Urlop"
|
||||
"CHOROBOWE" -> "Chorobowe"
|
||||
"SZKOLENIE" -> "Szkolenie"
|
||||
"WOLNE" -> "Dzień wolny"
|
||||
"INNE" -> "Inne"
|
||||
else -> type
|
||||
}
|
||||
|
||||
fun canCancel(status: String, dateFrom: String, today: LocalDate = LocalDate.now()): Boolean {
|
||||
if (status == "pending") return true
|
||||
if (status != "approved") return false
|
||||
|
||||
val start = runCatching { LocalDate.parse(dateFrom) }.getOrNull() ?: return false
|
||||
return start.isAfter(today)
|
||||
}
|
||||
|
||||
fun calendarEntriesForDate(entries: List<DriverLeaveCalendarEntryDto>, date: LocalDate): List<DriverLeaveCalendarEntryDto> =
|
||||
entries.filter { entry ->
|
||||
val from = entry.dateFrom?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
val to = entry.dateTo?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
from != null && to != null && !date.isBefore(from) && !date.isAfter(to)
|
||||
}
|
||||
|
||||
fun calendarEntriesForRange(entries: List<DriverLeaveCalendarEntryDto>, dateFrom: String, dateTo: String): List<DriverLeaveCalendarEntryDto> {
|
||||
val selectedFrom = runCatching { LocalDate.parse(dateFrom) }.getOrNull() ?: return emptyList()
|
||||
val selectedTo = runCatching { LocalDate.parse(dateTo) }.getOrNull() ?: return emptyList()
|
||||
val from = minOf(selectedFrom, selectedTo)
|
||||
val to = maxOf(selectedFrom, selectedTo)
|
||||
|
||||
return entries.filter { entry ->
|
||||
val entryFrom = entry.dateFrom?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
val entryTo = entry.dateTo?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
entryFrom != null && entryTo != null && !entryTo.isBefore(from) && !entryFrom.isAfter(to)
|
||||
}
|
||||
}
|
||||
|
||||
fun phoneDialUri(phoneNumber: String?): String? {
|
||||
val raw = phoneNumber?.trim().orEmpty()
|
||||
if (raw.isBlank()) return null
|
||||
|
||||
val digits = raw.filter { it.isDigit() }
|
||||
if (digits.isBlank()) return null
|
||||
|
||||
val normalized = when {
|
||||
digits.startsWith("00") -> "+${digits.drop(2)}"
|
||||
raw.startsWith("+") -> "+$digits"
|
||||
digits.length == 9 -> "+48$digits"
|
||||
else -> "+$digits"
|
||||
}
|
||||
|
||||
return "tel:$normalized"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package pl.firmatpp.kierowca.ui
|
||||
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
import pl.firmatpp.kierowca.data.model.RoutePhotoDto
|
||||
import pl.firmatpp.kierowca.data.upload.RouteActionEntity
|
||||
import pl.firmatpp.kierowca.data.upload.RouteActionStatus
|
||||
import pl.firmatpp.kierowca.data.upload.RouteActionType
|
||||
|
||||
data class ProjectedDriverRoute(
|
||||
val route: DriverRouteDto,
|
||||
val visibleActions: List<RouteActionEntity>,
|
||||
val loadingWeightPending: Boolean,
|
||||
val unloadingWeightPending: Boolean,
|
||||
)
|
||||
|
||||
internal val routeActionVisibleStatuses = setOf(
|
||||
RouteActionStatus.Pending,
|
||||
RouteActionStatus.WaitingForPhotos,
|
||||
RouteActionStatus.Syncing,
|
||||
RouteActionStatus.FailedRetryable,
|
||||
RouteActionStatus.FailedConflict,
|
||||
RouteActionStatus.FailedPermanent,
|
||||
)
|
||||
|
||||
private val routeActionDataProjectionStatuses = routeActionVisibleStatuses + RouteActionStatus.Confirmed
|
||||
private val routeActionLifecycleProjectionStatuses = setOf(
|
||||
RouteActionStatus.Pending,
|
||||
RouteActionStatus.WaitingForPhotos,
|
||||
RouteActionStatus.Syncing,
|
||||
RouteActionStatus.FailedRetryable,
|
||||
RouteActionStatus.Confirmed,
|
||||
)
|
||||
|
||||
fun projectDriverRoute(route: DriverRouteDto, actions: List<RouteActionEntity>): ProjectedDriverRoute {
|
||||
val visible = actions
|
||||
.filter { it.routeId == route.id && it.status in routeActionVisibleStatuses }
|
||||
val projectable = actions
|
||||
.filter { it.routeId == route.id && it.status in routeActionDataProjectionStatuses }
|
||||
var projectedRoute = route
|
||||
var loadingWeightPending = false
|
||||
var unloadingWeightPending = false
|
||||
|
||||
projectable
|
||||
.sortedWith(compareBy<RouteActionEntity> { it.createdAtEpochMillis }.thenBy { it.clientActionId })
|
||||
.forEach { action ->
|
||||
when (action.action) {
|
||||
RouteActionType.Start -> {
|
||||
projectedRoute = projectedRoute.copy(
|
||||
loadingWeight = action.weight,
|
||||
loadingNotes = action.notes,
|
||||
photos = projectedRoute.safePhotos(),
|
||||
)
|
||||
if (action.status in routeActionLifecycleProjectionStatuses) {
|
||||
projectedRoute = projectedRoute.copy(
|
||||
status = "W TRAKCIE",
|
||||
driverStatus = "W TRAKCIE",
|
||||
trackingStatus = "active",
|
||||
)
|
||||
}
|
||||
loadingWeightPending = action.status != RouteActionStatus.Confirmed
|
||||
}
|
||||
RouteActionType.Finish -> {
|
||||
projectedRoute = projectedRoute.copy(
|
||||
unloadingWeight = action.weight,
|
||||
unloadingNotes = action.notes,
|
||||
photos = projectedRoute.safePhotos(),
|
||||
)
|
||||
if (action.status in routeActionLifecycleProjectionStatuses) {
|
||||
projectedRoute = projectedRoute.copy(
|
||||
status = "ZAKOŃCZONA",
|
||||
driverStatus = "ZAKOŃCZONA",
|
||||
trackingStatus = "finished",
|
||||
completedAt = action.occurredAt,
|
||||
)
|
||||
}
|
||||
unloadingWeightPending = action.status != RouteActionStatus.Confirmed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ProjectedDriverRoute(
|
||||
route = projectedRoute,
|
||||
visibleActions = visible.sortedWith(
|
||||
compareByDescending<RouteActionEntity> { it.createdAtEpochMillis }.thenBy { it.clientActionId },
|
||||
),
|
||||
loadingWeightPending = loadingWeightPending,
|
||||
unloadingWeightPending = unloadingWeightPending,
|
||||
)
|
||||
}
|
||||
|
||||
fun projectDriverRoutes(routes: List<DriverRouteDto>, actions: List<RouteActionEntity>): List<DriverRouteDto> =
|
||||
routes.map { route -> projectDriverRoute(route, actions).route }
|
||||
|
||||
fun routeActionNeedsAttention(status: String): Boolean =
|
||||
status == RouteActionStatus.FailedConflict || status == RouteActionStatus.FailedPermanent
|
||||
|
||||
internal fun DriverRouteDto.safePhotos(): List<RoutePhotoDto> = photos.orEmpty()
|
||||
@@ -0,0 +1,720 @@
|
||||
package pl.firmatpp.kierowca.ui
|
||||
|
||||
import java.io.File
|
||||
import java.math.BigDecimal
|
||||
import java.math.RoundingMode
|
||||
import java.net.URLEncoder
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.util.Locale
|
||||
import kotlin.math.abs
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
import pl.firmatpp.kierowca.data.model.DispatchSheetReminderDto
|
||||
import pl.firmatpp.kierowca.data.model.RoutePhotoDto
|
||||
import pl.firmatpp.kierowca.data.model.TachographReminderDto
|
||||
import pl.firmatpp.kierowca.data.model.TachographReminderTaskDto
|
||||
import pl.firmatpp.kierowca.data.model.driverLifecycleStatus
|
||||
import pl.firmatpp.kierowca.data.upload.PhotoUploadEntity
|
||||
import pl.firmatpp.kierowca.data.upload.PhotoUploadStatus
|
||||
import pl.firmatpp.kierowca.data.upload.isWorkerCancellationFailure
|
||||
import pl.firmatpp.kierowca.data.upload.RouteActionEntity
|
||||
import pl.firmatpp.kierowca.data.upload.RouteActionStatus
|
||||
import pl.firmatpp.kierowca.data.upload.RouteActionType
|
||||
|
||||
private val shortDateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM")
|
||||
private val routeWeightKilogramInputThreshold = BigDecimal("1000")
|
||||
private const val routeWeightMaxTons = 999.999
|
||||
const val routeStageNotesMaxLength = 2000
|
||||
private const val googleMapsPackage = "com.google.android.apps.maps"
|
||||
|
||||
data class NavigationIntentCandidate(
|
||||
val uri: String,
|
||||
val packageName: String? = null,
|
||||
)
|
||||
|
||||
data class AppUpdateBannerUi(
|
||||
val message: String,
|
||||
val actionLabel: String,
|
||||
val required: Boolean,
|
||||
val downloaded: Boolean,
|
||||
)
|
||||
|
||||
object RouteLocationMode {
|
||||
const val Disabled = "disabled"
|
||||
const val Optional = "optional"
|
||||
const val Required = "required"
|
||||
}
|
||||
|
||||
fun normalizeRouteLocationMode(value: String?): String = when (value) {
|
||||
RouteLocationMode.Disabled,
|
||||
RouteLocationMode.Required,
|
||||
-> value
|
||||
else -> RouteLocationMode.Optional
|
||||
}
|
||||
|
||||
fun shouldTrackRouteLocation(
|
||||
mode: String,
|
||||
optionalLocationEnabled: Boolean,
|
||||
hasLocationPermission: Boolean,
|
||||
): Boolean = hasLocationPermission && when (normalizeRouteLocationMode(mode)) {
|
||||
RouteLocationMode.Disabled -> false
|
||||
RouteLocationMode.Required -> true
|
||||
else -> optionalLocationEnabled
|
||||
}
|
||||
|
||||
fun routeStartRequiresLocationPermission(
|
||||
mode: String,
|
||||
hasLocationPermission: Boolean,
|
||||
): Boolean = normalizeRouteLocationMode(mode) == RouteLocationMode.Required && !hasLocationPermission
|
||||
|
||||
fun shouldWarnAboutRequiredRouteLocation(
|
||||
mode: String,
|
||||
hasActiveRoute: Boolean,
|
||||
hasLocationPermission: Boolean,
|
||||
): Boolean = normalizeRouteLocationMode(mode) == RouteLocationMode.Required &&
|
||||
hasActiveRoute &&
|
||||
!hasLocationPermission
|
||||
|
||||
fun appUpdateBannerUi(
|
||||
currentVersionCode: Int,
|
||||
latestVersionCode: Int?,
|
||||
latestVersionName: String?,
|
||||
minimumSupportedVersionCode: Int,
|
||||
playUpdateAvailable: Boolean,
|
||||
playAvailableVersionCode: Int?,
|
||||
updateDownloaded: Boolean,
|
||||
): AppUpdateBannerUi? {
|
||||
val highestAvailableVersion = listOfNotNull(latestVersionCode, playAvailableVersionCode).maxOrNull()
|
||||
val required = minimumSupportedVersionCode > 0 && currentVersionCode < minimumSupportedVersionCode
|
||||
val available = updateDownloaded ||
|
||||
playUpdateAvailable ||
|
||||
highestAvailableVersion?.let { it > currentVersionCode } == true ||
|
||||
required
|
||||
if (!available) return null
|
||||
|
||||
val versionLabel = latestVersionName
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?.let { " $it" }
|
||||
.orEmpty()
|
||||
val message = when {
|
||||
updateDownloaded -> "Aktualizacja$versionLabel jest pobrana i gotowa do instalacji."
|
||||
required -> "Ta wersja aplikacji nie jest już obsługiwana. Zaktualizuj ją, aby kontynuować."
|
||||
else -> "Dostępna jest nowa wersja aplikacji$versionLabel."
|
||||
}
|
||||
|
||||
return AppUpdateBannerUi(
|
||||
message = message,
|
||||
actionLabel = if (updateDownloaded) "Zainstaluj" else "Aktualizuj",
|
||||
required = required,
|
||||
downloaded = updateDownloaded,
|
||||
)
|
||||
}
|
||||
|
||||
fun hasValidNavigationCoordinates(latitude: Double?, longitude: Double?): Boolean =
|
||||
latitude != null &&
|
||||
longitude != null &&
|
||||
latitude.isFinite() &&
|
||||
longitude.isFinite() &&
|
||||
latitude in -90.0..90.0 &&
|
||||
longitude in -180.0..180.0
|
||||
|
||||
fun navigationIntentCandidates(
|
||||
latitude: Double?,
|
||||
longitude: Double?,
|
||||
label: String?,
|
||||
): List<NavigationIntentCandidate> {
|
||||
if (!hasValidNavigationCoordinates(latitude, longitude)) return emptyList()
|
||||
|
||||
val coordinates = "$latitude,$longitude"
|
||||
val encodedLabel = URLEncoder
|
||||
.encode(label?.takeIf { it.isNotBlank() } ?: "Cel", Charsets.UTF_8.name())
|
||||
.replace("+", "%20")
|
||||
|
||||
return listOf(
|
||||
NavigationIntentCandidate(
|
||||
uri = "google.navigation:q=$coordinates",
|
||||
packageName = googleMapsPackage,
|
||||
),
|
||||
NavigationIntentCandidate(uri = "geo:0,0?q=$coordinates($encodedLabel)"),
|
||||
NavigationIntentCandidate(uri = "https://www.google.com/maps/dir/?api=1&destination=$coordinates"),
|
||||
)
|
||||
}
|
||||
|
||||
enum class RouteFlowStepState {
|
||||
Todo,
|
||||
ServerSaved,
|
||||
InProgress,
|
||||
Syncing,
|
||||
Confirmed,
|
||||
NeedsAttention,
|
||||
}
|
||||
|
||||
enum class RouteLifecycleAction {
|
||||
Start,
|
||||
Finish,
|
||||
}
|
||||
|
||||
data class RouteFlowStepUi(
|
||||
val key: String,
|
||||
val title: String,
|
||||
val state: RouteFlowStepState,
|
||||
val stateLabel: String,
|
||||
val dateLabel: String? = null,
|
||||
)
|
||||
|
||||
data class RouteLifecycleActionUi(
|
||||
val label: String,
|
||||
val action: RouteLifecycleAction,
|
||||
)
|
||||
|
||||
data class RouteSyncCalloutUi(
|
||||
val text: String,
|
||||
val isConflict: Boolean,
|
||||
val canCorrect: Boolean,
|
||||
)
|
||||
|
||||
fun canManageRoutePhotos(selectedDate: String, today: LocalDate = LocalDate.now()): Boolean =
|
||||
runCatching { LocalDate.parse(selectedDate).isEqual(today) }.getOrDefault(false)
|
||||
|
||||
fun routeIsActiveToday(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): Boolean {
|
||||
val viewedDate = runCatching { LocalDate.parse(selectedDate) }.getOrNull() ?: return false
|
||||
val loadingDate = route.routeDate?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: return false
|
||||
val unloadingDate = route.unloadingDate
|
||||
?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
?: loadingDate
|
||||
|
||||
return viewedDate == today && !today.isBefore(loadingDate) && !today.isAfter(unloadingDate)
|
||||
}
|
||||
|
||||
fun routeUnloadingDate(route: DriverRouteDto): String? = route.unloadingDate ?: route.routeDate
|
||||
|
||||
fun routeDayOrdering(route: DriverRouteDto, date: String): Int =
|
||||
route.dayOrderings?.get(date) ?: route.ordering ?: Int.MAX_VALUE
|
||||
|
||||
fun routeScheduleDateLabel(date: String?): String =
|
||||
date
|
||||
?.let { runCatching { LocalDate.parse(it).format(shortDateFormatter) }.getOrNull() }
|
||||
?: "—"
|
||||
|
||||
fun routeScheduleSummary(route: DriverRouteDto): String {
|
||||
val loading = routeScheduleDateLabel(route.routeDate)
|
||||
val unloading = routeScheduleDateLabel(routeUnloadingDate(route))
|
||||
|
||||
return if (route.unloadingDate == null) {
|
||||
"Załadunek: $loading · Rozładunek: ten sam dzień"
|
||||
} else {
|
||||
"Załadunek: $loading · Rozładunek: $unloading"
|
||||
}
|
||||
}
|
||||
|
||||
fun routeTodayInstruction(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): String? {
|
||||
if (!routeIsActiveToday(route, selectedDate, today)) return null
|
||||
|
||||
val loadingDate = route.routeDate?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: return null
|
||||
val unloadingDate = routeUnloadingDate(route)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: loadingDate
|
||||
|
||||
return when {
|
||||
route.driverLifecycleStatus() == "ZAKOŃCZONA" -> "Kurs zakończony."
|
||||
loadingDate == unloadingDate -> "Dziś: załadunek i rozładunek."
|
||||
today == loadingDate -> "Dziś: załadunek."
|
||||
today == unloadingDate && route.driverLifecycleStatus() == "ZAPLANOWANA" -> "Dziś: rozładunek. Załadunek możesz potwierdzić dzisiaj."
|
||||
today == unloadingDate -> "Dziś: rozładunek."
|
||||
else -> "Kurs jest w trasie. Rozładunek: ${routeScheduleDateLabel(routeUnloadingDate(route))}."
|
||||
}
|
||||
}
|
||||
|
||||
fun canCompleteRouteFromDriverApp(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): Boolean =
|
||||
runCatching { LocalDate.parse(selectedDate) }.getOrNull() == today
|
||||
&& routeUnloadingDate(route)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } == today
|
||||
&& route.driverLifecycleStatus() in setOf("ZAPLANOWANA", "W TRAKCIE")
|
||||
|
||||
fun canStartRouteFromDriverApp(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): Boolean =
|
||||
routeIsActiveToday(route, selectedDate, today)
|
||||
&& route.driverLifecycleStatus() == "ZAPLANOWANA"
|
||||
|
||||
fun canFinishRouteFromDriverApp(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): Boolean =
|
||||
route.driverLifecycleStatus() == "W TRAKCIE"
|
||||
&& runCatching { LocalDate.parse(selectedDate) }.getOrNull() == today
|
||||
&& routeUnloadingDate(route)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } == today
|
||||
|
||||
object RouteStageRequirement {
|
||||
const val Required = "required"
|
||||
const val Optional = "optional"
|
||||
const val Disabled = "disabled"
|
||||
}
|
||||
|
||||
fun normalizeRouteStageRequirement(value: String?): String = when (value) {
|
||||
RouteStageRequirement.Optional -> RouteStageRequirement.Optional
|
||||
RouteStageRequirement.Disabled -> RouteStageRequirement.Disabled
|
||||
else -> RouteStageRequirement.Required
|
||||
}
|
||||
|
||||
fun routeStageRequirementIsVisible(requirement: String): Boolean =
|
||||
normalizeRouteStageRequirement(requirement) != RouteStageRequirement.Disabled
|
||||
|
||||
fun routeStageRequirementIsRequired(requirement: String): Boolean =
|
||||
normalizeRouteStageRequirement(requirement) == RouteStageRequirement.Required
|
||||
|
||||
fun normalizeRouteStageNotes(value: String): String = value.take(routeStageNotesMaxLength)
|
||||
|
||||
fun parseRouteWeightTons(weightText: String): Double? {
|
||||
val enteredWeight = weightText.trim().replace(',', '.').toBigDecimalOrNull() ?: return null
|
||||
val tons = if (enteredWeight.abs() >= routeWeightKilogramInputThreshold) {
|
||||
enteredWeight.movePointLeft(3)
|
||||
} else {
|
||||
enteredWeight
|
||||
}
|
||||
|
||||
return tons.setScale(3, RoundingMode.HALF_UP).toDouble()
|
||||
}
|
||||
|
||||
fun routeWeightInputHelpText(weightText: String): String {
|
||||
val enteredWeight = weightText.trim().replace(',', '.').toDoubleOrNull()
|
||||
val tons = parseRouteWeightTons(weightText)
|
||||
val enteredAsKilograms = enteredWeight != null &&
|
||||
abs(enteredWeight) >= routeWeightKilogramInputThreshold.toDouble() &&
|
||||
tons != null
|
||||
|
||||
return if (enteredAsKilograms) {
|
||||
"Wpisano kilogramy — zapiszemy ${String.format(Locale("pl", "PL"), "%.3f", tons)} t."
|
||||
} else {
|
||||
"Wpisz tony (np. 23,4). Wartości od 1000 rozpoznajemy jako kilogramy (np. 23400)."
|
||||
}
|
||||
}
|
||||
|
||||
fun canSubmitRouteStageForm(
|
||||
weightText: String,
|
||||
serverPhotoCount: Int,
|
||||
localUploadCount: Int,
|
||||
weightRequirement: String = RouteStageRequirement.Required,
|
||||
photoRequirement: String = RouteStageRequirement.Required,
|
||||
): Boolean {
|
||||
return routeStageSubmitBlocker(
|
||||
weightText,
|
||||
serverPhotoCount,
|
||||
localUploadCount,
|
||||
weightRequirement,
|
||||
photoRequirement,
|
||||
) == null
|
||||
}
|
||||
|
||||
fun loadingPhotosSubmitBlocker(
|
||||
serverPhotoCount: Int,
|
||||
localUploadCount: Int,
|
||||
photoRequirement: String = RouteStageRequirement.Required,
|
||||
): String? =
|
||||
if (
|
||||
routeStageRequirementIsRequired(photoRequirement) &&
|
||||
visiblePhotoAttachmentCount(serverPhotoCount, localUploadCount) <= 0
|
||||
) {
|
||||
"Dodaj co najmniej jedno zdjęcie załadunku."
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
fun loadingWeightSubmitBlocker(
|
||||
weightText: String,
|
||||
serverPhotoCount: Int,
|
||||
localUploadCount: Int,
|
||||
weightRequirement: String = RouteStageRequirement.Required,
|
||||
photoRequirement: String = RouteStageRequirement.Required,
|
||||
): String? {
|
||||
val trimmed = weightText.trim()
|
||||
val normalizedWeight = parseRouteWeightTons(trimmed)
|
||||
val weightVisible = routeStageRequirementIsVisible(weightRequirement)
|
||||
|
||||
return when {
|
||||
weightVisible && routeStageRequirementIsRequired(weightRequirement) && trimmed.isBlank() -> "Podaj tonaż."
|
||||
weightVisible && trimmed.isNotBlank() && normalizedWeight == null -> "Podaj poprawny tonaż."
|
||||
weightVisible && normalizedWeight != null && normalizedWeight <= 0.0 -> "Tonaż musi być większy od zera."
|
||||
weightVisible && normalizedWeight != null && normalizedWeight > routeWeightMaxTons -> "Tonaż nie może przekraczać 999,999 t."
|
||||
loadingPhotosSubmitBlocker(serverPhotoCount, localUploadCount, photoRequirement) != null -> "Dodaj co najmniej jedno zdjęcie załadunku."
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
fun routeStageSubmitBlocker(
|
||||
weightText: String,
|
||||
serverPhotoCount: Int,
|
||||
localUploadCount: Int,
|
||||
weightRequirement: String = RouteStageRequirement.Required,
|
||||
photoRequirement: String = RouteStageRequirement.Required,
|
||||
): String? {
|
||||
val trimmed = weightText.trim()
|
||||
val normalizedWeight = parseRouteWeightTons(trimmed)
|
||||
val weightVisible = routeStageRequirementIsVisible(weightRequirement)
|
||||
|
||||
return when {
|
||||
weightVisible && routeStageRequirementIsRequired(weightRequirement) && trimmed.isBlank() -> "Podaj tonaż."
|
||||
weightVisible && trimmed.isNotBlank() && normalizedWeight == null -> "Podaj poprawny tonaż."
|
||||
weightVisible && normalizedWeight != null && normalizedWeight <= 0.0 -> "Tonaż musi być większy od zera."
|
||||
weightVisible && normalizedWeight != null && normalizedWeight > routeWeightMaxTons -> "Tonaż nie może przekraczać 999,999 t."
|
||||
routeStageRequirementIsRequired(photoRequirement) && visiblePhotoAttachmentCount(serverPhotoCount, localUploadCount) <= 0 -> "Dodaj co najmniej jedno zdjęcie etapu."
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
fun routeLifecyclePrimaryAction(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): RouteLifecycleActionUi? =
|
||||
when {
|
||||
canStartRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Załaduj", RouteLifecycleAction.Start)
|
||||
canFinishRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Rozładuj", RouteLifecycleAction.Finish)
|
||||
else -> null
|
||||
}
|
||||
|
||||
fun routeSyncCallout(actions: List<RouteActionEntity>): RouteSyncCalloutUi? {
|
||||
val unresolved = actions
|
||||
.filter { it.status in routeActionVisibleStatuses }
|
||||
.maxByOrNull { it.createdAtEpochMillis }
|
||||
?: return null
|
||||
val isConflict = routeActionNeedsAttention(unresolved.status)
|
||||
|
||||
return RouteSyncCalloutUi(
|
||||
text = if (isConflict) {
|
||||
"Kurs wymaga obsługi. Dane wpisane w telefonie zostały zachowane."
|
||||
} else {
|
||||
when (unresolved.status) {
|
||||
RouteActionStatus.WaitingForPhotos -> "Czekam na wysłanie zdjęć etapu, potem wyślę zmianę statusu."
|
||||
RouteActionStatus.Pending,
|
||||
RouteActionStatus.Syncing -> "Trwa wysyłanie zmiany statusu kursu."
|
||||
RouteActionStatus.FailedRetryable -> "Nie udało się wysłać. Aplikacja spróbuje ponownie."
|
||||
else -> "Zmiana zapisana w telefonie. Aplikacja wyśle ją automatycznie."
|
||||
}
|
||||
},
|
||||
isConflict = isConflict,
|
||||
canCorrect = unresolved.status == RouteActionStatus.FailedPermanent,
|
||||
)
|
||||
}
|
||||
|
||||
fun routeFlowSteps(
|
||||
route: DriverRouteDto,
|
||||
actions: List<RouteActionEntity>,
|
||||
loadingPhotoRequirement: String = RouteStageRequirement.Required,
|
||||
loadingWeightRequirement: String = RouteStageRequirement.Required,
|
||||
): List<RouteFlowStepUi> {
|
||||
val startOverride = routeActionStepState(actions, RouteActionType.Start)
|
||||
val finishOverride = routeActionStepState(actions, RouteActionType.Finish)
|
||||
val loadingPhotoCount = routePhotosForStage(route.photos, "loading").size
|
||||
val driverStatus = route.driverLifecycleStatus()
|
||||
val loadingPhotosState = when {
|
||||
startOverride != null -> startOverride
|
||||
driverStatus == "ZAKOŃCZONA" -> RouteFlowStepState.Confirmed
|
||||
driverStatus == "W TRAKCIE" -> RouteFlowStepState.Confirmed
|
||||
loadingPhotoCount > 0 -> RouteFlowStepState.ServerSaved
|
||||
else -> RouteFlowStepState.Todo
|
||||
}
|
||||
val loadingWeightState = startOverride ?: when {
|
||||
driverStatus == "ZAKOŃCZONA" -> RouteFlowStepState.Confirmed
|
||||
driverStatus == "W TRAKCIE" -> RouteFlowStepState.Confirmed
|
||||
route.loadingWeight != null -> RouteFlowStepState.ServerSaved
|
||||
else -> RouteFlowStepState.Todo
|
||||
}
|
||||
val transitState = when {
|
||||
finishOverride != null -> RouteFlowStepState.InProgress
|
||||
driverStatus == "ZAKOŃCZONA" -> RouteFlowStepState.Confirmed
|
||||
startOverride != null -> startOverride
|
||||
driverStatus == "W TRAKCIE" -> RouteFlowStepState.InProgress
|
||||
else -> RouteFlowStepState.Todo
|
||||
}
|
||||
val unloadingState = finishOverride ?: when {
|
||||
driverStatus == "ZAKOŃCZONA" -> RouteFlowStepState.Confirmed
|
||||
route.unloadingWeight != null -> RouteFlowStepState.ServerSaved
|
||||
else -> RouteFlowStepState.Todo
|
||||
}
|
||||
|
||||
return buildList {
|
||||
if (routeStageRequirementIsVisible(loadingPhotoRequirement)) {
|
||||
add(RouteFlowStepUi("loading_photos", "Zdjęcia załadunku", loadingPhotosState, routeFlowStateLabel(loadingPhotosState), routeScheduleDateLabel(route.routeDate)))
|
||||
}
|
||||
if (routeStageRequirementIsVisible(loadingWeightRequirement)) {
|
||||
add(RouteFlowStepUi("loading_weight", "Tonaż załadunku", loadingWeightState, routeFlowStateLabel(loadingWeightState), routeScheduleDateLabel(route.routeDate)))
|
||||
}
|
||||
add(RouteFlowStepUi("transit", "W trasie", transitState, routeFlowStateLabel(transitState)))
|
||||
add(RouteFlowStepUi("unloading", "Rozładunek", unloadingState, routeFlowStateLabel(unloadingState), routeScheduleDateLabel(routeUnloadingDate(route))))
|
||||
}
|
||||
}
|
||||
|
||||
fun routePhotosForStage(photos: List<RoutePhotoDto>?, stage: String): List<RoutePhotoDto> {
|
||||
val normalized = normalizedRoutePhotoStage(stage)
|
||||
return photos.orEmpty().filter { normalizedRoutePhotoStage(it.stage) == normalized }
|
||||
}
|
||||
|
||||
fun normalizedRoutePhotoStage(stage: String?): String =
|
||||
when (stage) {
|
||||
"loading", "unloading" -> stage
|
||||
else -> "other"
|
||||
}
|
||||
|
||||
fun activeRouteUploadIntervalSeconds(
|
||||
isMoving: Boolean,
|
||||
isUrbanOrTurning: Boolean = false,
|
||||
isNearDestination: Boolean = false,
|
||||
isHighwayStable: Boolean = false,
|
||||
isLikelyOffRoute: Boolean = false,
|
||||
): Int =
|
||||
when {
|
||||
isLikelyOffRoute -> 3
|
||||
!isMoving -> 45
|
||||
isUrbanOrTurning || isNearDestination -> 5
|
||||
isHighwayStable -> 20
|
||||
else -> 20
|
||||
}
|
||||
|
||||
fun activeRouteNotificationTarget(arrived: Boolean): DriverScreen =
|
||||
if (arrived) DriverScreen.FinishRoute else DriverScreen.Detail
|
||||
|
||||
private fun routeActionStepState(actions: List<RouteActionEntity>, actionType: String): RouteFlowStepState? {
|
||||
val action = actions
|
||||
.filter { it.action == actionType && it.status in routeActionVisibleStatuses }
|
||||
.maxByOrNull { it.createdAtEpochMillis }
|
||||
?: return null
|
||||
|
||||
return when (action.status) {
|
||||
RouteActionStatus.FailedConflict,
|
||||
RouteActionStatus.FailedPermanent -> RouteFlowStepState.NeedsAttention
|
||||
else -> RouteFlowStepState.Syncing
|
||||
}
|
||||
}
|
||||
|
||||
private fun routeFlowStateLabel(state: RouteFlowStepState): String =
|
||||
when (state) {
|
||||
RouteFlowStepState.Todo -> "do zrobienia"
|
||||
RouteFlowStepState.ServerSaved -> "zapisane na serwerze"
|
||||
RouteFlowStepState.InProgress -> "w trakcie"
|
||||
RouteFlowStepState.Syncing -> "synchronizacja"
|
||||
RouteFlowStepState.Confirmed -> "potwierdzone"
|
||||
RouteFlowStepState.NeedsAttention -> "wymaga uwagi"
|
||||
}
|
||||
|
||||
fun shouldShowRouteDayLiveUpdate(viewedDate: String, hintDate: String?): Boolean =
|
||||
viewedDate.isNotBlank() && (hintDate == null || hintDate == viewedDate)
|
||||
|
||||
fun routeDateChipLabel(routeDate: String?, today: LocalDate = LocalDate.now()): String {
|
||||
val date = routeDate
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
?: return "—"
|
||||
|
||||
val fallback = date.format(shortDateFormatter)
|
||||
val days = ChronoUnit.DAYS.between(today, date)
|
||||
val human = when {
|
||||
days == 0L -> "dzisiaj"
|
||||
days == 1L -> "jutro"
|
||||
days in 2L..7L -> polishWeekdayPhrase(date.dayOfWeek)
|
||||
else -> null
|
||||
}
|
||||
|
||||
return human?.let { "$it · $fallback" } ?: fallback
|
||||
}
|
||||
|
||||
private fun polishWeekdayPhrase(day: DayOfWeek): String =
|
||||
when (day) {
|
||||
DayOfWeek.MONDAY -> "w poniedziałek"
|
||||
DayOfWeek.TUESDAY -> "we wtorek"
|
||||
DayOfWeek.WEDNESDAY -> "w środę"
|
||||
DayOfWeek.THURSDAY -> "w czwartek"
|
||||
DayOfWeek.FRIDAY -> "w piątek"
|
||||
DayOfWeek.SATURDAY -> "w sobotę"
|
||||
DayOfWeek.SUNDAY -> "w niedzielę"
|
||||
}
|
||||
|
||||
fun inlinePhotoGridRows(photoCount: Int): Int =
|
||||
if (photoCount <= 0) 0 else (photoCount + 1) / 2
|
||||
|
||||
fun shouldShowPhotoPreviewLoadingState(hasPhoto: Boolean, isLoading: Boolean, isError: Boolean): Boolean =
|
||||
hasPhoto && isLoading && !isError
|
||||
|
||||
fun shouldShowPhotoPreviewErrorState(hasPhoto: Boolean, isError: Boolean): Boolean =
|
||||
hasPhoto && isError
|
||||
|
||||
fun shouldShowPhotoTileLoadingState(hasPhoto: Boolean, isLoading: Boolean, isError: Boolean): Boolean =
|
||||
hasPhoto && isLoading && !isError
|
||||
|
||||
fun shouldShowPhotoTileErrorState(hasPhoto: Boolean, isError: Boolean): Boolean =
|
||||
hasPhoto && isError
|
||||
|
||||
fun authBrandBannerHeightDp(screenHeightDp: Int): Int =
|
||||
when {
|
||||
screenHeightDp < 640 -> 118
|
||||
screenHeightDp < 740 -> 150
|
||||
else -> 190
|
||||
}
|
||||
|
||||
fun appBrandHeaderHeightDp(screenHeightDp: Int): Int =
|
||||
when {
|
||||
screenHeightDp < 640 -> 92
|
||||
screenHeightDp < 740 -> 108
|
||||
else -> 124
|
||||
}
|
||||
|
||||
fun bottomNavigationHeightDp(screenHeightDp: Int): Int =
|
||||
when {
|
||||
screenHeightDp < 640 -> 72
|
||||
screenHeightDp < 740 -> 78
|
||||
else -> 82
|
||||
}
|
||||
|
||||
fun screenHorizontalPaddingDp(screenWidthDp: Int): Int =
|
||||
when {
|
||||
screenWidthDp < 360 -> 14
|
||||
screenWidthDp < 420 -> 16
|
||||
else -> 20
|
||||
}
|
||||
|
||||
fun phonePrefixWidthDp(screenWidthDp: Int): Int =
|
||||
when {
|
||||
screenWidthDp < 360 -> 70
|
||||
screenWidthDp < 420 -> 82
|
||||
else -> 94
|
||||
}
|
||||
|
||||
fun routeFactColumns(screenWidthDp: Int): Int =
|
||||
if (screenWidthDp < 360) 1 else 2
|
||||
|
||||
fun visiblePhotoAttachmentCount(serverPhotoCount: Int, localUploadCount: Int): Int =
|
||||
serverPhotoCount.coerceAtLeast(0) + localUploadCount.coerceAtLeast(0)
|
||||
|
||||
fun photoUploadCanSatisfyStage(status: String): Boolean =
|
||||
status in setOf(
|
||||
PhotoUploadStatus.Pending.storageValue,
|
||||
PhotoUploadStatus.Uploading.storageValue,
|
||||
PhotoUploadStatus.Verifying.storageValue,
|
||||
PhotoUploadStatus.Confirmed.storageValue,
|
||||
PhotoUploadStatus.FailedRetryable.storageValue,
|
||||
)
|
||||
|
||||
fun routeStageUsableUploads(uploads: List<PhotoUploadEntity>): List<PhotoUploadEntity> =
|
||||
uploads.filter { photoUploadCanSatisfyStage(it.status) }
|
||||
|
||||
fun queuedPhotoUploadCount(statuses: List<String>): Int =
|
||||
statuses.count { status -> status != "CONFIRMED" && status != "CANCELLED" }
|
||||
|
||||
fun routePhotoSortEpochMillis(createdAt: String?, takenAt: String?, fallback: Long): Long =
|
||||
parseIsoOffsetEpochMillis(createdAt)
|
||||
?: parseIsoOffsetEpochMillis(takenAt)
|
||||
?: fallback
|
||||
|
||||
fun confirmedUploadServerPhotoId(status: String, serverPhotoId: String?): String? =
|
||||
serverPhotoId?.takeIf { status == "CONFIRMED" && it.isNotBlank() }
|
||||
|
||||
fun canRetryPhotoUpload(status: String, lastError: String? = null): Boolean =
|
||||
status == PhotoUploadStatus.FailedRetryable.storageValue ||
|
||||
(status == PhotoUploadStatus.FailedPermanent.storageValue && isWorkerCancellationFailure(lastError))
|
||||
|
||||
fun canDiscardLocalPhotoUpload(status: String, serverPhotoId: String?): Boolean =
|
||||
serverPhotoId.isNullOrBlank() && status in setOf(
|
||||
PhotoUploadStatus.FailedRetryable.storageValue,
|
||||
PhotoUploadStatus.FailedPermanent.storageValue,
|
||||
)
|
||||
|
||||
fun canShowPhotoUploadFailureDetails(status: String, lastError: String?): Boolean =
|
||||
status in setOf("FAILED_RETRYABLE", "FAILED_PERMANENT") && !lastError.isNullOrBlank()
|
||||
|
||||
fun localUploadPreviewPhoto(upload: PhotoUploadEntity): RoutePhotoDto? {
|
||||
if (upload.localPath.isBlank()) return null
|
||||
|
||||
return RoutePhotoDto(
|
||||
id = upload.clientRequestId,
|
||||
routeId = upload.routeId,
|
||||
clientRequestId = upload.clientRequestId,
|
||||
contentSha256 = upload.contentSha256,
|
||||
source = upload.source,
|
||||
stage = normalizedRoutePhotoStage(upload.stage),
|
||||
mimeType = upload.mimeType,
|
||||
size = upload.size,
|
||||
url = File(upload.localPath).toURI().toString(),
|
||||
takenAt = upload.takenAt,
|
||||
latitude = upload.latitude,
|
||||
longitude = upload.longitude,
|
||||
locationAccuracyMeters = upload.locationAccuracyMeters,
|
||||
createdAt = null,
|
||||
canDelete = confirmedUploadServerPhotoId(upload.status, upload.serverPhotoId) != null,
|
||||
deleteUntil = null,
|
||||
)
|
||||
}
|
||||
|
||||
fun routeScreenAfterServerRefresh(currentScreen: DriverScreen, route: DriverRouteDto): DriverScreen =
|
||||
when {
|
||||
currentScreen in setOf(DriverScreen.StartRoute, DriverScreen.LoadingWeight) &&
|
||||
route.driverLifecycleStatus() in setOf("W TRAKCIE", "ZAKOŃCZONA") -> DriverScreen.Detail
|
||||
currentScreen == DriverScreen.FinishRoute && route.driverLifecycleStatus() == "ZAKOŃCZONA" -> DriverScreen.Detail
|
||||
else -> currentScreen
|
||||
}
|
||||
|
||||
fun canLaunchCameraWithLocationPolicy(requirePreciseLocation: Boolean, hasFineLocation: Boolean): Boolean =
|
||||
!requirePreciseLocation || hasFineLocation
|
||||
|
||||
fun shouldShowDispatchSheetReminderCard(reminder: DispatchSheetReminderDto?): Boolean =
|
||||
reminder?.dueToday == true && reminder.status in setOf("missing", "uploaded")
|
||||
|
||||
fun shouldShowTachographReminderCard(reminder: TachographReminderDto?): Boolean =
|
||||
reminder?.enabled == true &&
|
||||
reminder.visible &&
|
||||
!reminder.title.isNullOrBlank() &&
|
||||
!reminder.message.isNullOrBlank() &&
|
||||
!reminder.tasks.isNullOrEmpty()
|
||||
|
||||
fun defaultTachographConfirmationSelection(tasks: List<TachographReminderTaskDto>): Set<String> =
|
||||
if (tasks.size == 1) setOf(tasks.single().id) else emptySet()
|
||||
|
||||
fun dispatchSheetPrimaryActionLabel(reminder: DispatchSheetReminderDto?, hasQueuedUpload: Boolean): String =
|
||||
when {
|
||||
hasQueuedUpload -> "Wysyłam zdjęcie..."
|
||||
reminder?.status == "uploaded" -> "Popraw"
|
||||
else -> "Zrób zdjęcie"
|
||||
}
|
||||
|
||||
fun offlineStaleBannerMessage(isOnline: Boolean, isStale: Boolean, syncLabel: String): String? =
|
||||
when {
|
||||
isOnline && !isStale -> null
|
||||
!isOnline && syncLabel == "brak zapisanej synchronizacji" ->
|
||||
"Brak połączenia z serwerem. Sprawdź internet i spróbuj ponownie."
|
||||
!isOnline -> "Brak połączenia z serwerem. Dane z $syncLabel mogą być nieaktualne."
|
||||
else -> "Dane mogą być nieaktualne. Ostatnia synchronizacja: $syncLabel."
|
||||
}
|
||||
|
||||
fun connectionStatusBannerMessage(
|
||||
isOnline: Boolean,
|
||||
isStale: Boolean,
|
||||
serverConnectionState: ServerConnectionState,
|
||||
showRealtimeReconnecting: Boolean,
|
||||
syncLabel: String,
|
||||
): String? = when {
|
||||
!isOnline -> offlineStaleBannerMessage(false, isStale, syncLabel)
|
||||
serverConnectionState == ServerConnectionState.Degraded ->
|
||||
"Internet działa, ale serwer jest chwilowo niedostępny. Pokazujemy dane z $syncLabel."
|
||||
showRealtimeReconnecting -> "Ponowne łączenie. Dane są uzgadniane z serwerem."
|
||||
isStale -> offlineStaleBannerMessage(true, true, syncLabel)
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun parseIsoOffsetEpochMillis(value: String?): Long? =
|
||||
value?.takeIf { it.isNotBlank() }?.let {
|
||||
runCatching { OffsetDateTime.parse(it).toInstant().toEpochMilli() }.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
package pl.firmatpp.kierowca.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.speech.RecognitionListener
|
||||
import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Mic
|
||||
import androidx.compose.material.icons.outlined.StopCircle
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import pl.firmatpp.kierowca.ui.theme.TppTheme
|
||||
|
||||
internal data class VoiceDictationUiState(
|
||||
val isListening: Boolean = false,
|
||||
val message: String = "Możesz wpisać uwagę albo podyktować ją po polsku.",
|
||||
val isError: Boolean = false,
|
||||
)
|
||||
|
||||
internal fun mergeDictationText(existingText: String, recognizedText: String): String {
|
||||
val existing = existingText.trimEnd()
|
||||
val recognized = recognizedText.trim()
|
||||
if (recognized.isBlank()) return normalizeRouteStageNotes(existingText)
|
||||
|
||||
return normalizeRouteStageNotes(
|
||||
if (existing.isBlank()) recognized else "$existing $recognized",
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun VoiceNotesField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
stageLabel: String,
|
||||
enabled: Boolean,
|
||||
onListeningChanged: (Boolean) -> Unit = {},
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var dictationState by remember { mutableStateOf(VoiceDictationUiState()) }
|
||||
val currentValue by rememberUpdatedState(value)
|
||||
val currentOnValueChange by rememberUpdatedState(onValueChange)
|
||||
val controller = remember(context) { AndroidLiveVoiceDictation(context.applicationContext) }
|
||||
|
||||
val startDictation = {
|
||||
controller.start(
|
||||
existingText = currentValue,
|
||||
onText = currentOnValueChange,
|
||||
onState = { dictationState = it },
|
||||
)
|
||||
}
|
||||
val microphonePermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission(),
|
||||
) { granted ->
|
||||
if (granted) {
|
||||
startDictation()
|
||||
} else {
|
||||
dictationState = VoiceDictationUiState(
|
||||
message = "Brak dostępu do mikrofonu. Możesz nadal wpisać uwagę ręcznie.",
|
||||
isError = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(dictationState.isListening) {
|
||||
onListeningChanged(dictationState.isListening)
|
||||
}
|
||||
|
||||
DisposableEffect(controller) {
|
||||
onDispose {
|
||||
onListeningChanged(false)
|
||||
controller.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = modifier,
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = { currentOnValueChange(normalizeRouteStageNotes(it)) },
|
||||
label = { Text("Uwagi do $stageLabel (opcjonalnie)") },
|
||||
placeholder = { Text("Np. oczekiwanie, uszkodzenie, problem z dokumentami…") },
|
||||
supportingText = {
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text("Zapisujemy tylko tekst uwagi.")
|
||||
Text("${value.length}/$routeStageNotesMaxLength")
|
||||
}
|
||||
},
|
||||
readOnly = dictationState.isListening,
|
||||
enabled = enabled,
|
||||
minLines = 3,
|
||||
maxLines = 6,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
if (dictationState.isListening) {
|
||||
controller.stop()
|
||||
} else if (
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
startDictation()
|
||||
} else {
|
||||
microphonePermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
},
|
||||
enabled = enabled,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = if (dictationState.isListening) Icons.Outlined.StopCircle else Icons.Outlined.Mic,
|
||||
contentDescription = null,
|
||||
)
|
||||
Text(
|
||||
text = if (dictationState.isListening) "Zakończ dyktowanie" else "Dyktuj uwagę",
|
||||
modifier = Modifier.padding(start = 10.dp),
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
}
|
||||
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
if (dictationState.isListening) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(18.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = TppTheme.colors.forest,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = dictationState.message,
|
||||
color = if (dictationState.isError) Color(0xFFB42318) else TppTheme.colors.muted,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class AndroidLiveVoiceDictation(
|
||||
private val context: Context,
|
||||
) : RecognitionListener {
|
||||
private var recognizer: SpeechRecognizer? = null
|
||||
private var prefix: String = ""
|
||||
private var onText: ((String) -> Unit)? = null
|
||||
private var onState: ((VoiceDictationUiState) -> Unit)? = null
|
||||
private var listening = false
|
||||
|
||||
fun start(
|
||||
existingText: String,
|
||||
onText: (String) -> Unit,
|
||||
onState: (VoiceDictationUiState) -> Unit,
|
||||
) {
|
||||
if (! SpeechRecognizer.isRecognitionAvailable(context)) {
|
||||
onState(
|
||||
VoiceDictationUiState(
|
||||
message = "Na tym telefonie nie ma usługi rozpoznawania mowy. Wpisz uwagę ręcznie.",
|
||||
isError = true,
|
||||
),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
this.prefix = existingText
|
||||
this.onText = onText
|
||||
this.onState = onState
|
||||
|
||||
if (recognizer == null) {
|
||||
recognizer = SpeechRecognizer.createSpeechRecognizer(context).also {
|
||||
it.setRecognitionListener(this)
|
||||
}
|
||||
}
|
||||
|
||||
listening = true
|
||||
emitState("Uruchamiam mikrofon…")
|
||||
runCatching {
|
||||
recognizer?.startListening(recognitionIntent())
|
||||
}.onFailure {
|
||||
listening = false
|
||||
emitState("Nie udało się uruchomić dyktowania. Spróbuj ponownie.", isError = true)
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
if (! listening) return
|
||||
emitState("Kończę i sprawdzam rozpoznany tekst…")
|
||||
recognizer?.stopListening()
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
listening = false
|
||||
onText = null
|
||||
onState = null
|
||||
recognizer?.cancel()
|
||||
recognizer?.destroy()
|
||||
recognizer = null
|
||||
}
|
||||
|
||||
override fun onReadyForSpeech(params: Bundle?) {
|
||||
emitState("Słucham… Mów normalnie. Rozpoznany tekst pojawia się wyżej na żywo.")
|
||||
}
|
||||
|
||||
override fun onBeginningOfSpeech() {
|
||||
emitState("Rozpoznaję mowę na żywo…")
|
||||
}
|
||||
|
||||
override fun onRmsChanged(rmsdB: Float) = Unit
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) = Unit
|
||||
|
||||
override fun onEndOfSpeech() {
|
||||
emitState("Sprawdzam rozpoznany tekst…")
|
||||
}
|
||||
|
||||
override fun onError(error: Int) {
|
||||
listening = false
|
||||
emitState(speechRecognitionErrorMessage(error), isError = true)
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
val recognized = bestRecognitionResult(results)
|
||||
if (recognized.isNotBlank()) {
|
||||
onText?.invoke(mergeDictationText(prefix, recognized))
|
||||
}
|
||||
listening = false
|
||||
emitState(
|
||||
if (recognized.isBlank()) {
|
||||
"Nie wykryto tekstu. Naciśnij „Dyktuj uwagę” i spróbuj ponownie."
|
||||
} else {
|
||||
"Rozpoznano: „${recognized.take(160)}”. Możesz teraz poprawić tekst."
|
||||
},
|
||||
isError = recognized.isBlank(),
|
||||
)
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) {
|
||||
val recognized = bestRecognitionResult(partialResults)
|
||||
if (recognized.isBlank()) return
|
||||
|
||||
onText?.invoke(mergeDictationText(prefix, recognized))
|
||||
emitState("Na żywo: „${recognized.take(160)}”")
|
||||
}
|
||||
|
||||
override fun onEvent(eventType: Int, params: Bundle?) = Unit
|
||||
|
||||
private fun recognitionIntent(): Intent =
|
||||
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
|
||||
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
|
||||
putExtra(RecognizerIntent.EXTRA_LANGUAGE, "pl-PL")
|
||||
putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
|
||||
putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3)
|
||||
putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false)
|
||||
putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
putExtra(
|
||||
RecognizerIntent.EXTRA_ENABLE_FORMATTING,
|
||||
RecognizerIntent.FORMATTING_OPTIMIZE_LATENCY,
|
||||
)
|
||||
putExtra(RecognizerIntent.EXTRA_HIDE_PARTIAL_TRAILING_PUNCTUATION, true)
|
||||
}
|
||||
}
|
||||
|
||||
private fun bestRecognitionResult(bundle: Bundle?): String =
|
||||
bundle
|
||||
?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
|
||||
?.firstOrNull()
|
||||
.orEmpty()
|
||||
.trim()
|
||||
|
||||
private fun emitState(message: String, isError: Boolean = false) {
|
||||
onState?.invoke(
|
||||
VoiceDictationUiState(
|
||||
isListening = listening,
|
||||
message = message,
|
||||
isError = isError,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun speechRecognitionErrorMessage(error: Int): String = when (error) {
|
||||
SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS ->
|
||||
"Brak dostępu do mikrofonu. Możesz wpisać uwagę ręcznie."
|
||||
SpeechRecognizer.ERROR_SPEECH_TIMEOUT ->
|
||||
"Nie usłyszałem mowy. Naciśnij „Dyktuj uwagę” i spróbuj ponownie."
|
||||
SpeechRecognizer.ERROR_NO_MATCH ->
|
||||
"Nie rozpoznano słów. Mów wyraźnie i spróbuj ponownie."
|
||||
SpeechRecognizer.ERROR_NETWORK,
|
||||
SpeechRecognizer.ERROR_NETWORK_TIMEOUT ->
|
||||
"Rozpoznawanie mowy nie ma teraz połączenia. Spróbuj ponownie lub wpisz uwagę."
|
||||
SpeechRecognizer.ERROR_RECOGNIZER_BUSY ->
|
||||
"Mikrofon jest teraz zajęty. Odczekaj chwilę i spróbuj ponownie."
|
||||
SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED,
|
||||
SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE ->
|
||||
"Polskie rozpoznawanie mowy nie jest dostępne na tym telefonie."
|
||||
else ->
|
||||
"Nie udało się rozpoznać mowy. Spróbuj ponownie lub wpisz uwagę ręcznie."
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package pl.firmatpp.kierowca.ui
|
||||
|
||||
class OtpAttemptCoordinator {
|
||||
private var currentAttemptId: Long = 0L
|
||||
private var bufferedCode: String? = null
|
||||
|
||||
fun beginAttempt(): Long {
|
||||
currentAttemptId += 1L
|
||||
bufferedCode = null
|
||||
return currentAttemptId
|
||||
}
|
||||
|
||||
fun isCurrent(attemptId: Long): Boolean = attemptId == currentAttemptId
|
||||
|
||||
fun bufferRetrievedCode(attemptId: Long, code: String): Boolean {
|
||||
if (!isCurrent(attemptId) || !isRetrievedOtpCode(code)) return false
|
||||
bufferedCode = code
|
||||
return true
|
||||
}
|
||||
|
||||
fun takeBufferedCode(attemptId: Long): String? {
|
||||
if (!isCurrent(attemptId)) return null
|
||||
return bufferedCode.also { bufferedCode = null }
|
||||
}
|
||||
|
||||
fun discard(attemptId: Long) {
|
||||
if (isCurrent(attemptId)) bufferedCode = null
|
||||
}
|
||||
}
|
||||
|
||||
internal fun sanitizeOtpCode(code: String): String =
|
||||
code.filter(Char::isDigit).take(OTP_MAX_LENGTH)
|
||||
|
||||
internal fun isRetrievedOtpCode(code: String): Boolean =
|
||||
code.length in OTP_MIN_LENGTH..OTP_MAX_LENGTH && code.all(Char::isDigit)
|
||||
|
||||
internal fun otpResendDelaySeconds(availableAtEpochMillis: Long, nowEpochMillis: Long): Int {
|
||||
val remainingMillis = (availableAtEpochMillis - nowEpochMillis).coerceAtLeast(0L)
|
||||
return ((remainingMillis + 999L) / 1_000L).toInt()
|
||||
}
|
||||
|
||||
internal const val OTP_MIN_LENGTH = 4
|
||||
internal const val OTP_DEFAULT_LENGTH = 6
|
||||
internal const val OTP_MAX_LENGTH = 10
|
||||
internal const val OTP_RESEND_COOLDOWN_MILLIS = 30_000L
|
||||
@@ -0,0 +1,29 @@
|
||||
package pl.firmatpp.kierowca.ui
|
||||
|
||||
class OtpAutoSubmitPolicy {
|
||||
private var lastSubmittedCode: String? = null
|
||||
|
||||
fun shouldSubmit(code: String, loading: Boolean): Boolean {
|
||||
return shouldSubmitCompleteCode(code, loading, code.length == OTP_DEFAULT_LENGTH)
|
||||
}
|
||||
|
||||
fun shouldSubmitRetrieved(code: String, loading: Boolean): Boolean {
|
||||
return shouldSubmitCompleteCode(code, loading, isRetrievedOtpCode(code))
|
||||
}
|
||||
|
||||
private fun shouldSubmitCompleteCode(code: String, loading: Boolean, complete: Boolean): Boolean {
|
||||
if (!complete) {
|
||||
lastSubmittedCode = null
|
||||
return false
|
||||
}
|
||||
|
||||
if (loading || code == lastSubmittedCode) return false
|
||||
|
||||
lastSubmittedCode = code
|
||||
return true
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
lastSubmittedCode = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package pl.firmatpp.kierowca.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import android.os.CancellationSignal
|
||||
import android.os.Looper
|
||||
import androidx.core.content.ContextCompat
|
||||
import kotlin.coroutines.resume
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
private const val PHOTO_LOCATION_PROVIDER_TIMEOUT_MILLIS = 5_000L
|
||||
|
||||
internal suspend fun currentPhotoLocation(context: Context): Location? {
|
||||
if (!hasAnyLocationPermission(context)) return null
|
||||
|
||||
val manager = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null
|
||||
val hasFineLocation = ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
val providers = buildList {
|
||||
if (hasFineLocation) add(LocationManager.GPS_PROVIDER)
|
||||
add(LocationManager.NETWORK_PROVIDER)
|
||||
}.filter { provider -> runCatching { manager.isProviderEnabled(provider) }.getOrDefault(false) }
|
||||
|
||||
for (provider in providers) {
|
||||
val location = withTimeoutOrNull(PHOTO_LOCATION_PROVIDER_TIMEOUT_MILLIS) {
|
||||
manager.awaitSingleLocation(context, provider)
|
||||
}
|
||||
if (location != null) return location
|
||||
}
|
||||
|
||||
return bestLastKnownLocation(manager)
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private suspend fun LocationManager.awaitSingleLocation(
|
||||
context: Context,
|
||||
provider: String,
|
||||
): Location? = suspendCancellableCoroutine { continuation ->
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
val cancellationSignal = CancellationSignal()
|
||||
continuation.invokeOnCancellation { cancellationSignal.cancel() }
|
||||
runCatching {
|
||||
getCurrentLocation(provider, cancellationSignal, context.mainExecutor) { location ->
|
||||
if (continuation.isActive) continuation.resume(location)
|
||||
}
|
||||
}.onFailure {
|
||||
if (continuation.isActive) continuation.resume(null)
|
||||
}
|
||||
return@suspendCancellableCoroutine
|
||||
}
|
||||
|
||||
val listener = object : LocationListener {
|
||||
override fun onLocationChanged(location: Location) {
|
||||
removeUpdates(this)
|
||||
if (continuation.isActive) continuation.resume(location)
|
||||
}
|
||||
}
|
||||
continuation.invokeOnCancellation { runCatching { removeUpdates(listener) } }
|
||||
runCatching {
|
||||
@Suppress("DEPRECATION")
|
||||
requestSingleUpdate(provider, listener, Looper.getMainLooper())
|
||||
}.onFailure {
|
||||
if (continuation.isActive) continuation.resume(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hasAnyLocationPermission(context: Context): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun bestLastKnownLocation(manager: LocationManager): Location? {
|
||||
val providers = listOf(
|
||||
LocationManager.GPS_PROVIDER,
|
||||
LocationManager.NETWORK_PROVIDER,
|
||||
LocationManager.PASSIVE_PROVIDER,
|
||||
)
|
||||
|
||||
return providers.mapNotNull { provider ->
|
||||
runCatching {
|
||||
if (manager.isProviderEnabled(provider) || provider == LocationManager.PASSIVE_PROVIDER) {
|
||||
manager.getLastKnownLocation(provider)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}.getOrNull()
|
||||
}.maxByOrNull { it.time }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package pl.firmatpp.kierowca.ui
|
||||
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.input.OffsetMapping
|
||||
import androidx.compose.ui.text.input.TransformedText
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
|
||||
object PolishPhoneNumberVisualTransformation : VisualTransformation {
|
||||
override fun filter(text: AnnotatedString): TransformedText {
|
||||
val rawDigits = text.text.filter(Char::isDigit).take(9)
|
||||
val formatted = rawDigits.chunked(3).joinToString(" ")
|
||||
|
||||
return TransformedText(
|
||||
AnnotatedString(formatted),
|
||||
object : OffsetMapping {
|
||||
override fun originalToTransformed(offset: Int): Int {
|
||||
val safeOffset = offset.coerceIn(0, rawDigits.length)
|
||||
val spacesBeforeOffset = when {
|
||||
safeOffset <= 3 -> 0
|
||||
safeOffset <= 6 -> 1
|
||||
else -> 2
|
||||
}
|
||||
|
||||
return (safeOffset + spacesBeforeOffset).coerceAtMost(formatted.length)
|
||||
}
|
||||
|
||||
override fun transformedToOriginal(offset: Int): Int {
|
||||
val safeOffset = offset.coerceIn(0, formatted.length)
|
||||
|
||||
return formatted
|
||||
.take(safeOffset)
|
||||
.count(Char::isDigit)
|
||||
.coerceAtMost(rawDigits.length)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package pl.firmatpp.kierowca.ui.theme
|
||||
|
||||
enum class AppThemeMode(val storedValue: String) {
|
||||
Current("current"),
|
||||
Material3("material3");
|
||||
|
||||
companion object {
|
||||
val Default: AppThemeMode = Material3
|
||||
|
||||
fun fromStoredValue(value: String?): AppThemeMode =
|
||||
entries.firstOrNull { it.storedValue == value } ?: Default
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,20 @@
|
||||
package pl.firmatpp.kierowca.ui.theme
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Shapes
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.ReadOnlyComposable
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.view.WindowCompat
|
||||
|
||||
object TppColors {
|
||||
val Forest = Color(0xFF154212)
|
||||
@@ -18,7 +29,71 @@ object TppColors {
|
||||
val Error = Color(0xFFBA1A1A)
|
||||
}
|
||||
|
||||
private val TppScheme = lightColorScheme(
|
||||
@Immutable
|
||||
data class TppColorTokens(
|
||||
val forest: Color,
|
||||
val containerGreen: Color,
|
||||
val logoLeaf: Color,
|
||||
val navy: Color,
|
||||
val surface: Color,
|
||||
val panel: Color,
|
||||
val ink: Color,
|
||||
val muted: Color,
|
||||
val outline: Color,
|
||||
val error: Color,
|
||||
val card: Color,
|
||||
val successContainer: Color,
|
||||
val successOutline: Color,
|
||||
val warningContainer: Color,
|
||||
val warningOutline: Color,
|
||||
)
|
||||
|
||||
object TppTheme {
|
||||
val colors: TppColorTokens
|
||||
@Composable
|
||||
@ReadOnlyComposable
|
||||
get() = LocalTppColorTokens.current
|
||||
}
|
||||
|
||||
private val CurrentColorTokens = TppColorTokens(
|
||||
forest = TppColors.Forest,
|
||||
containerGreen = TppColors.ContainerGreen,
|
||||
logoLeaf = TppColors.LogoLeaf,
|
||||
navy = TppColors.Navy,
|
||||
surface = TppColors.Surface,
|
||||
panel = TppColors.Panel,
|
||||
ink = TppColors.Ink,
|
||||
muted = TppColors.Muted,
|
||||
outline = TppColors.Outline,
|
||||
error = TppColors.Error,
|
||||
card = Color.White,
|
||||
successContainer = Color(0xFFEAF7EF),
|
||||
successOutline = Color(0xFF9BD1AD),
|
||||
warningContainer = Color(0xFFFFF7E6),
|
||||
warningOutline = Color(0xFFE6B85C),
|
||||
)
|
||||
|
||||
private val Material3ColorTokens = TppColorTokens(
|
||||
forest = Color(0xFF226C2C),
|
||||
containerGreen = Color(0xFF2F7D32),
|
||||
logoLeaf = Color(0xFF5FA642),
|
||||
navy = Color(0xFF225A86),
|
||||
surface = Color(0xFFF8FBF6),
|
||||
panel = Color(0xFFEAF1E6),
|
||||
ink = Color(0xFF172018),
|
||||
muted = Color(0xFF566252),
|
||||
outline = Color(0xFFBAC8B5),
|
||||
error = Color(0xFFBA1A1A),
|
||||
card = Color(0xFFFFFFFF),
|
||||
successContainer = Color(0xFFDFF4E2),
|
||||
successOutline = Color(0xFF8EC69A),
|
||||
warningContainer = Color(0xFFFFF1D6),
|
||||
warningOutline = Color(0xFFE4B45B),
|
||||
)
|
||||
|
||||
private val LocalTppColorTokens = staticCompositionLocalOf { CurrentColorTokens }
|
||||
|
||||
private val CurrentScheme = lightColorScheme(
|
||||
primary = TppColors.Forest,
|
||||
onPrimary = Color.White,
|
||||
primaryContainer = TppColors.ContainerGreen,
|
||||
@@ -33,10 +108,71 @@ private val TppScheme = lightColorScheme(
|
||||
error = TppColors.Error,
|
||||
)
|
||||
|
||||
private val Material3Scheme = lightColorScheme(
|
||||
primary = Material3ColorTokens.forest,
|
||||
onPrimary = Color.White,
|
||||
primaryContainer = Material3ColorTokens.containerGreen,
|
||||
onPrimaryContainer = Color.White,
|
||||
secondary = Material3ColorTokens.navy,
|
||||
onSecondary = Color.White,
|
||||
secondaryContainer = Color(0xFFD2E7F7),
|
||||
onSecondaryContainer = Color(0xFF071E30),
|
||||
tertiary = Color(0xFF7A5D00),
|
||||
onTertiary = Color.White,
|
||||
tertiaryContainer = Color(0xFFFFE08A),
|
||||
background = Material3ColorTokens.surface,
|
||||
onBackground = Material3ColorTokens.ink,
|
||||
surface = Material3ColorTokens.surface,
|
||||
onSurface = Material3ColorTokens.ink,
|
||||
surfaceVariant = Material3ColorTokens.panel,
|
||||
onSurfaceVariant = Material3ColorTokens.muted,
|
||||
outline = Material3ColorTokens.outline,
|
||||
outlineVariant = Color(0xFFD5DED1),
|
||||
error = Material3ColorTokens.error,
|
||||
)
|
||||
|
||||
private val CurrentShapes = Shapes(
|
||||
extraSmall = androidx.compose.foundation.shape.RoundedCornerShape(2.dp),
|
||||
small = androidx.compose.foundation.shape.RoundedCornerShape(4.dp),
|
||||
medium = androidx.compose.foundation.shape.RoundedCornerShape(8.dp),
|
||||
large = androidx.compose.foundation.shape.RoundedCornerShape(8.dp),
|
||||
extraLarge = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
|
||||
)
|
||||
|
||||
private val Material3Shapes = Shapes(
|
||||
extraSmall = androidx.compose.foundation.shape.RoundedCornerShape(8.dp),
|
||||
small = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
|
||||
medium = androidx.compose.foundation.shape.RoundedCornerShape(20.dp),
|
||||
large = androidx.compose.foundation.shape.RoundedCornerShape(28.dp),
|
||||
extraLarge = androidx.compose.foundation.shape.RoundedCornerShape(32.dp),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun TppKierowcaTheme(content: @Composable () -> Unit) {
|
||||
MaterialTheme(
|
||||
colorScheme = TppScheme,
|
||||
content = content,
|
||||
)
|
||||
@Suppress("DEPRECATION")
|
||||
fun TppKierowcaTheme(
|
||||
themeMode: AppThemeMode = AppThemeMode.Default,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val colorTokens = if (themeMode == AppThemeMode.Material3) Material3ColorTokens else CurrentColorTokens
|
||||
val colorScheme = if (themeMode == AppThemeMode.Material3) Material3Scheme else CurrentScheme
|
||||
val shapes = if (themeMode == AppThemeMode.Material3) Material3Shapes else CurrentShapes
|
||||
val view = LocalView.current
|
||||
|
||||
if (!view.isInEditMode) {
|
||||
SideEffect {
|
||||
val window = (view.context as? Activity)?.window ?: return@SideEffect
|
||||
window.statusBarColor = colorTokens.surface.toArgb()
|
||||
window.navigationBarColor = colorTokens.surface.toArgb()
|
||||
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = true
|
||||
WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = true
|
||||
}
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalTppColorTokens provides colorTokens) {
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
shapes = shapes,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package pl.firmatpp.kierowca.update
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.IntentSenderRequest
|
||||
import com.google.android.play.core.appupdate.AppUpdateInfo
|
||||
import com.google.android.play.core.appupdate.AppUpdateManager
|
||||
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
|
||||
import com.google.android.play.core.appupdate.AppUpdateOptions
|
||||
import com.google.android.play.core.install.InstallStateUpdatedListener
|
||||
import com.google.android.play.core.install.model.AppUpdateType
|
||||
import com.google.android.play.core.install.model.InstallStatus
|
||||
import com.google.android.play.core.install.model.UpdateAvailability
|
||||
|
||||
data class PlayAppUpdateState(
|
||||
val updateAvailable: Boolean = false,
|
||||
val availableVersionCode: Int? = null,
|
||||
val downloaded: Boolean = false,
|
||||
val checking: Boolean = false,
|
||||
)
|
||||
|
||||
class PlayInAppUpdateController(
|
||||
private val activity: ComponentActivity,
|
||||
private val launcher: ActivityResultLauncher<IntentSenderRequest>,
|
||||
private val onStateChanged: (PlayAppUpdateState) -> Unit,
|
||||
private val appUpdateManager: AppUpdateManager = AppUpdateManagerFactory.create(activity),
|
||||
) {
|
||||
private var state = PlayAppUpdateState()
|
||||
private val installStateListener = InstallStateUpdatedListener { installState ->
|
||||
when (installState.installStatus()) {
|
||||
InstallStatus.DOWNLOADED -> updateState(state.copy(downloaded = true, updateAvailable = true))
|
||||
InstallStatus.INSTALLED -> updateState(PlayAppUpdateState())
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
appUpdateManager.registerListener(installStateListener)
|
||||
}
|
||||
|
||||
fun checkForUpdate() {
|
||||
updateState(state.copy(checking = true))
|
||||
appUpdateManager.appUpdateInfo
|
||||
.addOnSuccessListener(::handleUpdateInfo)
|
||||
.addOnFailureListener { updateState(state.copy(checking = false)) }
|
||||
}
|
||||
|
||||
fun startUpdate(required: Boolean, playStoreUrl: String?) {
|
||||
appUpdateManager.appUpdateInfo
|
||||
.addOnSuccessListener { info ->
|
||||
if (info.updateAvailability() != UpdateAvailability.UPDATE_AVAILABLE) {
|
||||
openPlayStore(playStoreUrl)
|
||||
return@addOnSuccessListener
|
||||
}
|
||||
|
||||
val preferredType = if (required) AppUpdateType.IMMEDIATE else AppUpdateType.FLEXIBLE
|
||||
val updateType = when {
|
||||
info.isUpdateTypeAllowed(preferredType) -> preferredType
|
||||
info.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE) -> AppUpdateType.FLEXIBLE
|
||||
info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE) -> AppUpdateType.IMMEDIATE
|
||||
else -> null
|
||||
}
|
||||
|
||||
if (updateType == null || !launchUpdate(info, updateType)) {
|
||||
openPlayStore(playStoreUrl)
|
||||
}
|
||||
}
|
||||
.addOnFailureListener { openPlayStore(playStoreUrl) }
|
||||
}
|
||||
|
||||
fun completeDownloadedUpdate() {
|
||||
appUpdateManager.completeUpdate()
|
||||
}
|
||||
|
||||
fun onUpdateFlowResult(resultCode: Int) {
|
||||
if (resultCode != Activity.RESULT_OK) {
|
||||
checkForUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
appUpdateManager.unregisterListener(installStateListener)
|
||||
}
|
||||
|
||||
private fun handleUpdateInfo(info: AppUpdateInfo) {
|
||||
val downloaded = info.installStatus() == InstallStatus.DOWNLOADED
|
||||
val available = info.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE ||
|
||||
info.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS ||
|
||||
downloaded
|
||||
|
||||
updateState(
|
||||
PlayAppUpdateState(
|
||||
updateAvailable = available,
|
||||
availableVersionCode = info.availableVersionCode().takeIf { it > 0 },
|
||||
downloaded = downloaded,
|
||||
checking = false,
|
||||
),
|
||||
)
|
||||
|
||||
if (
|
||||
info.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS &&
|
||||
info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)
|
||||
) {
|
||||
launchUpdate(info, AppUpdateType.IMMEDIATE)
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchUpdate(info: AppUpdateInfo, updateType: Int): Boolean =
|
||||
appUpdateManager.startUpdateFlowForResult(
|
||||
info,
|
||||
launcher,
|
||||
AppUpdateOptions.newBuilder(updateType).build(),
|
||||
)
|
||||
|
||||
private fun openPlayStore(playStoreUrl: String?) {
|
||||
val packageName = activity.packageName
|
||||
val candidates = listOf(
|
||||
Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName")).setPackage("com.android.vending"),
|
||||
Intent(
|
||||
Intent.ACTION_VIEW,
|
||||
Uri.parse(playStoreUrl?.takeIf { it.isNotBlank() }
|
||||
?: "https://play.google.com/store/apps/details?id=$packageName"),
|
||||
),
|
||||
)
|
||||
|
||||
for (intent in candidates) {
|
||||
try {
|
||||
activity.startActivity(intent)
|
||||
return
|
||||
} catch (_: ActivityNotFoundException) {
|
||||
// Try the browser fallback.
|
||||
} catch (_: SecurityException) {
|
||||
// Try the browser fallback.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateState(next: PlayAppUpdateState) {
|
||||
state = next
|
||||
onStateChanged(next)
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.4 MiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector
|
||||
android:height="108dp"
|
||||
android:width="108dp"
|
||||
android:viewportHeight="108"
|
||||
android:viewportWidth="108"
|
||||
xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="#FFFFFF"
|
||||
android:pathData="M0,0h108v108h-108z"/>
|
||||
</vector>
|
||||
|
After Width: | Height: | Size: 1010 KiB |
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
<monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
<monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 8.1 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 5.4 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 5.0 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 8.7 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 21 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#0B192E</color>
|
||||
</resources>
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">TPP Kierowca</string>
|
||||
<string name="app_name">Firma TPP - Kierowca</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.ITSTransport" parent="android:Theme.Material.Light.NoActionBar" />
|
||||
</resources>
|
||||
@@ -0,0 +1,117 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import java.io.IOException
|
||||
import java.net.UnknownHostException
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import retrofit2.HttpException
|
||||
import retrofit2.Response
|
||||
|
||||
class ApiErrorMapperTest {
|
||||
@Test
|
||||
fun rethrowsWorkerCancellationInsteadOfMappingItAsApplicationFailure() {
|
||||
val cancellation = CancellationException("Job was cancelled")
|
||||
|
||||
try {
|
||||
cancellation.rethrowIfCancellation()
|
||||
fail("CancellationException should be rethrown")
|
||||
} catch (thrown: CancellationException) {
|
||||
assertSame(cancellation, thrown)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapsNetworkFailuresToRetryableOfflineMessage() {
|
||||
val error = ApiErrorMapper.map(IOException("timeout"))
|
||||
|
||||
assertEquals(ApiErrorKind.Network, error.kind)
|
||||
assertTrue(error.retryable)
|
||||
assertEquals("Nie udało się połączyć z serwerem. Operacja nie została potwierdzona.", error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapsUnknownHostToActionableOfflineMessage() {
|
||||
val error = ApiErrorMapper.map(UnknownHostException("api-intranet.firmatpp.pl"))
|
||||
|
||||
assertEquals(ApiErrorKind.Network, error.kind)
|
||||
assertTrue(error.retryable)
|
||||
assertEquals(
|
||||
"Brak internetu lub połączenia z serwerem. Sprawdź zasięg i spróbuj ponownie.",
|
||||
error.message,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun doesNotReportExpectedNetworkFailuresAsNonFatal() {
|
||||
assertFalse(ApiErrorMapper.shouldReportNonFatal(UnknownHostException("api-intranet.firmatpp.pl")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapsMobileApiProblemCodes() {
|
||||
val error = ApiErrorMapper.mapProblem(
|
||||
statusCode = 422,
|
||||
code = "PHOTO_IDEMPOTENCY_CONFLICT",
|
||||
message = "Ten upload został już użyty dla innego zdjęcia.",
|
||||
retryable = false,
|
||||
)
|
||||
|
||||
assertEquals(ApiErrorKind.Validation, error.kind)
|
||||
assertFalse(error.retryable)
|
||||
assertEquals("PHOTO_IDEMPOTENCY_CONFLICT", error.code)
|
||||
assertEquals("Ten upload został już użyty dla innego zdjęcia.", error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapsServerErrorsToRetryableUnconfirmedMessage() {
|
||||
val error = ApiErrorMapper.mapHttpStatus(503, null)
|
||||
|
||||
assertEquals(ApiErrorKind.Server, error.kind)
|
||||
assertTrue(error.retryable)
|
||||
assertEquals("Serwer nie potwierdził operacji. Aplikacja spróbuje ponownie.", error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsRawServerResponseForTroubleshooting() {
|
||||
val body = """{"code":"PHOTO_SERVER_UNAVAILABLE","message":"Storage timeout","retryable":true}"""
|
||||
val error = ApiErrorMapper.mapHttpStatus(503, body)
|
||||
|
||||
assertEquals(ApiErrorKind.Server, error.kind)
|
||||
assertEquals(503, error.statusCode)
|
||||
assertEquals("PHOTO_SERVER_UNAVAILABLE", error.code)
|
||||
assertEquals("Storage timeout", error.message)
|
||||
assertEquals(body, error.responseBody)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapsInvalidOtpReasonToActionableMessage() {
|
||||
val error = ApiErrorMapper.mapHttpStatus(422, """{"ok":false,"reason":"INVALID_OTP"}""")
|
||||
|
||||
assertEquals("INVALID_OTP", error.code)
|
||||
assertEquals("Kod jest nieprawidłowy lub wygasł. Użyj kodu z najnowszego SMS-a.", error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun translatesRateLimitResponses() {
|
||||
val error = ApiErrorMapper.mapHttpStatus(429, """{"message":"Too Many Attempts."}""")
|
||||
|
||||
assertEquals(ApiErrorKind.RateLimited, error.kind)
|
||||
assertEquals("Za dużo prób. Odczekaj chwilę i spróbuj ponownie.", error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preservesApiProblemWhenSameExceptionIsMappedMoreThanOnce() {
|
||||
val body = """{"ok":false,"reason":"INVALID_OTP"}"""
|
||||
.toResponseBody("application/json".toMediaType())
|
||||
val exception = HttpException(Response.error<Any>(422, body))
|
||||
|
||||
assertEquals("INVALID_OTP", ApiErrorMapper.map(exception).code)
|
||||
assertEquals("INVALID_OTP", ApiErrorMapper.map(exception).code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.TestScope
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import pl.firmatpp.kierowca.ui.theme.AppThemeMode
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class AppPreferencesStoreTest {
|
||||
@get:Rule
|
||||
val temporaryFolder = TemporaryFolder()
|
||||
|
||||
@Test
|
||||
fun startsWithMaterial3ThemeMode() = runTest {
|
||||
val store = preferencesStore("default.preferences_pb")
|
||||
|
||||
assertEquals(AppThemeMode.Material3, store.themeMode.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistsSelectedThemeMode() = runTest {
|
||||
val file = temporaryFolder.newFile("theme.preferences_pb")
|
||||
val store = preferencesStore(file)
|
||||
|
||||
store.setThemeMode(AppThemeMode.Material3)
|
||||
|
||||
assertEquals(AppThemeMode.Material3, store.themeMode.first())
|
||||
}
|
||||
|
||||
private fun TestScope.preferencesStore(fileName: String): AppPreferencesStore =
|
||||
preferencesStore(temporaryFolder.newFile(fileName))
|
||||
|
||||
private fun TestScope.preferencesStore(file: File): AppPreferencesStore {
|
||||
val dataStore = PreferenceDataStoreFactory.create(scope = backgroundScope) { file }
|
||||
return AppPreferencesStore(dataStore)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package pl.firmatpp.kierowca.data
|
||||
|
||||
import okio.Buffer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Test
|
||||
|
||||
class PhotoUploadMetadataTest {
|
||||
@Test
|
||||
fun convertsPresentCameraMetadataToMultipartTextParts() {
|
||||
val parts = PhotoUploadMetadata(
|
||||
takenAt = "2026-06-30T07:38:12Z",
|
||||
latitude = 50.0619474,
|
||||
longitude = 19.9368564,
|
||||
locationAccuracyMeters = 8.5,
|
||||
).toMultipartTextParts()
|
||||
|
||||
assertEquals("2026-06-30T07:38:12Z", parts.getValue("takenAt").readUtf8())
|
||||
assertEquals("50.0619474", parts.getValue("latitude").readUtf8())
|
||||
assertEquals("19.9368564", parts.getValue("longitude").readUtf8())
|
||||
assertEquals("8.5", parts.getValue("locationAccuracyMeters").readUtf8())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipsLocationPartsWhenMetadataIsEmpty() {
|
||||
val parts = PhotoUploadMetadata().toMultipartTextParts()
|
||||
|
||||
assertFalse(parts.containsKey("latitude"))
|
||||
assertFalse(parts.containsKey("longitude"))
|
||||
assertFalse(parts.containsKey("locationAccuracyMeters"))
|
||||
}
|
||||
|
||||
private fun okhttp3.RequestBody.readUtf8(): String {
|
||||
val buffer = Buffer()
|
||||
writeTo(buffer)
|
||||
return buffer.readUtf8()
|
||||
}
|
||||
}
|
||||