Compare commits

..
14 changed files with 368 additions and 51 deletions
+2 -2
View File
@@ -34,8 +34,8 @@ android {
applicationId = "pl.firmatpp.kierowca" applicationId = "pl.firmatpp.kierowca"
minSdk = 26 minSdk = 26
targetSdk = 36 targetSdk = 36
versionCode = 131 versionCode = 133
versionName = "1.0.78" versionName = "1.0.80"
setProperty("archivesBaseName", "pl.firmatpp.kierowca") setProperty("archivesBaseName", "pl.firmatpp.kierowca")
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@@ -1,5 +1,6 @@
package pl.firmatpp.kierowca.data package pl.firmatpp.kierowca.data
import java.io.Serializable
import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.toRequestBody
@@ -9,7 +10,7 @@ data class PhotoUploadMetadata(
val latitude: Double? = null, val latitude: Double? = null,
val longitude: Double? = null, val longitude: Double? = null,
val locationAccuracyMeters: Double? = null, val locationAccuracyMeters: Double? = null,
) ) : Serializable
fun PhotoUploadMetadata.toMultipartTextParts(): Map<String, RequestBody> = buildMap { fun PhotoUploadMetadata.toMultipartTextParts(): Map<String, RequestBody> = buildMap {
takenAt?.let { put("takenAt", it.toPlainTextBody()) } takenAt?.let { put("takenAt", it.toPlainTextBody()) }
@@ -42,7 +42,10 @@ data class DriverDto(
val anonymousLabel: String?, val anonymousLabel: String?,
) )
data class DayPublicationDto(val date: String, val isVisible: Boolean, val version: Long)
data class BootstrapResponse( data class BootstrapResponse(
val dayPublication: DayPublicationDto? = null,
val session: DriverSessionDto, val session: DriverSessionDto,
val routes: RoutesBucketDto, val routes: RoutesBucketDto,
val driverAppSettings: DriverAppSettingsDto?, val driverAppSettings: DriverAppSettingsDto?,
@@ -37,6 +37,9 @@ interface DriverCacheDao {
@Query("DELETE FROM driver_bootstrap_cache") @Query("DELETE FROM driver_bootstrap_cache")
suspend fun clearBootstrap() suspend fun clearBootstrap()
@Query("DELETE FROM driver_route_cache WHERE routeId = :routeId")
suspend fun deleteRoute(routeId: String)
@Query("DELETE FROM driver_route_cache") @Query("DELETE FROM driver_route_cache")
suspend fun clearRoutes() suspend fun clearRoutes()
@@ -27,6 +27,13 @@ class DriverSyncRepository(
val response = repository.bootstrap(date) val response = repository.bootstrap(date)
val selectedDate = response.driverAppSettings?.selectedDate ?: requestedDate val selectedDate = response.driverAppSettings?.selectedDate ?: requestedDate
val routeState = response.syncState?.scopes?.firstOrNull { it.scope == SCOPE_ROUTES } val routeState = response.syncState?.scopes?.firstOrNull { it.scope == SCOPE_ROUTES }
if (response.dayPublication?.isVisible == false) {
// Previously downloaded details must not survive withdrawing a day.
dao.allRouteCaches().forEach { cached ->
val route = gson.fromJson(cached.payloadJson, RouteResponse::class.java).route
if (selectedDate in routeVisibleDates(route)) dao.deleteRoute(route.id)
}
}
dao.upsertBootstrap( dao.upsertBootstrap(
DriverBootstrapCacheEntity( DriverBootstrapCacheEntity(
date = selectedDate, date = selectedDate,
@@ -61,6 +68,7 @@ class DriverSyncRepository(
CachedValue(response, stale = false, syncedAtEpochMillis = System.currentTimeMillis()) CachedValue(response, stale = false, syncedAtEpochMillis = System.currentTimeMillis())
}.getOrElse { throwable -> }.getOrElse { throwable ->
throwable.rethrowIfCancellation() throwable.rethrowIfCancellation()
if (throwable is HttpException && throwable.code() == 404) dao.deleteRoute(routeId)
cachedRoute(routeId, throwable) cachedRoute(routeId, throwable)
} }
@@ -23,6 +23,16 @@ class DriverFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) { override fun onMessageReceived(message: RemoteMessage) {
val data = message.data val data = message.data
if (data["type"] == "driver_routes_published") {
NewRouteNotificationWorker.enqueuePublication(
context = applicationContext,
date = data["date"],
version = data["publicationVersion"]?.toLongOrNull(),
driverId = data["driverId"],
)
DriverSyncWorker.enqueue(applicationContext, data["date"], null)
return
}
if (data["type"] == "driver_new_route_notification") { if (data["type"] == "driver_new_route_notification") {
NewRouteNotificationWorker.enqueue( NewRouteNotificationWorker.enqueue(
context = applicationContext, context = applicationContext,
@@ -27,6 +27,7 @@ import pl.firmatpp.kierowca.data.ApiErrorKind
import pl.firmatpp.kierowca.data.ApiErrorMapper import pl.firmatpp.kierowca.data.ApiErrorMapper
import pl.firmatpp.kierowca.data.DriverRepository import pl.firmatpp.kierowca.data.DriverRepository
import pl.firmatpp.kierowca.data.rethrowIfCancellation 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.sync.NetworkMonitor
import pl.firmatpp.kierowca.diagnostics.AppDiagnostics import pl.firmatpp.kierowca.diagnostics.AppDiagnostics
import retrofit2.HttpException import retrofit2.HttpException
@@ -39,25 +40,41 @@ class NewRouteNotificationWorker(
override suspend fun doWork(): Result { override suspend fun doWork(): Result {
if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) return Result.retry() if (!NetworkMonitor(applicationContext).isCurrentlyValidated()) return Result.retry()
val routeId = inputData.getString(KEY_ROUTE_ID)?.takeIf(String::isNotBlank) ?: return Result.success() val routeId = inputData.getString(KEY_ROUTE_ID)?.takeIf(String::isNotBlank)
val publicationDate = inputData.getString(KEY_DATE)
val publicationVersion = inputData.getLong(KEY_PUBLICATION_VERSION, -1L)
val isPublication = publicationVersion >= 0L
if (!isPublication && routeId == null) return Result.success()
return runCatching { return runCatching {
val route = repository.route(routeId).route val route = if (isPublication) {
if (publicationDate.isNullOrBlank()) return@runCatching Result.success()
val bootstrap = DriverSyncRepository(applicationContext).bootstrap(publicationDate)
if (bootstrap.stale) return@runCatching Result.retry()
val publication = bootstrap.value.dayPublication
if (publication?.isVisible != true || publication.version != publicationVersion ||
bootstrap.value.notificationPreferences?.notifyNewRoutes != true ||
bootstrap.value.session.driver.id != inputData.getString(KEY_DRIVER_ID)) {
return@runCatching Result.success()
}
bootstrap.value.routes.today.firstOrNull() ?: return@runCatching Result.success()
} else repository.route(requireNotNull(routeId)).route
if (!canShowNotifications(applicationContext)) { if (!canShowNotifications(applicationContext)) {
return@runCatching Result.success() return@runCatching Result.success()
} }
createChannel(applicationContext) createChannel(applicationContext)
val contentTitle = NewRouteNotificationFormatter.title(route.routeDate ?: inputData.getString(KEY_DATE)) val contentTitle = if (isPublication) "Opublikowano kursy" else NewRouteNotificationFormatter.title(route.routeDate ?: publicationDate)
val contentText = NewRouteNotificationFormatter.collapsedText(route) val contentText = if (isPublication) PublishedRoutesNotificationFormatter.text(publicationDate) else NewRouteNotificationFormatter.collapsedText(route)
val expandedText = NewRouteNotificationFormatter.expandedText(route) val expandedText = if (isPublication) contentText else NewRouteNotificationFormatter.expandedText(route)
val notificationId = if (isPublication) "published-$publicationDate".hashCode() else route.id.hashCode()
val intent = Intent(applicationContext, MainActivity::class.java).apply { val intent = Intent(applicationContext, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
putExtra(MainActivity.EXTRA_ROUTE_ID, route.id) putExtra(MainActivity.EXTRA_ROUTE_ID, route.id)
} }
val pendingIntent = PendingIntent.getActivity( val pendingIntent = PendingIntent.getActivity(
applicationContext, applicationContext,
route.id.hashCode(), notificationId,
intent, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
) )
@@ -69,12 +86,13 @@ class NewRouteNotificationWorker(
.setStyle(NotificationCompat.BigTextStyle().bigText(expandedText)) .setStyle(NotificationCompat.BigTextStyle().bigText(expandedText))
.setContentIntent(pendingIntent) .setContentIntent(pendingIntent)
.setAutoCancel(true) .setAutoCancel(true)
.setOnlyAlertOnce(true)
.setCategory(NotificationCompat.CATEGORY_REMINDER) .setCategory(NotificationCompat.CATEGORY_REMINDER)
.setPriority(NotificationCompat.PRIORITY_DEFAULT) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build() .build()
try { try {
NotificationManagerCompat.from(applicationContext).notify(route.id.hashCode(), notification) NotificationManagerCompat.from(applicationContext).notify(notificationId, notification)
} catch (_: SecurityException) { } catch (_: SecurityException) {
return@runCatching Result.success() return@runCatching Result.success()
} }
@@ -125,6 +143,22 @@ class NewRouteNotificationWorker(
private const val CHANNEL_ID = "new_routes" private const val CHANNEL_ID = "new_routes"
private const val KEY_ROUTE_ID = "routeId" private const val KEY_ROUTE_ID = "routeId"
private const val KEY_DATE = "date" private const val KEY_DATE = "date"
private const val KEY_PUBLICATION_VERSION = "publicationVersion"
private const val KEY_DRIVER_ID = "driverId"
fun enqueuePublication(context: Context, date: String?, version: Long?, driverId: String?) {
if (date.isNullOrBlank() || version == null || version < 1L || driverId.isNullOrBlank()) return
val request = OneTimeWorkRequestBuilder<NewRouteNotificationWorker>()
.setInputData(workDataOf(KEY_DATE to date, KEY_PUBLICATION_VERSION to version, KEY_DRIVER_ID to driverId))
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
"driver-day-publication-$date",
ExistingWorkPolicy.REPLACE,
request,
)
}
fun enqueue(context: Context, routeId: String?, date: String?) { fun enqueue(context: Context, routeId: String?, date: String?) {
if (routeId.isNullOrBlank()) return if (routeId.isNullOrBlank()) return
@@ -0,0 +1,22 @@
package pl.firmatpp.kierowca.sync
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.format.DateTimeFormatter
object PublishedRoutesNotificationFormatter {
fun text(value: String?): String {
val date = runCatching { LocalDate.parse(value) }.getOrNull()
?: return "Opublikowano twoje kursy. Otwórz aplikację, aby je zobaczyć."
val weekday = when (date.dayOfWeek) {
DayOfWeek.MONDAY -> "poniedziałek"
DayOfWeek.TUESDAY -> "wtorek"
DayOfWeek.WEDNESDAY -> "środę"
DayOfWeek.THURSDAY -> "czwartek"
DayOfWeek.FRIDAY -> "piątek"
DayOfWeek.SATURDAY -> "sobotę"
DayOfWeek.SUNDAY -> "niedzielę"
}
return "Opublikowano twoje kursy na $weekday (${date.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"))})."
}
}
@@ -115,6 +115,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
@@ -1202,9 +1203,22 @@ private fun RoutesScreen(
val context = LocalContext.current val context = LocalContext.current
val coroutineScope = rememberCoroutineScope() val coroutineScope = rememberCoroutineScope()
var cameraUri by remember { mutableStateOf<Uri?>(null) } var cameraUri by remember { mutableStateOf<Uri?>(null) }
var cameraLocationMetadata by remember { mutableStateOf(PhotoUploadMetadata()) }
var cameraMetadataGeneration by remember { mutableStateOf(0L) }
var showPreciseLocationPermissionDialog by remember { mutableStateOf(false) } var showPreciseLocationPermissionDialog by remember { mutableStateOf(false) }
var showRouteDatePicker by remember { mutableStateOf(false) } var showRouteDatePicker by remember { mutableStateOf(false) }
var showTachographConfirmation by remember { mutableStateOf(false) } var showTachographConfirmation by remember { mutableStateOf(false) }
val prepareCameraMetadata = {
val generation = cameraMetadataGeneration + 1
cameraMetadataGeneration = generation
cameraLocationMetadata = PhotoUploadMetadata()
coroutineScope.launch {
val metadata = cameraPhotoMetadata(context).copy(takenAt = null)
if (cameraMetadataGeneration == generation) {
cameraLocationMetadata = metadata
}
}
}
val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { ok -> val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { ok ->
val capturedUri = cameraUri val capturedUri = cameraUri
if ( if (
@@ -1215,10 +1229,13 @@ private fun RoutesScreen(
hasFineLocation = hasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION), hasFineLocation = hasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION),
) )
) { ) {
coroutineScope.launch { onDispatchSheetUpload(
onDispatchSheetUpload(capturedUri, "camera", cameraPhotoMetadata(context)) capturedUri,
} "camera",
cameraLocationMetadata.copy(takenAt = Instant.now().toString()),
)
} }
cameraMetadataGeneration += 1
cameraUri = null cameraUri = null
} }
val cameraPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grants -> val cameraPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grants ->
@@ -1228,10 +1245,14 @@ private fun RoutesScreen(
hasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) hasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
if (!canLaunchCameraWithLocationPolicy(state.requirePreciseLocationForPhotos, fineLocationGranted)) { if (!canLaunchCameraWithLocationPolicy(state.requirePreciseLocationForPhotos, fineLocationGranted)) {
showPreciseLocationPermissionDialog = true showPreciseLocationPermissionDialog = true
cameraMetadataGeneration += 1
cameraUri = null cameraUri = null
return@rememberLauncherForActivityResult return@rememberLauncherForActivityResult
} }
if (cameraGranted && pendingUri != null) cameraLauncher.launch(pendingUri) if (cameraGranted && pendingUri != null) {
prepareCameraMetadata()
cameraLauncher.launch(pendingUri)
}
} }
LaunchedEffect(state.routeDayLiveUpdateMessage) { LaunchedEffect(state.routeDayLiveUpdateMessage) {
@@ -1339,6 +1360,7 @@ private fun RoutesScreen(
requirePreciseLocation = state.requirePreciseLocationForPhotos, requirePreciseLocation = state.requirePreciseLocationForPhotos,
) )
if (missingPermissions.isEmpty()) { if (missingPermissions.isEmpty()) {
prepareCameraMetadata()
cameraLauncher.launch(newUri) cameraLauncher.launch(newUri)
} else { } else {
cameraPermissionLauncher.launch(missingPermissions) cameraPermissionLauncher.launch(missingPermissions)
@@ -4441,21 +4463,28 @@ private fun RouteStageScreen(
) { ) {
val context = LocalContext.current val context = LocalContext.current
val coroutineScope = rememberCoroutineScope() val coroutineScope = rememberCoroutineScope()
var cameraUri by remember { mutableStateOf<Uri?>(null) } var cameraUri by rememberSaveable(stage) { mutableStateOf<Uri?>(null) }
var pendingCameraMode by remember { mutableStateOf<RouteStageCameraMode?>(null) } var pendingCameraMode by rememberSaveable(stage) { mutableStateOf<RouteStageCameraMode?>(null) }
var showMultiplePhotoCamera by remember(stage) { mutableStateOf(false) } var showMultiplePhotoCamera by rememberSaveable(stage) { mutableStateOf(false) }
var multiplePhotoLocationMetadata by remember(stage) { mutableStateOf(PhotoUploadMetadata()) } var multiplePhotoLocationMetadata by rememberSaveable(stage) { mutableStateOf(PhotoUploadMetadata()) }
var showPreciseLocationPermissionDialog by remember { mutableStateOf(false) } var showPreciseLocationPermissionDialog by rememberSaveable(stage) { mutableStateOf(false) }
var voiceDictationActive by remember(stage) { mutableStateOf(false) } var voiceDictationActive by remember(stage) { mutableStateOf(false) }
var cameraAttachmentTarget by remember(stage) { mutableStateOf<RouteWorkflowAttachmentTarget?>(null) } var cameraAttachmentTarget by rememberSaveable(stage) { mutableStateOf<RouteWorkflowAttachmentTarget?>(null) }
var pickerAttachmentTarget by remember(stage) { mutableStateOf<RouteWorkflowAttachmentTarget?>(null) } var pickerAttachmentTarget by rememberSaveable(stage) { mutableStateOf<RouteWorkflowAttachmentTarget?>(null) }
var singlePhotoLocationMetadata by rememberSaveable(stage) { mutableStateOf(PhotoUploadMetadata()) }
var singlePhotoMetadataGeneration by rememberSaveable(stage) { mutableStateOf(0L) }
val route = state.displaySelectedRoute val route = state.displaySelectedRoute
val stagePhotos = route?.photos?.let { routePhotosForStage(it, stage) }.orEmpty() val stagePhotos = route?.photos?.let { routePhotosForStage(it, stage) }.orEmpty()
val stageUploads = state.photoUploads.filter { normalizedRoutePhotoStage(it.stage) == stage } val stageUploads = state.photoUploads.filter { normalizedRoutePhotoStage(it.stage) == stage }
val stagePreparations = state.preparingPhotoUploads.filter { normalizedRoutePhotoStage(it.stage) == stage }
val usableStageUploads = routeStageUsableUploads(stageUploads) val usableStageUploads = routeStageUsableUploads(stageUploads)
val cargoStagePhotos = stagePhotos.filter { it.workflowDocumentId.isNullOrBlank() } val cargoStagePhotos = stagePhotos.filter { it.workflowDocumentId.isNullOrBlank() }
val cargoStageUploads = usableStageUploads.filter { it.workflowDocumentId.isNullOrBlank() } val cargoStageUploads = usableStageUploads.filter { it.workflowDocumentId.isNullOrBlank() }
val attachmentCount = visiblePhotoAttachmentCount(cargoStagePhotos.size, cargoStageUploads.size) val cargoStagePreparations = stagePreparations.filter { it.workflowDocumentId.isNullOrBlank() }
val attachmentCount = visiblePhotoAttachmentCount(
cargoStagePhotos.size,
cargoStageUploads.size + cargoStagePreparations.size,
)
val photoRequirement = if (stage == "loading") state.loadingPhotoRequirement else state.unloadingPhotoRequirement val photoRequirement = if (stage == "loading") state.loadingPhotoRequirement else state.unloadingPhotoRequirement
val weightRequirement = if (stage == "loading") state.loadingWeightRequirement else state.unloadingWeightRequirement val weightRequirement = if (stage == "loading") state.loadingWeightRequirement else state.unloadingWeightRequirement
val submitBlocker = if (state.routeWorkflow != null) { val submitBlocker = if (state.routeWorkflow != null) {
@@ -4494,9 +4523,21 @@ private fun RouteStageScreen(
submitBlocker submitBlocker
} }
val weightBlocker = submitBlocker?.takeIf { it.contains("wag", ignoreCase = true) || it.contains("popraw", ignoreCase = true) } val weightBlocker = submitBlocker?.takeIf { it.contains("wag", ignoreCase = true) || it.contains("popraw", ignoreCase = true) }
val prepareSinglePhotoMetadata = {
val generation = singlePhotoMetadataGeneration + 1
singlePhotoMetadataGeneration = generation
singlePhotoLocationMetadata = PhotoUploadMetadata()
coroutineScope.launch {
val metadata = cameraPhotoMetadata(context).copy(takenAt = null)
if (singlePhotoMetadataGeneration == generation) {
singlePhotoLocationMetadata = metadata
}
}
}
val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { ok -> val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { ok ->
val capturedUri = cameraUri val capturedUri = cameraUri
val attachmentTarget = cameraAttachmentTarget
if ( if (
ok && ok &&
capturedUri != null && capturedUri != null &&
@@ -4509,12 +4550,13 @@ private fun RouteStageScreen(
onUpload( onUpload(
capturedUri, capturedUri,
"camera", "camera",
cameraPhotoMetadata(context), singlePhotoLocationMetadata.copy(takenAt = Instant.now().toString()),
cameraAttachmentTarget?.stepId, attachmentTarget?.stepId,
cameraAttachmentTarget?.documentId, attachmentTarget?.documentId,
) )
} }
} }
singlePhotoMetadataGeneration += 1
cameraUri = null cameraUri = null
cameraAttachmentTarget = null cameraAttachmentTarget = null
} }
@@ -4533,6 +4575,7 @@ private fun RouteStageScreen(
hasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) hasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
if (!canLaunchCameraWithLocationPolicy(state.requirePreciseLocationForPhotos, fineLocationGranted)) { if (!canLaunchCameraWithLocationPolicy(state.requirePreciseLocationForPhotos, fineLocationGranted)) {
showPreciseLocationPermissionDialog = true showPreciseLocationPermissionDialog = true
singlePhotoMetadataGeneration += 1
cameraUri = null cameraUri = null
pendingCameraMode = null pendingCameraMode = null
return@rememberLauncherForActivityResult return@rememberLauncherForActivityResult
@@ -4540,7 +4583,10 @@ private fun RouteStageScreen(
if (cameraGranted) { if (cameraGranted) {
when (requestedMode) { when (requestedMode) {
RouteStageCameraMode.Single -> { RouteStageCameraMode.Single -> {
if (pendingUri != null) cameraLauncher.launch(pendingUri) if (pendingUri != null) {
prepareSinglePhotoMetadata()
cameraLauncher.launch(pendingUri)
}
} }
RouteStageCameraMode.Multiple -> { RouteStageCameraMode.Multiple -> {
openMultiplePhotoCamera() openMultiplePhotoCamera()
@@ -4553,28 +4599,30 @@ private fun RouteStageScreen(
pendingCameraMode = null pendingCameraMode = null
} }
val pickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> val pickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
val attachmentTarget = pickerAttachmentTarget
if (uri != null) { if (uri != null) {
coroutineScope.launch { coroutineScope.launch {
onUpload( onUpload(
uri, uri,
"gallery", "gallery",
PhotoUploadMetadata(), PhotoUploadMetadata(),
pickerAttachmentTarget?.stepId, attachmentTarget?.stepId,
pickerAttachmentTarget?.documentId, attachmentTarget?.documentId,
) )
} }
} }
pickerAttachmentTarget = null pickerAttachmentTarget = null
} }
val filePickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> val filePickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
val attachmentTarget = pickerAttachmentTarget
if (uri != null) { if (uri != null) {
coroutineScope.launch { coroutineScope.launch {
onUpload( onUpload(
uri, uri,
"file", "file",
PhotoUploadMetadata(), PhotoUploadMetadata(),
pickerAttachmentTarget?.stepId, attachmentTarget?.stepId,
pickerAttachmentTarget?.documentId, attachmentTarget?.documentId,
) )
} }
} }
@@ -4629,6 +4677,7 @@ private fun RouteStageScreen(
weightText = state.routeStageWeightText, weightText = state.routeStageWeightText,
serverPhotos = stagePhotos, serverPhotos = stagePhotos,
localUploads = usableStageUploads, localUploads = usableStageUploads,
preparingUploads = stagePreparations,
onStepToggle = onStepToggle, onStepToggle = onStepToggle,
onTakeDocumentPhoto = { stepId, documentId -> onTakeDocumentPhoto = { stepId, documentId ->
cameraAttachmentTarget = RouteWorkflowAttachmentTarget(stepId, documentId) cameraAttachmentTarget = RouteWorkflowAttachmentTarget(stepId, documentId)
@@ -4641,6 +4690,7 @@ private fun RouteStageScreen(
) )
if (missingPermissions.isEmpty()) { if (missingPermissions.isEmpty()) {
pendingCameraMode = null pendingCameraMode = null
prepareSinglePhotoMetadata()
cameraLauncher.launch(newUri) cameraLauncher.launch(newUri)
} else { } else {
cameraPermissionLauncher.launch(missingPermissions) cameraPermissionLauncher.launch(missingPermissions)
@@ -4726,6 +4776,7 @@ private fun RouteStageScreen(
) )
if (missingPermissions.isEmpty()) { if (missingPermissions.isEmpty()) {
pendingCameraMode = null pendingCameraMode = null
prepareSinglePhotoMetadata()
cameraLauncher.launch(newUri) cameraLauncher.launch(newUri)
} else { } else {
cameraPermissionLauncher.launch(missingPermissions) cameraPermissionLauncher.launch(missingPermissions)
@@ -4761,6 +4812,7 @@ private fun RouteStageScreen(
PhotoGrid( PhotoGrid(
photos = cargoStagePhotos, photos = cargoStagePhotos,
uploads = stageUploads.filter { it.workflowDocumentId.isNullOrBlank() }, uploads = stageUploads.filter { it.workflowDocumentId.isNullOrBlank() },
preparations = cargoStagePreparations,
deletingPhotoIds = state.deletingPhotoIds, deletingPhotoIds = state.deletingPhotoIds,
imageAuthHeader = state.imageAuthHeader, imageAuthHeader = state.imageAuthHeader,
onPhoto = onPhoto, onPhoto = onPhoto,
@@ -4807,7 +4859,7 @@ private fun RouteStageScreen(
private data class RouteWorkflowAttachmentTarget( private data class RouteWorkflowAttachmentTarget(
val stepId: String, val stepId: String,
val documentId: String, val documentId: String,
) ) : java.io.Serializable
@Composable @Composable
private fun RouteWorkflowStepsCard( private fun RouteWorkflowStepsCard(
@@ -4816,6 +4868,7 @@ private fun RouteWorkflowStepsCard(
weightText: String, weightText: String,
serverPhotos: List<RoutePhotoDto>, serverPhotos: List<RoutePhotoDto>,
localUploads: List<PhotoUploadEntity>, localUploads: List<PhotoUploadEntity>,
preparingUploads: List<PreparingPhotoUpload>,
onStepToggle: (String, Boolean) -> Unit, onStepToggle: (String, Boolean) -> Unit,
onTakeDocumentPhoto: (String, String) -> Unit, onTakeDocumentPhoto: (String, String) -> Unit,
onPickDocumentPhoto: (String, String) -> Unit, onPickDocumentPhoto: (String, String) -> Unit,
@@ -4902,7 +4955,10 @@ private fun RouteWorkflowStepsCard(
it.status != PhotoUploadStatus.Cancelled.storageValue && it.status != PhotoUploadStatus.Cancelled.storageValue &&
it.status != PhotoUploadStatus.FailedPermanent.storageValue it.status != PhotoUploadStatus.FailedPermanent.storageValue
} }
val count = documentServerPhotos.size + documentUploads.size val documentPreparations = preparingUploads.count {
it.workflowStepId == step.id && it.workflowDocumentId == document.id
}
val count = documentServerPhotos.size + documentUploads.size + documentPreparations
Column( Column(
Modifier Modifier
.fillMaxWidth() .fillMaxWidth()
@@ -5951,6 +6007,7 @@ private fun CargoActionButton(label: String, icon: ImageVector, color: Color, on
private fun PhotoGrid( private fun PhotoGrid(
photos: List<RoutePhotoDto>, photos: List<RoutePhotoDto>,
uploads: List<PhotoUploadEntity>, uploads: List<PhotoUploadEntity>,
preparations: List<PreparingPhotoUpload> = emptyList(),
deletingPhotoIds: Set<String>, deletingPhotoIds: Set<String>,
imageAuthHeader: String?, imageAuthHeader: String?,
onPhoto: (RoutePhotoDto) -> Unit, onPhoto: (RoutePhotoDto) -> Unit,
@@ -5960,9 +6017,13 @@ private fun PhotoGrid(
readOnly: Boolean = false, readOnly: Boolean = false,
) { ) {
var pendingDelete by remember { mutableStateOf<PhotoDeleteTarget?>(null) } var pendingDelete by remember { mutableStateOf<PhotoDeleteTarget?>(null) }
val items = (uploads.map { PhotoGridItem.Upload(it) } + photos.map { PhotoGridItem.Server(it) }) val items = (
preparations.map { PhotoGridItem.Preparing(it) } +
uploads.map { PhotoGridItem.Upload(it) } +
photos.map { PhotoGridItem.Server(it) }
)
.sortedByDescending { it.sortEpochMillis } .sortedByDescending { it.sortEpochMillis }
val visibleAttachmentCount = visiblePhotoAttachmentCount(photos.size, uploads.size) val visibleAttachmentCount = visiblePhotoAttachmentCount(photos.size, uploads.size + preparations.size)
Card( Card(
colors = CardDefaults.cardColors(containerColor = TppTheme.colors.card), colors = CardDefaults.cardColors(containerColor = TppTheme.colors.card),
@@ -6009,6 +6070,10 @@ private fun PhotoGrid(
readOnly = readOnly, readOnly = readOnly,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
is PhotoGridItem.Preparing -> PreparingPhotoTile(
preparation = item.preparation,
modifier = Modifier.weight(1f),
)
} }
} }
if (rowItems.size == 1) { if (rowItems.size == 1) {
@@ -6055,6 +6120,9 @@ private sealed class PhotoGridItem(open val sortEpochMillis: Long) {
) )
data class Upload(val upload: PhotoUploadEntity) : PhotoGridItem(upload.createdAtEpochMillis) data class Upload(val upload: PhotoUploadEntity) : PhotoGridItem(upload.createdAtEpochMillis)
data class Preparing(val preparation: PreparingPhotoUpload) :
PhotoGridItem(preparation.createdAtEpochMillis)
} }
private sealed class PhotoDeleteTarget { private sealed class PhotoDeleteTarget {
@@ -6288,6 +6356,40 @@ private fun PendingPhotoTile(
} }
} }
@Composable
private fun PreparingPhotoTile(
preparation: PreparingPhotoUpload,
modifier: Modifier = Modifier,
) {
Box(modifier.aspectRatio(1f).background(TppTheme.colors.panel, RoundedCornerShape(4.dp))) {
AsyncImage(
model = preparation.uri,
contentDescription = "Przygotowywane zdjęcie",
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
)
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.24f)))
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center).size(30.dp),
color = Color.White,
trackColor = Color.White.copy(alpha = 0.3f),
strokeWidth = 2.5.dp,
)
Text(
"Przygotowuję zdjęcie",
color = TppTheme.colors.ink,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.labelMedium,
modifier = Modifier
.align(Alignment.BottomStart)
.fillMaxWidth()
.background(Color.White.copy(alpha = 0.94f))
.padding(10.dp),
)
}
}
@Composable @Composable
private fun PhotoTileLoadingOverlay() { private fun PhotoTileLoadingOverlay() {
Box( Box(
@@ -0,0 +1,14 @@
package pl.firmatpp.kierowca.ui
import java.time.LocalDate
import pl.firmatpp.kierowca.data.model.DriverRouteDto
fun routeIncludesPublicationDate(route: DriverRouteDto?, date: String?): Boolean {
if (route == null || date == null) return false
return runCatching {
val day = LocalDate.parse(date)
val start = LocalDate.parse(route.routeDate)
val end = LocalDate.parse(route.unloadingDate ?: route.routeDate)
!day.isBefore(start) && !day.isAfter(end)
}.getOrDefault(false)
}
@@ -73,6 +73,16 @@ enum class DriverScreen { Initializing, Phone, Otp, Routes, Profile, Diagnostics
enum class ServerConnectionState { Unknown, Reachable, Degraded } enum class ServerConnectionState { Unknown, Reachable, Degraded }
data class PreparingPhotoUpload(
val id: String,
val routeId: String,
val uri: Uri,
val stage: String,
val workflowStepId: String?,
val workflowDocumentId: String?,
val createdAtEpochMillis: Long = System.currentTimeMillis(),
)
data class DriverUiState( data class DriverUiState(
val screen: DriverScreen = DriverScreen.Initializing, val screen: DriverScreen = DriverScreen.Initializing,
val loading: Boolean = true, val loading: Boolean = true,
@@ -111,6 +121,7 @@ data class DriverUiState(
val routeActions: List<RouteActionEntity> = emptyList(), val routeActions: List<RouteActionEntity> = emptyList(),
val visibleRouteActions: List<RouteActionEntity> = emptyList(), val visibleRouteActions: List<RouteActionEntity> = emptyList(),
val photoUploads: List<PhotoUploadEntity> = emptyList(), val photoUploads: List<PhotoUploadEntity> = emptyList(),
val preparingPhotoUploads: List<PreparingPhotoUpload> = emptyList(),
val queuedPhotoUploads: List<PhotoUploadEntity> = emptyList(), val queuedPhotoUploads: List<PhotoUploadEntity> = emptyList(),
val dispatchSheetReminder: DispatchSheetReminderDto? = null, val dispatchSheetReminder: DispatchSheetReminderDto? = null,
val tachographReminder: TachographReminderDto? = null, val tachographReminder: TachographReminderDto? = null,
@@ -633,6 +644,10 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
error = null, error = null,
) )
} }
if (!cached.stale && response.dayPublication?.isVisible == false &&
routeIncludesPublicationDate(_state.value.selectedRoute, response.dayPublication.date)) {
_state.value.selectedRoute?.id?.let(::closeUnavailableRoute)
}
response.session.driver.id.let { driverId -> response.session.driver.id.let { driverId ->
liveSyncClient.start(driverId, response.realtime) liveSyncClient.start(driverId, response.realtime)
if (_state.value.isOnline && !cached.stale) registerPushTokenIfAvailable(driverId) if (_state.value.isOnline && !cached.stale) registerPushTokenIfAvailable(driverId)
@@ -754,6 +769,8 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
if (generation != routeDetailRequestGeneration) return@onFailure if (generation != routeDetailRequestGeneration) return@onFailure
if (ApiErrorMapper.map(throwable).kind == ApiErrorKind.Auth) { if (ApiErrorMapper.map(throwable).kind == ApiErrorKind.Auth) {
handleExpiredSession() handleExpiredSession()
} else if (ApiErrorMapper.map(throwable).statusCode == 404) {
closeUnavailableRoute(routeId)
} else { } else {
_state.update { it.withApiError(throwable) } _state.update { it.withApiError(throwable) }
} }
@@ -763,6 +780,19 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
} }
} }
private fun closeUnavailableRoute(routeId: String) {
routeDetailRequestGeneration++
_state.update { current ->
if (current.selectedRoute?.id != routeId) current else current.copy(
selectedRoute = null,
selectedPhoto = null,
routes = current.routes.filterNot { it.id == routeId },
refreshing = false,
screen = if (current.screen in setOf(DriverScreen.Detail, DriverScreen.StartRoute, DriverScreen.LoadingWeight, DriverScreen.FinishRoute, DriverScreen.Photo)) DriverScreen.Routes else current.screen,
)
}
}
fun openProfile() { fun openProfile() {
_state.update { it.copy(screen = DriverScreen.Profile, error = null) } _state.update { it.copy(screen = DriverScreen.Profile, error = null) }
if ( if (
@@ -1496,23 +1526,46 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
_state.update { it.copy(error = "Zdjęcia możesz dodać tylko w zaplanowanym zakresie kursu.") } _state.update { it.copy(error = "Zdjęcia możesz dodać tylko w zaplanowanym zakresie kursu.") }
return null return null
} }
val preparation = PreparingPhotoUpload(
id = UUID.randomUUID().toString(),
routeId = route.id,
uri = uri,
stage = stage,
workflowStepId = workflowStepId,
workflowDocumentId = workflowDocumentId,
)
_state.update {
it.copy(
preparingPhotoUploads = it.preparingPhotoUploads + preparation,
error = null,
)
}
return viewModelScope.launch { return viewModelScope.launch {
_state.update { it.copy(error = null) } try {
runCatching { runCatching {
photoUploadOutbox.enqueue( photoUploadOutbox.enqueue(
routeId = route.id, routeId = route.id,
uri = uri, uri = uri,
source = source, source = source,
metadata = metadata, metadata = metadata,
stage = stage, stage = stage,
workflowVersion = snapshot.routeWorkflow?.version, workflowVersion = snapshot.routeWorkflow?.version,
workflowStepId = workflowStepId, workflowStepId = workflowStepId,
workflowDocumentId = workflowDocumentId, workflowDocumentId = workflowDocumentId,
) )
}
.onFailure { throwable ->
_state.update { it.withApiError(throwable) }
} }
.onFailure { throwable ->
_state.update { it.withApiError(throwable) }
}
} finally {
_state.update {
it.copy(
preparingPhotoUploads = it.preparingPhotoUploads.filterNot { item ->
item.id == preparation.id
},
)
}
}
} }
} }
@@ -2017,7 +2070,14 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
DriverScreen.Detail -> { DriverScreen.Detail -> {
photoUploadsJob?.cancel() photoUploadsJob?.cancel()
routeActionsJob?.cancel() routeActionsJob?.cancel()
it.copy(screen = DriverScreen.Routes, selectedRoute = null, routeActions = emptyList(), photoUploads = emptyList(), feedback = null) it.copy(
screen = DriverScreen.Routes,
selectedRoute = null,
routeActions = emptyList(),
photoUploads = emptyList(),
preparingPhotoUploads = emptyList(),
feedback = null,
)
} }
DriverScreen.Profile -> it.copy(screen = DriverScreen.Routes) DriverScreen.Profile -> it.copy(screen = DriverScreen.Routes)
DriverScreen.Diagnostics -> it.copy(screen = DriverScreen.Profile) DriverScreen.Diagnostics -> it.copy(screen = DriverScreen.Profile)
@@ -2239,6 +2299,7 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
val snapshot = _state.value val snapshot = _state.value
when (hint.scope) { when (hint.scope) {
DriverSyncRepository.SCOPE_ROUTES -> { DriverSyncRepository.SCOPE_ROUTES -> {
if (routeIncludesPublicationDate(snapshot.selectedRoute, hint.date)) refreshSelectedRoute()
if (shouldShowRouteDayLiveUpdate(snapshot.selectedDate, hint.date)) { if (shouldShowRouteDayLiveUpdate(snapshot.selectedDate, hint.date)) {
refreshRoutesSilently() refreshRoutesSilently()
if (snapshot.screen == DriverScreen.Routes) { if (snapshot.screen == DriverScreen.Routes) {
@@ -43,6 +43,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@@ -74,7 +75,7 @@ internal fun MultiplePhotoCameraScreen(
imageCaptureMode = ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY imageCaptureMode = ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY
} }
} }
var capturedCount by remember { mutableIntStateOf(0) } var capturedCount by rememberSaveable(stage) { mutableIntStateOf(0) }
var pendingUploads by remember { mutableIntStateOf(0) } var pendingUploads by remember { mutableIntStateOf(0) }
var isCapturing by remember { mutableStateOf(false) } var isCapturing by remember { mutableStateOf(false) }
var cameraUnavailable by remember { mutableStateOf(false) } var cameraUnavailable by remember { mutableStateOf(false) }
@@ -0,0 +1,20 @@
package pl.firmatpp.kierowca.sync
import org.junit.Assert.assertEquals
import org.junit.Test
class PublishedRoutesNotificationFormatterTest {
@Test
fun formatsPublicationWithPolishWeekdayAndUnambiguousDate() {
assertEquals("Opublikowano twoje kursy na poniedziałek (28.09.2026).", PublishedRoutesNotificationFormatter.text("2026-09-28"))
assertEquals("Opublikowano twoje kursy na środę (30.09.2026).", PublishedRoutesNotificationFormatter.text("2026-09-30"))
assertEquals("Opublikowano twoje kursy na niedzielę (04.10.2026).", PublishedRoutesNotificationFormatter.text("2026-10-04"))
}
@Test
fun handlesMissingAndInvalidDates() {
val fallback = "Opublikowano twoje kursy. Otwórz aplikację, aby je zobaczyć."
assertEquals(fallback, PublishedRoutesNotificationFormatter.text(null))
assertEquals(fallback, PublishedRoutesNotificationFormatter.text("invalid"))
}
}
@@ -0,0 +1,38 @@
package pl.firmatpp.kierowca.ui
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import pl.firmatpp.kierowca.data.model.DriverRouteDto
class DriverDayPublicationUiRulesTest {
private val route = DriverRouteDto(
id = "42", routeDate = "2026-09-28", unloadingDate = "2026-09-30",
startsAt = "09:00", originName = "Baza", destinationName = "Zakład",
contractorName = "Kontrahent", contractName = null, contractCode = null, relationLabel = "Baza → Zakład",
status = "ZAPLANOWANA", distanceKm = 20.0, notes = null, truck = null,
)
@Test
fun hidingAnyScheduledDayCanInvalidateOpenDetails() {
assertTrue(routeIncludesPublicationDate(route, "2026-09-28"))
assertTrue(routeIncludesPublicationDate(route, "2026-09-29"))
assertTrue(routeIncludesPublicationDate(route, "2026-09-30"))
}
@Test
fun unrelatedOrInvalidDatesMustNotCloseTheOpenRoute() {
assertFalse(routeIncludesPublicationDate(route, "2026-09-27"))
assertFalse(routeIncludesPublicationDate(route, "2026-10-01"))
assertFalse(routeIncludesPublicationDate(route, "invalid"))
assertFalse(routeIncludesPublicationDate(null, "2026-09-28"))
assertFalse(routeIncludesPublicationDate(route, null))
}
@Test
fun singleDayRoutesDoNotInheritTheNextDaysPublication() {
val singleDay = route.copy(unloadingDate = null)
assertTrue(routeIncludesPublicationDate(singleDay, "2026-09-28"))
assertFalse(routeIncludesPublicationDate(singleDay, "2026-09-29"))
}
}