Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0564101e9e | ||
|
|
2baa544b32 | ||
|
|
f9c3a2e305 | ||
|
|
e49e7c358e |
@@ -34,8 +34,8 @@ android {
|
||||
applicationId = "pl.firmatpp.kierowca"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 102
|
||||
versionName = "1.0.49"
|
||||
versionCode = 104
|
||||
versionName = "1.0.51"
|
||||
setProperty("archivesBaseName", "pl.firmatpp.kierowca")
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
|
||||
@@ -71,8 +71,8 @@ class DriverRepository(
|
||||
suspend fun createLeaveRequest(dateFrom: String, dateTo: String, type: String, note: String?): DriverLeaveRequestDto =
|
||||
api.createLeaveRequest(authHeader(requireToken()), CreateLeaveRequestBody(dateFrom, dateTo, type, note)).data
|
||||
|
||||
suspend fun cancelLeaveRequest(id: String, comment: String? = null): DriverLeaveRequestDto =
|
||||
api.cancelLeaveRequest(authHeader(requireToken()), id, CancelLeaveRequestBody(comment)).data
|
||||
suspend fun cancelLeaveRequest(id: String, expectedVersion: Long, comment: String? = null): DriverLeaveRequestDto =
|
||||
api.cancelLeaveRequest(authHeader(requireToken()), id, CancelLeaveRequestBody(comment, expectedVersion)).data
|
||||
|
||||
suspend fun completeRoute(routeId: String) =
|
||||
api.completeRoute(authHeader(requireToken()), routeId)
|
||||
|
||||
@@ -193,6 +193,7 @@ data class CreateLeaveRequestBody(
|
||||
|
||||
data class CancelLeaveRequestBody(
|
||||
val comment: String? = null,
|
||||
val expectedVersion: Long? = null,
|
||||
)
|
||||
|
||||
data class DriverLeaveRequestDto(
|
||||
@@ -204,6 +205,10 @@ data class DriverLeaveRequestDto(
|
||||
val typeLabel: String? = null,
|
||||
val note: String? = null,
|
||||
val status: String,
|
||||
val version: Long = 1,
|
||||
val updatedAt: String? = null,
|
||||
val allowedDecisions: List<String> = emptyList(),
|
||||
val canCancel: Boolean = false,
|
||||
val submittedAt: String? = null,
|
||||
val decidedAt: String? = null,
|
||||
val decisionComment: String? = null,
|
||||
@@ -244,6 +249,9 @@ data class RealtimeStatusBody(
|
||||
data class DriverRouteDto(
|
||||
val id: String,
|
||||
val routeDate: String? = null,
|
||||
val unloadingDate: String? = null,
|
||||
val ordering: Int? = null,
|
||||
val dayOrderings: Map<String, Int>? = emptyMap(),
|
||||
val startsAt: String,
|
||||
val originName: String,
|
||||
val destinationName: String,
|
||||
|
||||
@@ -3,6 +3,7 @@ package pl.firmatpp.kierowca.data.sync
|
||||
import android.content.Context
|
||||
import com.google.gson.Gson
|
||||
import java.io.IOException
|
||||
import java.time.LocalDate
|
||||
import pl.firmatpp.kierowca.data.DriverRepository
|
||||
import pl.firmatpp.kierowca.data.model.BootstrapResponse
|
||||
import pl.firmatpp.kierowca.data.model.DriverRouteDto
|
||||
@@ -72,8 +73,8 @@ class DriverSyncRepository(
|
||||
),
|
||||
)
|
||||
|
||||
val selectedDate = date ?: return
|
||||
val cachedBootstrap = dao.bootstrap(selectedDate) ?: return
|
||||
(routeVisibleDates(route) + listOfNotNull(date)).distinct().forEach { selectedDate ->
|
||||
val cachedBootstrap = dao.bootstrap(selectedDate) ?: return@forEach
|
||||
val response = gson.fromJson(cachedBootstrap.payloadJson, BootstrapResponse::class.java)
|
||||
val updatedRoutes = response.routes.today.map { item -> if (item.id == route.id) route else item }
|
||||
dao.upsertBootstrap(
|
||||
@@ -85,6 +86,7 @@ class DriverSyncRepository(
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun fetchSyncState(date: String?, routeId: String?): SyncStateResponse =
|
||||
repository.syncState(date, routeId)
|
||||
@@ -96,6 +98,11 @@ class DriverSyncRepository(
|
||||
|
||||
suspend fun saveSyncStates(response: SyncStateResponse?) {
|
||||
response?.scopes.orEmpty().forEach { scope ->
|
||||
saveSyncScope(scope)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveSyncScope(scope: SyncScopeDto) {
|
||||
dao.upsertSyncState(
|
||||
DriverSyncStateEntity(
|
||||
key = syncStateKey(scope.scope, scope.date, scope.routeId),
|
||||
@@ -109,7 +116,6 @@ class DriverSyncRepository(
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun clearCache() {
|
||||
dao.clearBootstrap()
|
||||
@@ -146,11 +152,24 @@ class DriverSyncRepository(
|
||||
|
||||
private fun currentDateFallback(): String = java.time.LocalDate.now().toString()
|
||||
|
||||
private fun routeVisibleDates(route: DriverRouteDto): List<String> {
|
||||
val start = route.routeDate?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: return emptyList()
|
||||
val end = route.unloadingDate
|
||||
?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
?.takeUnless { it.isBefore(start) }
|
||||
?: start
|
||||
|
||||
return generateSequence(start) { date -> date.plusDays(1).takeIf { !it.isAfter(end) } }
|
||||
.map(LocalDate::toString)
|
||||
.toList()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SCOPE_ROUTES = "routes"
|
||||
const val SCOPE_ROUTE_DETAIL = "route_detail"
|
||||
const val SCOPE_SETTINGS = "settings"
|
||||
const val SCOPE_DISPATCH_SHEET = "dispatch_sheet"
|
||||
const val SCOPE_LEAVE_REQUESTS = "leave_requests"
|
||||
const val SCOPE_LEAVE_CALENDAR = "leave_calendar"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,10 +272,11 @@ class DriverLiveSyncClient(
|
||||
|
||||
private fun subscribe(socket: WebSocket, socketId: String) {
|
||||
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 {
|
||||
runCatching {
|
||||
channels.forEach { channel ->
|
||||
val auth = gateway.broadcastAuth(socketId, channel).auth
|
||||
if (!isCurrentSocket(socket)) return@launch
|
||||
val payload = mapOf(
|
||||
@@ -286,6 +287,7 @@ class DriverLiveSyncClient(
|
||||
),
|
||||
)
|
||||
check(socket.send(gson.toJson(payload))) { "WebSocket send returned false" }
|
||||
}
|
||||
}.onFailure { throwable ->
|
||||
AppDiagnostics.log("realtime_subscription_error: ${throwable.message ?: throwable::class.java.simpleName}")
|
||||
socket.close(1000, "subscription_failed")
|
||||
|
||||
@@ -52,6 +52,10 @@ class DriverSyncWorker(
|
||||
syncRepository.saveSyncStates(response)
|
||||
refreshed = true
|
||||
}
|
||||
DriverSyncRepository.SCOPE_LEAVE_CALENDAR -> {
|
||||
syncRepository.saveSyncStates(response)
|
||||
refreshed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,7 +281,7 @@ fun DriverApp(
|
||||
title = "Waga załadunku",
|
||||
stage = "loading",
|
||||
weightLabel = "Waga z wagi",
|
||||
submitLabel = "Rozpocznij kurs",
|
||||
submitLabel = "Załaduj",
|
||||
showWeightInput = true,
|
||||
showPhotoActions = false,
|
||||
showPhotoGrid = false,
|
||||
@@ -295,10 +295,10 @@ fun DriverApp(
|
||||
)
|
||||
DriverScreen.FinishRoute -> RouteStageScreen(
|
||||
state = state,
|
||||
title = "Zakończ kurs",
|
||||
title = "Rozładunek",
|
||||
stage = "unloading",
|
||||
weightLabel = "Waga na rozładunku",
|
||||
submitLabel = "Zakończ kurs",
|
||||
submitLabel = "Rozładuj",
|
||||
onBack = viewModel::back,
|
||||
onWeightChange = viewModel::updateRouteStageWeight,
|
||||
onUpload = { uri, source, metadata -> viewModel.uploadPhoto(uri, source, metadata, "unloading") },
|
||||
@@ -2030,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))
|
||||
RouteTimeline(display.origin, display.destination)
|
||||
}
|
||||
@@ -2061,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
|
||||
private fun RouteTimeline(origin: String, destination: String) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
@@ -2774,9 +2791,19 @@ private fun RouteLifecycleSection(
|
||||
val steps = routeFlowSteps(route, routeActions)
|
||||
val callout = routeSyncCallout(routeActions)
|
||||
val action = routeLifecyclePrimaryAction(route, selectedDate)
|
||||
val instruction = routeTodayInstruction(route, selectedDate)
|
||||
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
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()) {
|
||||
RouteStateMessage(
|
||||
text = feedback,
|
||||
@@ -2885,6 +2912,15 @@ private fun RouteFlowStepItem(step: RouteFlowStepUi, modifier: Modifier = Modifi
|
||||
maxLines = 2,
|
||||
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(
|
||||
step.stateLabel,
|
||||
color = color,
|
||||
@@ -2996,6 +3032,7 @@ private fun ManifestSection(route: DriverRouteDto, selectedDate: String, onNavig
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = TppTheme.colors.ink,
|
||||
)
|
||||
RouteScheduleLabel(route)
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = TppTheme.colors.outline.copy(alpha = 0.65f))
|
||||
|
||||
@@ -34,6 +34,7 @@ data class RouteFlowStepUi(
|
||||
val title: String,
|
||||
val state: RouteFlowStepState,
|
||||
val stateLabel: String,
|
||||
val dateLabel: String? = null,
|
||||
)
|
||||
|
||||
data class RouteLifecycleActionUi(
|
||||
@@ -49,12 +50,68 @@ data class RouteSyncCalloutUi(
|
||||
fun canManageRoutePhotos(selectedDate: String, today: LocalDate = LocalDate.now()): Boolean =
|
||||
runCatching { LocalDate.parse(selectedDate).isEqual(today) }.getOrDefault(false)
|
||||
|
||||
fun routeIsActiveToday(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): Boolean {
|
||||
val viewedDate = runCatching { LocalDate.parse(selectedDate) }.getOrNull() ?: return false
|
||||
val loadingDate = route.routeDate?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: return false
|
||||
val unloadingDate = route.unloadingDate
|
||||
?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
?: loadingDate
|
||||
|
||||
return viewedDate == today && !today.isBefore(loadingDate) && !today.isAfter(unloadingDate)
|
||||
}
|
||||
|
||||
fun routeUnloadingDate(route: DriverRouteDto): String? = route.unloadingDate ?: route.routeDate
|
||||
|
||||
fun routeDayOrdering(route: DriverRouteDto, date: String): Int =
|
||||
route.dayOrderings?.get(date) ?: route.ordering ?: Int.MAX_VALUE
|
||||
|
||||
fun routeScheduleDateLabel(date: String?): String =
|
||||
date
|
||||
?.let { runCatching { LocalDate.parse(it).format(shortDateFormatter) }.getOrNull() }
|
||||
?: "—"
|
||||
|
||||
fun routeScheduleSummary(route: DriverRouteDto): String {
|
||||
val loading = routeScheduleDateLabel(route.routeDate)
|
||||
val unloading = routeScheduleDateLabel(routeUnloadingDate(route))
|
||||
|
||||
return if (route.unloadingDate == null) {
|
||||
"Załadunek: $loading · Rozładunek: ten sam dzień"
|
||||
} else {
|
||||
"Załadunek: $loading · Rozładunek: $unloading"
|
||||
}
|
||||
}
|
||||
|
||||
fun routeTodayInstruction(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): String? {
|
||||
if (!routeIsActiveToday(route, selectedDate, today)) return null
|
||||
|
||||
val loadingDate = route.routeDate?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: return null
|
||||
val unloadingDate = routeUnloadingDate(route)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: loadingDate
|
||||
|
||||
return when {
|
||||
route.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(
|
||||
route: DriverRouteDto,
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): 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")
|
||||
|
||||
fun canStartRouteFromDriverApp(
|
||||
@@ -62,7 +119,7 @@ fun canStartRouteFromDriverApp(
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): Boolean =
|
||||
canManageRoutePhotos(selectedDate, today)
|
||||
routeIsActiveToday(route, selectedDate, today)
|
||||
&& route.status == "ZAPLANOWANA"
|
||||
|
||||
fun canFinishRouteFromDriverApp(
|
||||
@@ -70,8 +127,9 @@ fun canFinishRouteFromDriverApp(
|
||||
selectedDate: String,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): 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 {
|
||||
return routeStageSubmitBlocker(weightText, serverPhotoCount, localUploadCount) == null
|
||||
@@ -116,8 +174,8 @@ fun routeLifecyclePrimaryAction(
|
||||
today: LocalDate = LocalDate.now(),
|
||||
): RouteLifecycleActionUi? =
|
||||
when {
|
||||
canStartRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Rozpocznij kurs", RouteLifecycleAction.Start)
|
||||
canFinishRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Zakończ kurs", RouteLifecycleAction.Finish)
|
||||
canStartRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Załaduj", RouteLifecycleAction.Start)
|
||||
canFinishRouteFromDriverApp(route, selectedDate, today) -> RouteLifecycleActionUi("Rozładuj", RouteLifecycleAction.Finish)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -175,10 +233,10 @@ fun routeFlowSteps(route: DriverRouteDto, actions: List<RouteActionEntity>): Lis
|
||||
}
|
||||
|
||||
return listOf(
|
||||
RouteFlowStepUi("loading_photos", "Zdjęcia załadunku", loadingPhotosState, routeFlowStateLabel(loadingPhotosState)),
|
||||
RouteFlowStepUi("loading_weight", "Waga załadunku", loadingWeightState, routeFlowStateLabel(loadingWeightState)),
|
||||
RouteFlowStepUi("loading_photos", "Zdjęcia załadunku", loadingPhotosState, routeFlowStateLabel(loadingPhotosState), routeScheduleDateLabel(route.routeDate)),
|
||||
RouteFlowStepUi("loading_weight", "Waga załadunku", loadingWeightState, routeFlowStateLabel(loadingWeightState), routeScheduleDateLabel(route.routeDate)),
|
||||
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.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import java.time.LocalDate
|
||||
import java.time.Instant
|
||||
import pl.firmatpp.kierowca.data.AppPreferencesStore
|
||||
@@ -96,6 +97,10 @@ data class DriverUiState(
|
||||
|
||||
val displayRoutes: List<DriverRouteDto>
|
||||
get() = projectDriverRoutes(routes, projectionActions)
|
||||
.sortedWith(
|
||||
compareBy<DriverRouteDto> { route -> if (route.status == "ZAKOŃCZONA") 1 else 0 }
|
||||
.thenBy { route -> routeDayOrdering(route, selectedDate) },
|
||||
)
|
||||
|
||||
val selectedRouteProjection: ProjectedDriverRoute?
|
||||
get() = selectedRoute?.let { projectDriverRoute(it, projectionActions) }
|
||||
@@ -117,12 +122,17 @@ internal fun DriverUiState.withLoadedLeaveRequests(
|
||||
requests: List<DriverLeaveRequestDto>,
|
||||
navigateToList: Boolean,
|
||||
): 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 ->
|
||||
requests.firstOrNull { request -> request.id == selected.id } ?: selected
|
||||
merged.firstOrNull { request -> request.id == selected.id }?.takeIf { it.version >= selected.version } ?: selected
|
||||
}
|
||||
return copy(
|
||||
screen = if (navigateToList) DriverScreen.LeaveRequests else screen,
|
||||
leaveRequests = requests,
|
||||
leaveRequests = merged,
|
||||
selectedLeaveRequest = refreshedSelectedRequest,
|
||||
error = null,
|
||||
)
|
||||
@@ -147,6 +157,9 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
private var routeActionsJob: Job? = null
|
||||
private var dispatchSheetUploadsJob: Job? = 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
|
||||
|
||||
init {
|
||||
@@ -415,24 +428,22 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
fun openLeaveRequests() {
|
||||
if (!DriverLeaveRequestUiRules.isFeatureVisible(_state.value.leaveRequestsConfig)) return
|
||||
loadLeaveRequests(showLoading = true, navigateToList = true)
|
||||
viewModelScope.launch { loadLeaveRequests(showLoading = true, navigateToList = true) }
|
||||
}
|
||||
|
||||
fun refreshLeaveRequests() {
|
||||
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) {
|
||||
viewModelScope.launch {
|
||||
private suspend fun loadLeaveRequests(showLoading: Boolean, navigateToList: Boolean): Boolean {
|
||||
_state.update { it.copy(loading = showLoading, refreshing = !showLoading, error = null, feedback = null) }
|
||||
runCatching { repository.leaveRequests() }
|
||||
.onSuccess { requests ->
|
||||
val result = runCatching { repository.leaveRequests() }
|
||||
result.onSuccess { requests ->
|
||||
_state.update { it.withLoadedLeaveRequests(requests, navigateToList) }
|
||||
}
|
||||
.onFailure { throwable -> _state.update { it.withApiError(throwable) } }
|
||||
}.onFailure { throwable -> _state.update { it.withApiError(throwable) } }
|
||||
_state.update { it.copy(loading = false, refreshing = false) }
|
||||
}
|
||||
return result.isSuccess
|
||||
}
|
||||
|
||||
fun openLeaveRequest(id: String) {
|
||||
@@ -546,6 +557,7 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
runCatching { LocalDate.parse(snapshot.leaveCalendarLoadedUntil).plusDays(1) }.getOrDefault(LocalDate.now())
|
||||
}
|
||||
val to = from.plusMonths(6).minusDays(1)
|
||||
val generation = ++leaveCalendarRequestGeneration
|
||||
|
||||
viewModelScope.launch {
|
||||
_state.update {
|
||||
@@ -558,6 +570,7 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
runCatching { repository.leaveCalendar(from.toString(), to.toString()) }
|
||||
.onSuccess { entries ->
|
||||
if (generation != leaveCalendarRequestGeneration) return@onSuccess
|
||||
_state.update {
|
||||
val merged = (it.leaveCalendarEntries + entries)
|
||||
.distinctBy { entry -> entry.id }
|
||||
@@ -571,6 +584,7 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
.onFailure { throwable ->
|
||||
if (generation != leaveCalendarRequestGeneration) return@onFailure
|
||||
_state.update { it.withApiError(throwable).copy(leaveCalendarLoading = false) }
|
||||
}
|
||||
}
|
||||
@@ -579,13 +593,16 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
fun submitLeaveRequest() {
|
||||
val snapshot = _state.value
|
||||
if (!DriverLeaveRequestUiRules.isFeatureVisible(snapshot.leaveRequestsConfig)) return
|
||||
if (!leaveMutationMutex.tryLock()) return
|
||||
if (snapshot.leaveRequestDateFrom < LocalDate.now().toString()) {
|
||||
_state.update { it.copy(error = "Data od nie może być z przeszłości.") }
|
||||
leaveMutationMutex.unlock()
|
||||
return
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null, feedback = null) }
|
||||
try {
|
||||
runCatching {
|
||||
repository.createLeaveRequest(
|
||||
dateFrom = snapshot.leaveRequestDateFrom,
|
||||
@@ -608,16 +625,22 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
_state.update { it.withApiError(throwable) }
|
||||
}
|
||||
_state.update { it.copy(loading = false) }
|
||||
} finally {
|
||||
leaveMutationMutex.unlock()
|
||||
consumePendingLeaveHint()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelSelectedLeaveRequest() {
|
||||
val request = _state.value.selectedLeaveRequest ?: return
|
||||
if (!DriverLeaveRequestUiRules.canCancel(request.status, request.dateFrom.orEmpty())) return
|
||||
if (!leaveMutationMutex.tryLock()) return
|
||||
|
||||
viewModelScope.launch {
|
||||
_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 ->
|
||||
_state.update {
|
||||
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) }
|
||||
} finally {
|
||||
leaveMutationMutex.unlock()
|
||||
consumePendingLeaveHint()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
_state.update { it.copy(error = null) }
|
||||
runCatching { photoUploadOutbox.enqueue(route.id, uri, source, metadata, stage) }
|
||||
@@ -645,7 +691,12 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
|
||||
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 {
|
||||
it.copy(
|
||||
screen = DriverScreen.StartRoute,
|
||||
@@ -681,7 +732,12 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
|
||||
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 {
|
||||
it.copy(
|
||||
screen = DriverScreen.FinishRoute,
|
||||
@@ -708,6 +764,21 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
private fun submitRouteStage(stage: String) {
|
||||
val snapshot = _state.value
|
||||
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 weight = snapshot.routeStageWeightText.trim().replace(',', '.').toDoubleOrNull()
|
||||
val stagePhotos = routePhotosForStage(route.photos, stage)
|
||||
@@ -880,8 +951,13 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
|
||||
fun completeSelectedRoute() {
|
||||
val route = _state.value.selectedRoute ?: return
|
||||
if (_state.value.completingRoute || !_state.value.isOnline) return
|
||||
val snapshot = _state.value
|
||||
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 {
|
||||
_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 routeId = snapshot.selectedRoute?.id
|
||||
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) {
|
||||
refreshCurrentScopeFromSyncState()
|
||||
} else {
|
||||
if (staleScopes.isEmpty()) {
|
||||
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,10 +1145,55 @@ class DriverViewModel(application: Application) : AndroidViewModel(application)
|
||||
DriverSyncRepository.SCOPE_SETTINGS -> refreshRoutesSilently()
|
||||
DriverSyncRepository.SCOPE_DISPATCH_SHEET -> refreshRoutesSilently()
|
||||
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) {
|
||||
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) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -107,6 +107,21 @@ class DriverLiveSyncClientTest {
|
||||
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
|
||||
fun closesAndReconnectsWhenConnectedSocketStopsReceivingMessages() = runTest {
|
||||
val factory = FakeWebSocketFactory()
|
||||
|
||||
@@ -154,6 +154,7 @@ class DriverRouteProjectionTest {
|
||||
): DriverRouteDto =
|
||||
DriverRouteDto(
|
||||
id = "1",
|
||||
routeDate = "2026-06-30",
|
||||
startsAt = "",
|
||||
originName = "Baza",
|
||||
destinationName = "Instalacja",
|
||||
|
||||
@@ -39,6 +39,32 @@ class DriverUiRulesTest {
|
||||
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
|
||||
fun showsLiveRouteDayUpdateOnlyForViewedDate() {
|
||||
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[2].state)
|
||||
assertEquals(RouteFlowStepState.Todo, steps[3].state)
|
||||
assertEquals("Rozpocznij kurs", action?.label)
|
||||
assertEquals("Załaduj", action?.label)
|
||||
assertEquals(RouteLifecycleAction.Start, action?.action)
|
||||
}
|
||||
|
||||
@@ -327,7 +353,7 @@ class DriverUiRulesTest {
|
||||
assertEquals(RouteFlowStepState.Confirmed, steps[1].state)
|
||||
assertEquals(RouteFlowStepState.LocalComplete, steps[2].state)
|
||||
assertEquals(RouteFlowStepState.Todo, steps[3].state)
|
||||
assertEquals("Zakończ kurs", action?.label)
|
||||
assertEquals("Rozładuj", action?.label)
|
||||
assertEquals(RouteLifecycleAction.Finish, action?.action)
|
||||
}
|
||||
|
||||
@@ -400,13 +426,17 @@ class DriverUiRulesTest {
|
||||
}
|
||||
|
||||
private fun route(
|
||||
status: String,
|
||||
status: String = "ZAPLANOWANA",
|
||||
loadingWeight: Double? = null,
|
||||
unloadingWeight: Double? = null,
|
||||
photos: List<RoutePhotoDto> = emptyList(),
|
||||
routeDate: String? = "2026-06-30",
|
||||
unloadingDate: String? = null,
|
||||
): DriverRouteDto =
|
||||
DriverRouteDto(
|
||||
id = "1",
|
||||
routeDate = routeDate,
|
||||
unloadingDate = unloadingDate,
|
||||
startsAt = "",
|
||||
originName = "Baza",
|
||||
destinationName = "Instalacja",
|
||||
|
||||
@@ -55,6 +55,23 @@ class DriverUiStateTest {
|
||||
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
|
||||
fun displayRoutesAndSelectedRouteUseLocalRouteActionsProjection() {
|
||||
val route = route(status = "ZAPLANOWANA")
|
||||
@@ -70,18 +87,54 @@ class DriverUiStateTest {
|
||||
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(
|
||||
id = id,
|
||||
dateFrom = "2026-07-10",
|
||||
dateTo = "2026-07-12",
|
||||
type = "URLOP",
|
||||
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(
|
||||
id = "1",
|
||||
id = id,
|
||||
routeDate = "2026-06-30",
|
||||
ordering = ordering,
|
||||
dayOrderings = dayOrderings,
|
||||
startsAt = "",
|
||||
originName = "Baza",
|
||||
destinationName = "Instalacja",
|
||||
|
||||
Reference in New Issue
Block a user