Compare commits

..
Author SHA1 Message Date
admin 0564101e9e chore: release android driver 1.0.51 2026-07-10 22:35:04 +02:00
admin 2baa544b32 fix: reconcile leave requests in realtime 2026-07-10 22:32:13 +02:00
admin f9c3a2e305 Sortuj kursy kierowcy według dnia 2026-07-10 21:31:17 +02:00
admin e49e7c358e Obsłuż wielodniowe kursy kierowcy 2026-07-10 14:50:38 +02:00
admin 3267fee439 Usprawnij wybór urlopu przy konfliktach 2026-07-09 00:31:06 +02:00
15 changed files with 531 additions and 98 deletions
+2 -2
View File
@@ -34,8 +34,8 @@ android {
applicationId = "pl.firmatpp.kierowca" applicationId = "pl.firmatpp.kierowca"
minSdk = 26 minSdk = 26
targetSdk = 35 targetSdk = 35
versionCode = 101 versionCode = 104
versionName = "1.0.48" versionName = "1.0.51"
setProperty("archivesBaseName", "pl.firmatpp.kierowca") setProperty("archivesBaseName", "pl.firmatpp.kierowca")
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@@ -71,8 +71,8 @@ class DriverRepository(
suspend fun createLeaveRequest(dateFrom: String, dateTo: String, type: String, note: String?): DriverLeaveRequestDto = suspend fun createLeaveRequest(dateFrom: String, dateTo: String, type: String, note: String?): DriverLeaveRequestDto =
api.createLeaveRequest(authHeader(requireToken()), CreateLeaveRequestBody(dateFrom, dateTo, type, note)).data api.createLeaveRequest(authHeader(requireToken()), CreateLeaveRequestBody(dateFrom, dateTo, type, note)).data
suspend fun cancelLeaveRequest(id: String, comment: String? = null): DriverLeaveRequestDto = suspend fun cancelLeaveRequest(id: String, expectedVersion: Long, comment: String? = null): DriverLeaveRequestDto =
api.cancelLeaveRequest(authHeader(requireToken()), id, CancelLeaveRequestBody(comment)).data api.cancelLeaveRequest(authHeader(requireToken()), id, CancelLeaveRequestBody(comment, expectedVersion)).data
suspend fun completeRoute(routeId: String) = suspend fun completeRoute(routeId: String) =
api.completeRoute(authHeader(requireToken()), routeId) api.completeRoute(authHeader(requireToken()), routeId)
@@ -193,6 +193,7 @@ data class CreateLeaveRequestBody(
data class CancelLeaveRequestBody( data class CancelLeaveRequestBody(
val comment: String? = null, val comment: String? = null,
val expectedVersion: Long? = null,
) )
data class DriverLeaveRequestDto( data class DriverLeaveRequestDto(
@@ -204,6 +205,10 @@ data class DriverLeaveRequestDto(
val typeLabel: String? = null, val typeLabel: String? = null,
val note: String? = null, val note: String? = null,
val status: String, 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 submittedAt: String? = null,
val decidedAt: String? = null, val decidedAt: String? = null,
val decisionComment: String? = null, val decisionComment: String? = null,
@@ -244,6 +249,9 @@ data class RealtimeStatusBody(
data class DriverRouteDto( data class DriverRouteDto(
val id: String, val id: String,
val routeDate: String? = null, val routeDate: String? = null,
val unloadingDate: String? = null,
val ordering: Int? = null,
val dayOrderings: Map<String, Int>? = emptyMap(),
val startsAt: String, val startsAt: String,
val originName: String, val originName: String,
val destinationName: String, val destinationName: String,
@@ -3,6 +3,7 @@ package pl.firmatpp.kierowca.data.sync
import android.content.Context import android.content.Context
import com.google.gson.Gson import com.google.gson.Gson
import java.io.IOException import java.io.IOException
import java.time.LocalDate
import pl.firmatpp.kierowca.data.DriverRepository import pl.firmatpp.kierowca.data.DriverRepository
import pl.firmatpp.kierowca.data.model.BootstrapResponse import pl.firmatpp.kierowca.data.model.BootstrapResponse
import pl.firmatpp.kierowca.data.model.DriverRouteDto import pl.firmatpp.kierowca.data.model.DriverRouteDto
@@ -72,18 +73,19 @@ class DriverSyncRepository(
), ),
) )
val selectedDate = date ?: return (routeVisibleDates(route) + listOfNotNull(date)).distinct().forEach { selectedDate ->
val cachedBootstrap = dao.bootstrap(selectedDate) ?: return val cachedBootstrap = dao.bootstrap(selectedDate) ?: return@forEach
val response = gson.fromJson(cachedBootstrap.payloadJson, BootstrapResponse::class.java) val response = gson.fromJson(cachedBootstrap.payloadJson, BootstrapResponse::class.java)
val updatedRoutes = response.routes.today.map { item -> if (item.id == route.id) route else item } val updatedRoutes = response.routes.today.map { item -> if (item.id == route.id) route else item }
dao.upsertBootstrap( dao.upsertBootstrap(
cachedBootstrap.copy( cachedBootstrap.copy(
payloadJson = gson.toJson(response.copy(routes = response.routes.copy(today = updatedRoutes))), payloadJson = gson.toJson(response.copy(routes = response.routes.copy(today = updatedRoutes))),
checksum = null, checksum = null,
version = null, version = null,
syncedAtEpochMillis = syncedAt, syncedAtEpochMillis = syncedAt,
), ),
) )
}
} }
suspend fun fetchSyncState(date: String?, routeId: String?): SyncStateResponse = suspend fun fetchSyncState(date: String?, routeId: String?): SyncStateResponse =
@@ -96,21 +98,25 @@ class DriverSyncRepository(
suspend fun saveSyncStates(response: SyncStateResponse?) { suspend fun saveSyncStates(response: SyncStateResponse?) {
response?.scopes.orEmpty().forEach { scope -> response?.scopes.orEmpty().forEach { scope ->
dao.upsertSyncState( saveSyncScope(scope)
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 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() { suspend fun clearCache() {
dao.clearBootstrap() dao.clearBootstrap()
dao.clearRoutes() dao.clearRoutes()
@@ -146,11 +152,24 @@ class DriverSyncRepository(
private fun currentDateFallback(): String = java.time.LocalDate.now().toString() 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 { companion object {
const val SCOPE_ROUTES = "routes" const val SCOPE_ROUTES = "routes"
const val SCOPE_ROUTE_DETAIL = "route_detail" const val SCOPE_ROUTE_DETAIL = "route_detail"
const val SCOPE_SETTINGS = "settings" const val SCOPE_SETTINGS = "settings"
const val SCOPE_DISPATCH_SHEET = "dispatch_sheet" const val SCOPE_DISPATCH_SHEET = "dispatch_sheet"
const val SCOPE_LEAVE_REQUESTS = "leave_requests" const val SCOPE_LEAVE_REQUESTS = "leave_requests"
const val SCOPE_LEAVE_CALENDAR = "leave_calendar"
} }
} }
@@ -272,20 +272,22 @@ class DriverLiveSyncClient(
private fun subscribe(socket: WebSocket, socketId: String) { private fun subscribe(socket: WebSocket, socketId: String) {
val id = synchronized(lock) { driverId } ?: return val id = synchronized(lock) { driverId } ?: return
val channel = "private-driver-mobile.$id" val channels = listOf("private-driver-mobile.$id", "private-driver-mobile.0")
scope.launch { scope.launch {
runCatching { runCatching {
val auth = gateway.broadcastAuth(socketId, channel).auth channels.forEach { channel ->
if (!isCurrentSocket(socket)) return@launch val auth = gateway.broadcastAuth(socketId, channel).auth
val payload = mapOf( if (!isCurrentSocket(socket)) return@launch
"event" to "pusher:subscribe", val payload = mapOf(
"data" to mapOf( "event" to "pusher:subscribe",
"channel" to channel, "data" to mapOf(
"auth" to auth, "channel" to channel,
), "auth" to auth,
) ),
check(socket.send(gson.toJson(payload))) { "WebSocket send returned false" } )
check(socket.send(gson.toJson(payload))) { "WebSocket send returned false" }
}
}.onFailure { throwable -> }.onFailure { throwable ->
AppDiagnostics.log("realtime_subscription_error: ${throwable.message ?: throwable::class.java.simpleName}") AppDiagnostics.log("realtime_subscription_error: ${throwable.message ?: throwable::class.java.simpleName}")
socket.close(1000, "subscription_failed") socket.close(1000, "subscription_failed")
@@ -52,6 +52,10 @@ class DriverSyncWorker(
syncRepository.saveSyncStates(response) syncRepository.saveSyncStates(response)
refreshed = true refreshed = true
} }
DriverSyncRepository.SCOPE_LEAVE_CALENDAR -> {
syncRepository.saveSyncStates(response)
refreshed = true
}
} }
} }
} }
@@ -281,7 +281,7 @@ fun DriverApp(
title = "Waga załadunku", title = "Waga załadunku",
stage = "loading", stage = "loading",
weightLabel = "Waga z wagi", weightLabel = "Waga z wagi",
submitLabel = "Rozpocznij kurs", submitLabel = "Załaduj",
showWeightInput = true, showWeightInput = true,
showPhotoActions = false, showPhotoActions = false,
showPhotoGrid = false, showPhotoGrid = false,
@@ -295,10 +295,10 @@ fun DriverApp(
) )
DriverScreen.FinishRoute -> RouteStageScreen( DriverScreen.FinishRoute -> RouteStageScreen(
state = state, state = state,
title = "Zakończ kurs", title = "Rozładunek",
stage = "unloading", stage = "unloading",
weightLabel = "Waga na rozładunku", weightLabel = "Waga na rozładunku",
submitLabel = "Zakończ kurs", submitLabel = "Rozładuj",
onBack = viewModel::back, onBack = viewModel::back,
onWeightChange = viewModel::updateRouteStageWeight, onWeightChange = viewModel::updateRouteStageWeight,
onUpload = { uri, source, metadata -> viewModel.uploadPhoto(uri, source, metadata, "unloading") }, onUpload = { uri, source, metadata -> viewModel.uploadPhoto(uri, source, metadata, "unloading") },
@@ -1053,10 +1053,23 @@ private fun LeaveCalendarScreen(
val context = LocalContext.current val context = LocalContext.current
val listState = rememberLazyListState() val listState = rememberLazyListState()
val months = remember(state.leaveCalendarLoadedUntil) { leaveCalendarMonths(state.leaveCalendarLoadedUntil) } val months = remember(state.leaveCalendarLoadedUntil) { leaveCalendarMonths(state.leaveCalendarLoadedUntil) }
var detailsDate by remember { mutableStateOf<LocalDate?>(null) } var showConflictDetails by remember { mutableStateOf(false) }
val detailsEntries = detailsDate val selectedConflictEntries = remember(
?.let { DriverLeaveRequestUiRules.calendarEntriesForDate(state.leaveCalendarEntries, it) } state.leaveCalendarEntries,
.orEmpty() state.leaveCalendarHasSelection,
state.leaveRequestDateFrom,
state.leaveRequestDateTo,
) {
if (state.leaveCalendarHasSelection) {
DriverLeaveRequestUiRules.calendarEntriesForRange(
entries = state.leaveCalendarEntries,
dateFrom = state.leaveRequestDateFrom,
dateTo = state.leaveRequestDateTo,
)
} else {
emptyList()
}
}
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
LaunchedEffect(months.size, state.leaveCalendarLoading) { LaunchedEffect(months.size, state.leaveCalendarLoading) {
@@ -1074,6 +1087,8 @@ private fun LeaveCalendarScreen(
bottomBar = { bottomBar = {
LeaveCalendarContinueBar( LeaveCalendarContinueBar(
state = state, state = state,
conflictCount = selectedConflictEntries.size,
onShowConflicts = { showConflictDetails = true },
onContinue = onContinue, onContinue = onContinue,
) )
}, },
@@ -1093,11 +1108,8 @@ private fun LeaveCalendarScreen(
selectedFrom = state.leaveRequestDateFrom, selectedFrom = state.leaveRequestDateFrom,
selectedTo = state.leaveRequestDateTo, selectedTo = state.leaveRequestDateTo,
hasSelection = state.leaveCalendarHasSelection, hasSelection = state.leaveCalendarHasSelection,
onDayClick = { date, entries -> onDayClick = { date, _ ->
onDateSelected(date.toString()) onDateSelected(date.toString())
if (entries.isNotEmpty()) {
detailsDate = date
}
}, },
) )
} }
@@ -1121,15 +1133,15 @@ private fun LeaveCalendarScreen(
} }
} }
if (detailsDate != null && detailsEntries.isNotEmpty()) { if (showConflictDetails && selectedConflictEntries.isNotEmpty()) {
ModalBottomSheet( ModalBottomSheet(
onDismissRequest = { detailsDate = null }, onDismissRequest = { showConflictDetails = false },
sheetState = sheetState, sheetState = sheetState,
containerColor = TppTheme.colors.card, containerColor = TppTheme.colors.card,
) { ) {
LeaveCalendarDetailsSheet( LeaveCalendarDetailsSheet(
date = detailsDate, title = "Urlopy w wybranym terminie",
entries = detailsEntries, entries = selectedConflictEntries,
onCall = { dialUri -> onCall = { dialUri ->
context.startActivity(Intent(Intent.ACTION_DIAL, Uri.parse(dialUri))) context.startActivity(Intent(Intent.ACTION_DIAL, Uri.parse(dialUri)))
}, },
@@ -1139,7 +1151,12 @@ private fun LeaveCalendarScreen(
} }
@Composable @Composable
private fun LeaveCalendarContinueBar(state: DriverUiState, onContinue: () -> Unit) { private fun LeaveCalendarContinueBar(
state: DriverUiState,
conflictCount: Int,
onShowConflicts: () -> Unit,
onContinue: () -> Unit,
) {
val selectionText = when { val selectionText = when {
!state.leaveCalendarHasSelection -> "Wybierz pierwszy dzień urlopu" !state.leaveCalendarHasSelection -> "Wybierz pierwszy dzień urlopu"
else -> leaveDateRange(state.leaveRequestDateFrom, state.leaveRequestDateTo) else -> leaveDateRange(state.leaveRequestDateFrom, state.leaveRequestDateTo)
@@ -1178,6 +1195,28 @@ private fun LeaveCalendarContinueBar(state: DriverUiState, onContinue: () -> Uni
Text("Dalej", fontWeight = FontWeight.Bold) Text("Dalej", fontWeight = FontWeight.Bold)
} }
} }
if (state.leaveCalendarHasSelection && conflictCount > 0) {
Row(
Modifier
.fillMaxWidth()
.background(TppTheme.colors.warningContainer, RoundedCornerShape(4.dp))
.border(1.dp, TppTheme.colors.warningOutline, RoundedCornerShape(4.dp))
.padding(horizontal = 12.dp, vertical = 10.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Outlined.Info, contentDescription = null, tint = Color(0xFF7A5A00), modifier = Modifier.size(20.dp))
Text(
"Nakłada się z ${leaveConflictCountLabel(conflictCount)}",
color = Color(0xFF7A5A00),
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f),
)
TextButton(onClick = onShowConflicts) {
Text("Zobacz", color = TppTheme.colors.forest, fontWeight = FontWeight.Bold)
}
}
}
} }
} }
@@ -1307,7 +1346,7 @@ private fun LeaveCalendarDayCell(
@Composable @Composable
private fun LeaveCalendarDetailsSheet( private fun LeaveCalendarDetailsSheet(
date: LocalDate?, title: String,
entries: List<DriverLeaveCalendarEntryDto>, entries: List<DriverLeaveCalendarEntryDto>,
onCall: (String) -> Unit, onCall: (String) -> Unit,
) { ) {
@@ -1316,7 +1355,7 @@ private fun LeaveCalendarDetailsSheet(
verticalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
Text( Text(
date?.let { DateTimeFormatter.ofPattern("d MMMM yyyy", Locale("pl", "PL")).format(it) } ?: "Urlopy w tym dniu", title,
color = TppTheme.colors.ink, color = TppTheme.colors.ink,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
fontSize = 22.sp, fontSize = 22.sp,
@@ -1991,6 +2030,8 @@ private fun StitchRouteCard(route: DriverRouteDto, onRoute: (String) -> Unit) {
) )
} }
} }
Spacer(Modifier.height(12.dp))
RouteScheduleLabel(route)
Spacer(Modifier.height(if (compactWidth) 18.dp else 26.dp)) Spacer(Modifier.height(if (compactWidth) 18.dp else 26.dp))
RouteTimeline(display.origin, display.destination) RouteTimeline(display.origin, display.destination)
} }
@@ -2022,6 +2063,21 @@ private fun StatusChip(status: String, color: Color) {
) )
} }
@Composable
private fun RouteScheduleLabel(route: DriverRouteDto) {
Text(
routeScheduleSummary(route),
modifier = Modifier
.fillMaxWidth()
.background(TppTheme.colors.panel, RoundedCornerShape(4.dp))
.padding(horizontal = 10.dp, vertical = 8.dp),
color = TppTheme.colors.muted,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.SemiBold,
style = MaterialTheme.typography.labelMedium,
)
}
@Composable @Composable
private fun RouteTimeline(origin: String, destination: String) { private fun RouteTimeline(origin: String, destination: String) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(14.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(14.dp)) {
@@ -2735,9 +2791,19 @@ private fun RouteLifecycleSection(
val steps = routeFlowSteps(route, routeActions) val steps = routeFlowSteps(route, routeActions)
val callout = routeSyncCallout(routeActions) val callout = routeSyncCallout(routeActions)
val action = routeLifecyclePrimaryAction(route, selectedDate) val action = routeLifecyclePrimaryAction(route, selectedDate)
val instruction = routeTodayInstruction(route, selectedDate)
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) { Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
RouteFlowStepper(steps) RouteFlowStepper(steps)
if (instruction != null) {
RouteStateMessage(
text = instruction,
icon = Icons.Outlined.Info,
container = TppTheme.colors.panel,
outline = TppTheme.colors.outline,
color = TppTheme.colors.ink,
)
}
if (!feedback.isNullOrBlank()) { if (!feedback.isNullOrBlank()) {
RouteStateMessage( RouteStateMessage(
text = feedback, text = feedback,
@@ -2846,6 +2912,15 @@ private fun RouteFlowStepItem(step: RouteFlowStepUi, modifier: Modifier = Modifi
maxLines = 2, maxLines = 2,
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
if (step.dateLabel != null) {
Text(
step.dateLabel,
color = TppTheme.colors.muted,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.SemiBold,
style = MaterialTheme.typography.labelSmall,
)
}
Text( Text(
step.stateLabel, step.stateLabel,
color = color, color = color,
@@ -2926,6 +3001,9 @@ private fun photoCountLabel(count: Int): String =
else -> "zdjęć" else -> "zdjęć"
} }
private fun leaveConflictCountLabel(count: Int): String =
if (count == 1) "1 urlopem" else "$count urlopami"
@Composable @Composable
private fun ManifestSection(route: DriverRouteDto, selectedDate: String, onNavigate: (NavigationPointDto) -> Unit) { private fun ManifestSection(route: DriverRouteDto, selectedDate: String, onNavigate: (NavigationPointDto) -> Unit) {
val stripColor = routeStatusColor(route.status) val stripColor = routeStatusColor(route.status)
@@ -2954,6 +3032,7 @@ private fun ManifestSection(route: DriverRouteDto, selectedDate: String, onNavig
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
color = TppTheme.colors.ink, color = TppTheme.colors.ink,
) )
RouteScheduleLabel(route)
} }
} }
HorizontalDivider(color = TppTheme.colors.outline.copy(alpha = 0.65f)) HorizontalDivider(color = TppTheme.colors.outline.copy(alpha = 0.65f))
@@ -61,6 +61,19 @@ object DriverLeaveRequestUiRules {
from != null && to != null && !date.isBefore(from) && !date.isAfter(to) 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? { fun phoneDialUri(phoneNumber: String?): String? {
val raw = phoneNumber?.trim().orEmpty() val raw = phoneNumber?.trim().orEmpty()
if (raw.isBlank()) return null if (raw.isBlank()) return null
@@ -34,6 +34,7 @@ data class RouteFlowStepUi(
val title: String, val title: String,
val state: RouteFlowStepState, val state: RouteFlowStepState,
val stateLabel: String, val stateLabel: String,
val dateLabel: String? = null,
) )
data class RouteLifecycleActionUi( data class RouteLifecycleActionUi(
@@ -49,12 +50,68 @@ data class RouteSyncCalloutUi(
fun canManageRoutePhotos(selectedDate: String, today: LocalDate = LocalDate.now()): Boolean = fun canManageRoutePhotos(selectedDate: String, today: LocalDate = LocalDate.now()): Boolean =
runCatching { LocalDate.parse(selectedDate).isEqual(today) }.getOrDefault(false) 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.status == "ZAKOŃCZONA" -> "Kurs zakończony."
loadingDate == unloadingDate -> "Dziś: załadunek i rozładunek."
today == loadingDate -> "Dziś: załadunek."
today == unloadingDate && route.status == "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( fun canCompleteRouteFromDriverApp(
route: DriverRouteDto, route: DriverRouteDto,
selectedDate: String, selectedDate: String,
today: LocalDate = LocalDate.now(), today: LocalDate = LocalDate.now(),
): Boolean = ): Boolean =
canManageRoutePhotos(selectedDate, today) runCatching { LocalDate.parse(selectedDate) }.getOrNull() == today
&& routeUnloadingDate(route)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } == today
&& route.status in setOf("ZAPLANOWANA", "W TRAKCIE") && route.status in setOf("ZAPLANOWANA", "W TRAKCIE")
fun canStartRouteFromDriverApp( fun canStartRouteFromDriverApp(
@@ -62,7 +119,7 @@ fun canStartRouteFromDriverApp(
selectedDate: String, selectedDate: String,
today: LocalDate = LocalDate.now(), today: LocalDate = LocalDate.now(),
): Boolean = ): Boolean =
canManageRoutePhotos(selectedDate, today) routeIsActiveToday(route, selectedDate, today)
&& route.status == "ZAPLANOWANA" && route.status == "ZAPLANOWANA"
fun canFinishRouteFromDriverApp( fun canFinishRouteFromDriverApp(
@@ -70,8 +127,9 @@ fun canFinishRouteFromDriverApp(
selectedDate: String, selectedDate: String,
today: LocalDate = LocalDate.now(), today: LocalDate = LocalDate.now(),
): Boolean = ): Boolean =
canManageRoutePhotos(selectedDate, today) route.status == "W TRAKCIE"
&& route.status == "W TRAKCIE" && runCatching { LocalDate.parse(selectedDate) }.getOrNull() == today
&& routeUnloadingDate(route)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } == today
fun canSubmitRouteStageForm(weightText: String, serverPhotoCount: Int, localUploadCount: Int): Boolean { fun canSubmitRouteStageForm(weightText: String, serverPhotoCount: Int, localUploadCount: Int): Boolean {
return routeStageSubmitBlocker(weightText, serverPhotoCount, localUploadCount) == null return routeStageSubmitBlocker(weightText, serverPhotoCount, localUploadCount) == null
@@ -116,8 +174,8 @@ fun routeLifecyclePrimaryAction(
today: LocalDate = LocalDate.now(), today: LocalDate = LocalDate.now(),
): RouteLifecycleActionUi? = ): RouteLifecycleActionUi? =
when { when {
canStartRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Rozpocznij kurs", RouteLifecycleAction.Start) canStartRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Załaduj", RouteLifecycleAction.Start)
canFinishRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Zakończ kurs", RouteLifecycleAction.Finish) canFinishRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Rozładuj", RouteLifecycleAction.Finish)
else -> null else -> null
} }
@@ -175,10 +233,10 @@ fun routeFlowSteps(route: DriverRouteDto, actions: List<RouteActionEntity>): Lis
} }
return listOf( return listOf(
RouteFlowStepUi("loading_photos", "Zdjęcia załadunku", loadingPhotosState, routeFlowStateLabel(loadingPhotosState)), RouteFlowStepUi("loading_photos", "Zdjęcia załadunku", loadingPhotosState, routeFlowStateLabel(loadingPhotosState), routeScheduleDateLabel(route.routeDate)),
RouteFlowStepUi("loading_weight", "Waga załadunku", loadingWeightState, routeFlowStateLabel(loadingWeightState)), RouteFlowStepUi("loading_weight", "Waga załadunku", loadingWeightState, routeFlowStateLabel(loadingWeightState), routeScheduleDateLabel(route.routeDate)),
RouteFlowStepUi("transit", "W trasie", transitState, routeFlowStateLabel(transitState)), RouteFlowStepUi("transit", "W trasie", transitState, routeFlowStateLabel(transitState)),
RouteFlowStepUi("unloading", "Rozładunek", unloadingState, routeFlowStateLabel(unloadingState)), RouteFlowStepUi("unloading", "Rozładunek", unloadingState, routeFlowStateLabel(unloadingState), routeScheduleDateLabel(routeUnloadingDate(route))),
) )
} }
@@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import java.time.LocalDate import java.time.LocalDate
import java.time.Instant import java.time.Instant
import pl.firmatpp.kierowca.data.AppPreferencesStore import pl.firmatpp.kierowca.data.AppPreferencesStore
@@ -96,6 +97,10 @@ data class DriverUiState(
val displayRoutes: List<DriverRouteDto> val displayRoutes: List<DriverRouteDto>
get() = projectDriverRoutes(routes, projectionActions) get() = projectDriverRoutes(routes, projectionActions)
.sortedWith(
compareBy<DriverRouteDto> { route -> if (route.status == "ZAKOŃCZONA") 1 else 0 }
.thenBy { route -> routeDayOrdering(route, selectedDate) },
)
val selectedRouteProjection: ProjectedDriverRoute? val selectedRouteProjection: ProjectedDriverRoute?
get() = selectedRoute?.let { projectDriverRoute(it, projectionActions) } get() = selectedRoute?.let { projectDriverRoute(it, projectionActions) }
@@ -117,12 +122,17 @@ internal fun DriverUiState.withLoadedLeaveRequests(
requests: List<DriverLeaveRequestDto>, requests: List<DriverLeaveRequestDto>,
navigateToList: Boolean, navigateToList: Boolean,
): DriverUiState { ): DriverUiState {
val currentById = leaveRequests.associateBy { it.id }
val merged = requests.map { incoming ->
currentById[incoming.id]?.takeIf { current -> current.version > incoming.version } ?: incoming
}.toMutableList()
leaveRequests.filter { current -> requests.none { it.id == current.id } }.forEach(merged::add)
val refreshedSelectedRequest = selectedLeaveRequest?.let { selected -> val refreshedSelectedRequest = selectedLeaveRequest?.let { selected ->
requests.firstOrNull { request -> request.id == selected.id } ?: selected merged.firstOrNull { request -> request.id == selected.id }?.takeIf { it.version >= selected.version } ?: selected
} }
return copy( return copy(
screen = if (navigateToList) DriverScreen.LeaveRequests else screen, screen = if (navigateToList) DriverScreen.LeaveRequests else screen,
leaveRequests = requests, leaveRequests = merged,
selectedLeaveRequest = refreshedSelectedRequest, selectedLeaveRequest = refreshedSelectedRequest,
error = null, error = null,
) )
@@ -147,6 +157,9 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
private var routeActionsJob: Job? = null private var routeActionsJob: Job? = null
private var dispatchSheetUploadsJob: Job? = null private var dispatchSheetUploadsJob: Job? = null
private var pushTokenRegisteredForDriverId: String? = null private var pushTokenRegisteredForDriverId: String? = null
private val leaveMutationMutex = Mutex()
private var pendingLeaveHint: DriverSyncHint? = null
private var leaveCalendarRequestGeneration: Long = 0
val state: StateFlow<DriverUiState> = _state val state: StateFlow<DriverUiState> = _state
init { init {
@@ -415,24 +428,22 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
fun openLeaveRequests() { fun openLeaveRequests() {
if (!DriverLeaveRequestUiRules.isFeatureVisible(_state.value.leaveRequestsConfig)) return if (!DriverLeaveRequestUiRules.isFeatureVisible(_state.value.leaveRequestsConfig)) return
loadLeaveRequests(showLoading = true, navigateToList = true) viewModelScope.launch { loadLeaveRequests(showLoading = true, navigateToList = true) }
} }
fun refreshLeaveRequests() { fun refreshLeaveRequests() {
if (!DriverLeaveRequestUiRules.isFeatureVisible(_state.value.leaveRequestsConfig)) return if (!DriverLeaveRequestUiRules.isFeatureVisible(_state.value.leaveRequestsConfig)) return
loadLeaveRequests(showLoading = false, navigateToList = false) viewModelScope.launch { loadLeaveRequests(showLoading = false, navigateToList = false) }
} }
private fun loadLeaveRequests(showLoading: Boolean, navigateToList: Boolean) { private suspend fun loadLeaveRequests(showLoading: Boolean, navigateToList: Boolean): Boolean {
viewModelScope.launch { _state.update { it.copy(loading = showLoading, refreshing = !showLoading, error = null, feedback = null) }
_state.update { it.copy(loading = showLoading, refreshing = !showLoading, error = null, feedback = null) } val result = runCatching { repository.leaveRequests() }
runCatching { repository.leaveRequests() } result.onSuccess { requests ->
.onSuccess { requests -> _state.update { it.withLoadedLeaveRequests(requests, navigateToList) }
_state.update { it.withLoadedLeaveRequests(requests, navigateToList) } }.onFailure { throwable -> _state.update { it.withApiError(throwable) } }
} _state.update { it.copy(loading = false, refreshing = false) }
.onFailure { throwable -> _state.update { it.withApiError(throwable) } } return result.isSuccess
_state.update { it.copy(loading = false, refreshing = false) }
}
} }
fun openLeaveRequest(id: String) { fun openLeaveRequest(id: String) {
@@ -546,6 +557,7 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
runCatching { LocalDate.parse(snapshot.leaveCalendarLoadedUntil).plusDays(1) }.getOrDefault(LocalDate.now()) runCatching { LocalDate.parse(snapshot.leaveCalendarLoadedUntil).plusDays(1) }.getOrDefault(LocalDate.now())
} }
val to = from.plusMonths(6).minusDays(1) val to = from.plusMonths(6).minusDays(1)
val generation = ++leaveCalendarRequestGeneration
viewModelScope.launch { viewModelScope.launch {
_state.update { _state.update {
@@ -558,6 +570,7 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
} }
runCatching { repository.leaveCalendar(from.toString(), to.toString()) } runCatching { repository.leaveCalendar(from.toString(), to.toString()) }
.onSuccess { entries -> .onSuccess { entries ->
if (generation != leaveCalendarRequestGeneration) return@onSuccess
_state.update { _state.update {
val merged = (it.leaveCalendarEntries + entries) val merged = (it.leaveCalendarEntries + entries)
.distinctBy { entry -> entry.id } .distinctBy { entry -> entry.id }
@@ -571,6 +584,7 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
} }
} }
.onFailure { throwable -> .onFailure { throwable ->
if (generation != leaveCalendarRequestGeneration) return@onFailure
_state.update { it.withApiError(throwable).copy(leaveCalendarLoading = false) } _state.update { it.withApiError(throwable).copy(leaveCalendarLoading = false) }
} }
} }
@@ -579,13 +593,16 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
fun submitLeaveRequest() { fun submitLeaveRequest() {
val snapshot = _state.value val snapshot = _state.value
if (!DriverLeaveRequestUiRules.isFeatureVisible(snapshot.leaveRequestsConfig)) return if (!DriverLeaveRequestUiRules.isFeatureVisible(snapshot.leaveRequestsConfig)) return
if (!leaveMutationMutex.tryLock()) return
if (snapshot.leaveRequestDateFrom < LocalDate.now().toString()) { if (snapshot.leaveRequestDateFrom < LocalDate.now().toString()) {
_state.update { it.copy(error = "Data od nie może być z przeszłości.") } _state.update { it.copy(error = "Data od nie może być z przeszłości.") }
leaveMutationMutex.unlock()
return return
} }
viewModelScope.launch { viewModelScope.launch {
_state.update { it.copy(loading = true, error = null, feedback = null) } _state.update { it.copy(loading = true, error = null, feedback = null) }
try {
runCatching { runCatching {
repository.createLeaveRequest( repository.createLeaveRequest(
dateFrom = snapshot.leaveRequestDateFrom, dateFrom = snapshot.leaveRequestDateFrom,
@@ -608,16 +625,22 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
_state.update { it.withApiError(throwable) } _state.update { it.withApiError(throwable) }
} }
_state.update { it.copy(loading = false) } _state.update { it.copy(loading = false) }
} finally {
leaveMutationMutex.unlock()
consumePendingLeaveHint()
}
} }
} }
fun cancelSelectedLeaveRequest() { fun cancelSelectedLeaveRequest() {
val request = _state.value.selectedLeaveRequest ?: return val request = _state.value.selectedLeaveRequest ?: return
if (!DriverLeaveRequestUiRules.canCancel(request.status, request.dateFrom.orEmpty())) return if (!DriverLeaveRequestUiRules.canCancel(request.status, request.dateFrom.orEmpty())) return
if (!leaveMutationMutex.tryLock()) return
viewModelScope.launch { viewModelScope.launch {
_state.update { it.copy(loading = true, error = null, feedback = null) } _state.update { it.copy(loading = true, error = null, feedback = null) }
runCatching { repository.cancelLeaveRequest(request.id) } try {
runCatching { repository.cancelLeaveRequest(request.id, request.version) }
.onSuccess { updated -> .onSuccess { updated ->
_state.update { _state.update {
it.copy( it.copy(
@@ -628,13 +651,36 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
) )
} }
} }
.onFailure { throwable -> _state.update { it.withApiError(throwable) } } .onFailure { throwable ->
val apiError = ApiErrorMapper.map(throwable)
if (apiError.kind == ApiErrorKind.Conflict && apiError.code == "leave_request_stale") {
runCatching { repository.leaveRequest(request.id) }
.onSuccess { current ->
_state.update {
it.withLoadedLeaveRequests(listOf(current), navigateToList = false)
.copy(error = "Wniosek został wcześniej zmieniony. Pokazujemy aktualny stan.")
}
}
.onFailure { refreshError -> _state.update { it.withApiError(refreshError) } }
} else {
_state.update { it.withApiError(throwable) }
}
}
_state.update { it.copy(loading = false) } _state.update { it.copy(loading = false) }
} finally {
leaveMutationMutex.unlock()
consumePendingLeaveHint()
}
} }
} }
fun uploadPhoto(uri: Uri, source: String, metadata: PhotoUploadMetadata = PhotoUploadMetadata(), stage: String = "other") { fun uploadPhoto(uri: Uri, source: String, metadata: PhotoUploadMetadata = PhotoUploadMetadata(), stage: String = "other") {
val route = _state.value.selectedRoute ?: return val snapshot = _state.value
val route = snapshot.selectedRoute ?: return
if (!routeIsActiveToday(route, snapshot.selectedDate)) {
_state.update { it.copy(error = "Zdjęcia możesz dodać tylko w zaplanowanym zakresie kursu.") }
return
}
viewModelScope.launch { viewModelScope.launch {
_state.update { it.copy(error = null) } _state.update { it.copy(error = null) }
runCatching { photoUploadOutbox.enqueue(route.id, uri, source, metadata, stage) } runCatching { photoUploadOutbox.enqueue(route.id, uri, source, metadata, stage) }
@@ -645,7 +691,12 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
} }
fun openStartRoute() { fun openStartRoute() {
val route = _state.value.selectedRoute ?: return val snapshot = _state.value
val route = snapshot.selectedRoute ?: return
if (!canStartRouteFromDriverApp(route, snapshot.selectedDate)) {
_state.update { it.copy(error = "Załadunek nie jest dostępny poza zaplanowanym zakresem kursu.") }
return
}
_state.update { _state.update {
it.copy( it.copy(
screen = DriverScreen.StartRoute, screen = DriverScreen.StartRoute,
@@ -681,7 +732,12 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
} }
fun openFinishRoute() { fun openFinishRoute() {
val route = _state.value.selectedRoute ?: return val snapshot = _state.value
val route = snapshot.selectedRoute ?: return
if (!canFinishRouteFromDriverApp(route, snapshot.selectedDate)) {
_state.update { it.copy(error = "Rozładunek jest dostępny w dniu zaplanowanego rozładunku.") }
return
}
_state.update { _state.update {
it.copy( it.copy(
screen = DriverScreen.FinishRoute, screen = DriverScreen.FinishRoute,
@@ -708,6 +764,21 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
private fun submitRouteStage(stage: String) { private fun submitRouteStage(stage: String) {
val snapshot = _state.value val snapshot = _state.value
val route = snapshot.selectedRoute ?: return val route = snapshot.selectedRoute ?: return
val canSubmitStage = if (stage == "loading") {
canStartRouteFromDriverApp(route, snapshot.selectedDate)
} else {
canFinishRouteFromDriverApp(route, snapshot.selectedDate)
}
if (!canSubmitStage) {
_state.update {
it.copy(error = if (stage == "loading") {
"Załadunek nie jest dostępny poza zaplanowanym zakresem kursu."
} else {
"Rozładunek jest dostępny w dniu zaplanowanego rozładunku."
})
}
return
}
val driver = snapshot.driver val driver = snapshot.driver
val weight = snapshot.routeStageWeightText.trim().replace(',', '.').toDoubleOrNull() val weight = snapshot.routeStageWeightText.trim().replace(',', '.').toDoubleOrNull()
val stagePhotos = routePhotosForStage(route.photos, stage) val stagePhotos = routePhotosForStage(route.photos, stage)
@@ -880,8 +951,13 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
} }
fun completeSelectedRoute() { fun completeSelectedRoute() {
val route = _state.value.selectedRoute ?: return val snapshot = _state.value
if (_state.value.completingRoute || !_state.value.isOnline) return val route = snapshot.selectedRoute ?: return
if (snapshot.completingRoute || !snapshot.isOnline) return
if (!canCompleteRouteFromDriverApp(route, snapshot.selectedDate)) {
_state.update { it.copy(error = "Zakończenie kursu jest dostępne w dniu zaplanowanego rozładunku.") }
return
}
viewModelScope.launch { viewModelScope.launch {
_state.update { it.copy(completingRoute = true, feedback = null, error = null) } _state.update { it.copy(completingRoute = true, feedback = null, error = null) }
@@ -1022,12 +1098,23 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
val snapshot = _state.value val snapshot = _state.value
val routeId = snapshot.selectedRoute?.id val routeId = snapshot.selectedRoute?.id
val remote = runCatching { syncRepository.fetchSyncState(snapshot.selectedDate, routeId) }.getOrNull() ?: return val remote = runCatching { syncRepository.fetchSyncState(snapshot.selectedDate, routeId) }.getOrNull() ?: return
val needsRefresh = remote.scopes.any { syncRepository.shouldRefresh(it) } val staleScopes = remote.scopes.filter { syncRepository.shouldRefresh(it) }
if (needsRefresh) { if (staleScopes.isEmpty()) {
refreshCurrentScopeFromSyncState()
} else {
syncRepository.saveSyncStates(remote) syncRepository.saveSyncStates(remote)
return
}
staleScopes.forEach { scope ->
handleSyncHint(
DriverSyncHint(
scope = scope.scope,
date = scope.date,
routeId = scope.routeId,
version = scope.version,
checksum = scope.checksum,
),
)
} }
} }
@@ -1058,13 +1145,58 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
DriverSyncRepository.SCOPE_SETTINGS -> refreshRoutesSilently() DriverSyncRepository.SCOPE_SETTINGS -> refreshRoutesSilently()
DriverSyncRepository.SCOPE_DISPATCH_SHEET -> refreshRoutesSilently() DriverSyncRepository.SCOPE_DISPATCH_SHEET -> refreshRoutesSilently()
DriverSyncRepository.SCOPE_LEAVE_REQUESTS -> { DriverSyncRepository.SCOPE_LEAVE_REQUESTS -> {
if (leaveMutationMutex.isLocked) {
val pending = pendingLeaveHint
if (pending == null || hint.version > pending.version) pendingLeaveHint = hint
return
}
if (snapshot.screen == DriverScreen.LeaveRequests || snapshot.screen == DriverScreen.LeaveRequestDetail) { if (snapshot.screen == DriverScreen.LeaveRequests || snapshot.screen == DriverScreen.LeaveRequestDetail) {
refreshLeaveRequests() if (loadLeaveRequests(showLoading = false, navigateToList = false)) {
syncRepository.saveSyncScope(hint.asScope())
}
} else {
syncRepository.saveSyncScope(hint.asScope())
}
}
DriverSyncRepository.SCOPE_LEAVE_CALENDAR -> {
if (snapshot.screen == DriverScreen.LeaveCalendar) {
refreshLoadedLeaveCalendar(hint)
} else {
syncRepository.saveSyncScope(hint.asScope())
} }
} }
} }
} }
private suspend fun consumePendingLeaveHint() {
val hint = pendingLeaveHint ?: return
pendingLeaveHint = null
if (loadLeaveRequests(showLoading = false, navigateToList = false)) {
syncRepository.saveSyncScope(hint.asScope())
}
}
private suspend fun refreshLoadedLeaveCalendar(hint: DriverSyncHint) {
val generation = ++leaveCalendarRequestGeneration
val snapshot = _state.value
val from = LocalDate.now()
val loadedUntil = snapshot.leaveCalendarLoadedUntil
?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
?.takeUnless { it.isBefore(from) }
?: from.plusMonths(6).minusDays(1)
runCatching { repository.leaveCalendar(from.toString(), loadedUntil.toString()) }
.onSuccess { entries ->
if (generation != leaveCalendarRequestGeneration) return@onSuccess
_state.update { it.copy(leaveCalendarEntries = entries, leaveCalendarLoadedUntil = loadedUntil.toString(), leaveCalendarLoading = false) }
syncRepository.saveSyncScope(hint.asScope())
}
.onFailure { throwable ->
if (generation != leaveCalendarRequestGeneration) return@onFailure
_state.update { it.withApiError(throwable).copy(leaveCalendarLoading = false) }
}
}
private fun registerPushTokenIfAvailable(driverId: String) { private fun registerPushTokenIfAvailable(driverId: String) {
if (pushTokenRegisteredForDriverId == driverId) return if (pushTokenRegisteredForDriverId == driverId) return
@@ -107,6 +107,21 @@ class DriverLiveSyncClientTest {
assertTrue(factory.sockets.single().sent.any { it.contains("pusher:pong") }) assertTrue(factory.sockets.single().sent.any { it.contains("pusher:pong") })
} }
@Test
fun subscribesToOwnUpdatesAndSharedLeaveCalendarUpdates() = runTest {
val factory = FakeWebSocketFactory()
val client = liveClient(factory = factory, scope = this)
client.start("driver-1", config)
factory.sockets.single().message(connectionEstablished("socket-1"))
runCurrent()
val sent = factory.sockets.single().sent
assertTrue(sent.any { it.contains("private-driver-mobile.driver-1") })
assertTrue(sent.any { it.contains("private-driver-mobile.0") })
client.stop()
}
@Test @Test
fun closesAndReconnectsWhenConnectedSocketStopsReceivingMessages() = runTest { fun closesAndReconnectsWhenConnectedSocketStopsReceivingMessages() = runTest {
val factory = FakeWebSocketFactory() val factory = FakeWebSocketFactory()
@@ -64,6 +64,25 @@ class DriverLeaveRequestUiRulesTest {
assertEquals(listOf("week", "single-day"), matching.map { it.id }) assertEquals(listOf("week", "single-day"), matching.map { it.id })
} }
@Test
fun findsCalendarEntriesThatOverlapSelectedRange() {
val entries = listOf(
calendarEntry(id = "starts-before", dateFrom = "2026-08-01", dateTo = "2026-08-04"),
calendarEntry(id = "inside", dateFrom = "2026-08-06", dateTo = "2026-08-07"),
calendarEntry(id = "ends-after", dateFrom = "2026-08-09", dateTo = "2026-08-12"),
calendarEntry(id = "before", dateFrom = "2026-07-20", dateTo = "2026-07-22"),
calendarEntry(id = "after", dateFrom = "2026-08-13", dateTo = "2026-08-14"),
)
val matching = DriverLeaveRequestUiRules.calendarEntriesForRange(
entries = entries,
dateFrom = "2026-08-03",
dateTo = "2026-08-10",
)
assertEquals(listOf("starts-before", "inside", "ends-after"), matching.map { it.id })
}
@Test @Test
fun normalizesPhoneNumberIntoDialerUri() { fun normalizesPhoneNumberIntoDialerUri() {
assertEquals("tel:+48600700800", DriverLeaveRequestUiRules.phoneDialUri("+48 600 700 800")) assertEquals("tel:+48600700800", DriverLeaveRequestUiRules.phoneDialUri("+48 600 700 800"))
@@ -154,6 +154,7 @@ class DriverRouteProjectionTest {
): DriverRouteDto = ): DriverRouteDto =
DriverRouteDto( DriverRouteDto(
id = "1", id = "1",
routeDate = "2026-06-30",
startsAt = "", startsAt = "",
originName = "Baza", originName = "Baza",
destinationName = "Instalacja", destinationName = "Instalacja",
@@ -39,6 +39,32 @@ class DriverUiRulesTest {
assertFalse(canCompleteRouteFromDriverApp(route(status = "ZAPLANOWANA"), "2026-06-29", today)) assertFalse(canCompleteRouteFromDriverApp(route(status = "ZAPLANOWANA"), "2026-06-29", today))
} }
@Test
fun multiDayRouteCanLoadTodayButCanUnloadOnlyOnItsUnloadingDate() {
val route = route(
status = "ZAPLANOWANA",
routeDate = "2026-06-29",
unloadingDate = "2026-06-30",
)
assertTrue(canStartRouteFromDriverApp(route, "2026-06-30", today))
assertEquals("Załaduj", routeLifecyclePrimaryAction(route, "2026-06-30", today)?.label)
assertEquals("Dziś: rozładunek. Załadunek możesz potwierdzić dzisiaj.", routeTodayInstruction(route, "2026-06-30", today))
val activeRoute = route.copy(status = "W TRAKCIE")
assertTrue(canFinishRouteFromDriverApp(activeRoute, "2026-06-30", today))
assertEquals("Rozładuj", routeLifecyclePrimaryAction(activeRoute, "2026-06-30", today)?.label)
assertFalse(canFinishRouteFromDriverApp(activeRoute, "2026-06-29", LocalDate.parse("2026-06-29")))
}
@Test
fun routeScheduleShowsBothDispatcherDates() {
val route = route(routeDate = "2026-06-30", unloadingDate = "2026-07-02")
assertEquals("Załadunek: 30.06 · Rozładunek: 02.07", routeScheduleSummary(route))
assertEquals("Załadunek: 30.06 · Rozładunek: ten sam dzień", routeScheduleSummary(route.copy(unloadingDate = null)))
}
@Test @Test
fun showsLiveRouteDayUpdateOnlyForViewedDate() { fun showsLiveRouteDayUpdateOnlyForViewedDate() {
assertTrue(shouldShowRouteDayLiveUpdate(viewedDate = "2026-03-12", hintDate = "2026-03-12")) assertTrue(shouldShowRouteDayLiveUpdate(viewedDate = "2026-03-12", hintDate = "2026-03-12"))
@@ -300,7 +326,7 @@ class DriverUiRulesTest {
assertEquals(RouteFlowStepState.Todo, steps[1].state) assertEquals(RouteFlowStepState.Todo, steps[1].state)
assertEquals(RouteFlowStepState.Todo, steps[2].state) assertEquals(RouteFlowStepState.Todo, steps[2].state)
assertEquals(RouteFlowStepState.Todo, steps[3].state) assertEquals(RouteFlowStepState.Todo, steps[3].state)
assertEquals("Rozpocznij kurs", action?.label) assertEquals("Załaduj", action?.label)
assertEquals(RouteLifecycleAction.Start, action?.action) assertEquals(RouteLifecycleAction.Start, action?.action)
} }
@@ -327,7 +353,7 @@ class DriverUiRulesTest {
assertEquals(RouteFlowStepState.Confirmed, steps[1].state) assertEquals(RouteFlowStepState.Confirmed, steps[1].state)
assertEquals(RouteFlowStepState.LocalComplete, steps[2].state) assertEquals(RouteFlowStepState.LocalComplete, steps[2].state)
assertEquals(RouteFlowStepState.Todo, steps[3].state) assertEquals(RouteFlowStepState.Todo, steps[3].state)
assertEquals("Zakończ kurs", action?.label) assertEquals("Rozładuj", action?.label)
assertEquals(RouteLifecycleAction.Finish, action?.action) assertEquals(RouteLifecycleAction.Finish, action?.action)
} }
@@ -400,13 +426,17 @@ class DriverUiRulesTest {
} }
private fun route( private fun route(
status: String, status: String = "ZAPLANOWANA",
loadingWeight: Double? = null, loadingWeight: Double? = null,
unloadingWeight: Double? = null, unloadingWeight: Double? = null,
photos: List<RoutePhotoDto> = emptyList(), photos: List<RoutePhotoDto> = emptyList(),
routeDate: String? = "2026-06-30",
unloadingDate: String? = null,
): DriverRouteDto = ): DriverRouteDto =
DriverRouteDto( DriverRouteDto(
id = "1", id = "1",
routeDate = routeDate,
unloadingDate = unloadingDate,
startsAt = "", startsAt = "",
originName = "Baza", originName = "Baza",
destinationName = "Instalacja", destinationName = "Instalacja",
@@ -55,6 +55,23 @@ class DriverUiStateTest {
assertEquals(1, refreshed.leaveRequests.size) assertEquals(1, refreshed.leaveRequests.size)
} }
@Test
fun staleLeaveRequestRefreshDoesNotOverwriteNewerMutationResult() {
val state = DriverUiState(
screen = DriverScreen.LeaveRequestDetail,
leaveRequests = listOf(leaveRequest(id = "leave-1", status = "cancel_requested", version = 3)),
selectedLeaveRequest = leaveRequest(id = "leave-1", status = "cancel_requested", version = 3),
)
val refreshed = state.withLoadedLeaveRequests(
requests = listOf(leaveRequest(id = "leave-1", status = "approved", version = 2)),
navigateToList = false,
)
assertEquals("cancel_requested", refreshed.leaveRequests.single().status)
assertEquals(3L, refreshed.selectedLeaveRequest?.version)
}
@Test @Test
fun displayRoutesAndSelectedRouteUseLocalRouteActionsProjection() { fun displayRoutesAndSelectedRouteUseLocalRouteActionsProjection() {
val route = route(status = "ZAPLANOWANA") val route = route(status = "ZAPLANOWANA")
@@ -70,18 +87,54 @@ class DriverUiStateTest {
assertEquals(12.5, state.displaySelectedRoute?.loadingWeight) assertEquals(12.5, state.displaySelectedRoute?.loadingWeight)
} }
private fun leaveRequest(id: String, status: String): DriverLeaveRequestDto = @Test
fun displayRoutesMovesCompletedRoutesBelowActiveDispatcherOrder() {
val state = DriverUiState(
routes = listOf(
route(id = "completed", status = "ZAKOŃCZONA"),
route(id = "planned", status = "ZAPLANOWANA"),
route(id = "active", status = "W TRAKCIE"),
),
)
assertEquals(listOf("planned", "active", "completed"), state.displayRoutes.map { it.id })
}
@Test
fun displayRoutesUsesTheSelectedDayOrderingForMultiDayRoutes() {
val state = DriverUiState(
selectedDate = "2026-07-02",
routes = listOf(
route(id = "span", status = "ZAPLANOWANA", ordering = 0, dayOrderings = mapOf("2026-07-02" to 2)),
route(id = "above-first", status = "ZAPLANOWANA", ordering = 0, dayOrderings = mapOf("2026-07-02" to 0)),
route(id = "above-second", status = "ZAPLANOWANA", ordering = 1, dayOrderings = mapOf("2026-07-02" to 1)),
),
)
assertEquals(listOf("above-first", "above-second", "span"), state.displayRoutes.map { it.id })
}
private fun leaveRequest(id: String, status: String, version: Long = 1): DriverLeaveRequestDto =
DriverLeaveRequestDto( DriverLeaveRequestDto(
id = id, id = id,
dateFrom = "2026-07-10", dateFrom = "2026-07-10",
dateTo = "2026-07-12", dateTo = "2026-07-12",
type = "URLOP", type = "URLOP",
status = status, status = status,
version = version,
) )
private fun route(status: String): DriverRouteDto = private fun route(
id: String = "1",
status: String,
ordering: Int? = null,
dayOrderings: Map<String, Int> = emptyMap(),
): DriverRouteDto =
DriverRouteDto( DriverRouteDto(
id = "1", id = id,
routeDate = "2026-06-30",
ordering = ordering,
dayOrderings = dayOrderings,
startsAt = "", startsAt = "",
originName = "Baza", originName = "Baza",
destinationName = "Instalacja", destinationName = "Instalacja",