Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,16 @@ interface BookingRepository {

/** Returns bookings for this listing owned by the signed-in lender. */
suspend fun getBookingsForListing(listingId: String): List<Booking>

/** Returns bookings made by the signed-in renter. */
suspend fun getBookingsForRenter(): List<Booking>

/**
* Queues a cancellation without waiting for server confirmation; offline, the write stays queued
* until the connection returns. If the server later rejects it, for example because the booking
* is no longer requested or confirmed, the failure reaches [onWriteFailure].
*
* @param onWriteFailure receives a write failure that arrives after local queuing.
*/
suspend fun cancelBooking(id: String, onWriteFailure: (Exception) -> Unit = {})
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class FirebaseBookingRepository(
private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance(),
private val auth: FirebaseAuth = FirebaseAuth.getInstance(),
private val logWriteFailure: (Exception) -> Unit = {
Log.e("BookingRepository", "Booking request failed", it)
Log.e("BookingRepository", "Booking write failed", it)
},
) : BookingRepository {

Expand Down Expand Up @@ -69,6 +69,39 @@ class FirebaseBookingRepository(
.map { it.toBooking() }
}

override suspend fun getBookingsForRenter(): List<Booking> {
val uid =
auth.currentUser?.uid
?: throw FirebaseFirestoreException(
"Sign in to read bookings",
FirebaseFirestoreException.Code.UNAUTHENTICATED,
)
return firestore
.collection("bookings")
.whereEqualTo("renterUid", uid)
.get()
.await()
.documents
.map { it.toBooking() }
}

override suspend fun cancelBooking(id: String, onWriteFailure: (Exception) -> Unit) {
if (auth.currentUser == null) {
throw FirebaseFirestoreException(
"Sign in to cancel a booking",
FirebaseFirestoreException.Code.UNAUTHENTICATED,
)
}
firestore
.collection("bookings")
.document(id)
.update("status", BookingStatus.CANCELLED.name)
.addOnFailureListener(Executor { it.run() }) {
logWriteFailure(it)
onWriteFailure(it)
}
}

private fun DocumentSnapshot.toBooking(): Booking {
fun string(field: String): String =
getString(field) ?: throw IllegalStateException("Booking $id is missing $field")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.polybazaar.booking.model.Booking
import com.android.polybazaar.booking.model.BookingRepository
import com.android.polybazaar.booking.model.BookingStatus
import com.android.polybazaar.error.model.AppError
import com.android.polybazaar.error.model.toAppError
import kotlinx.coroutines.CancellationException
Expand All @@ -18,6 +19,9 @@ data class BookingUiState(
val isSubmitting: Boolean = false,
/** True after local queuing; it does not mean the server confirmed or lender accepted it. */
val isQueued: Boolean = false,
val bookings: List<Booking> = emptyList(),
val isLoadingBookings: Boolean = false,
val cancellingBookingIds: Set<String> = emptySet(),
val error: AppError? = null,
)

Expand Down Expand Up @@ -58,4 +62,65 @@ class BookingViewModel(private val bookingRepository: BookingRepository) : ViewM
fun acknowledgeQueuedBooking() {
_uiState.update { it.copy(isQueued = false) }
}

/** Loads bookings made by the signed-in renter. */
fun loadRenterBookings() {
Comment thread
adrimikh marked this conversation as resolved.
Resolved
if (_uiState.value.isLoadingBookings) return
_uiState.update { it.copy(isLoadingBookings = true, error = null) }
viewModelScope.launch {
try {
val bookings = bookingRepository.getBookingsForRenter()
_uiState.update { it.copy(bookings = bookings, isLoadingBookings = false) }
} catch (exception: Exception) {
if (exception is CancellationException) {
_uiState.update { it.copy(isLoadingBookings = false) }
throw exception
}
_uiState.update { it.copy(isLoadingBookings = false, error = exception.toAppError()) }
}
}
}

/**
* Queues a cancellation and shows the booking as cancelled at once, also offline. If the server
* later rejects the write, the booking returns to its previous status and the error is exposed.
* [BookingUiState.cancellingBookingIds] holds the booking only until the write is queued.
*/
fun cancelBooking(id: String) {
val previousStatus = _uiState.value.bookings.firstOrNull { it.id == id }?.status
if (id in _uiState.value.cancellingBookingIds || previousStatus == BookingStatus.CANCELLED) {
return
}
_uiState.update { it.copy(cancellingBookingIds = it.cancellingBookingIds + id, error = null) }
Comment thread
adrimikh marked this conversation as resolved.
Resolved
viewModelScope.launch {
var rejected = false
try {
bookingRepository.cancelBooking(id) { exception ->
rejected = true
_uiState.update {
it.copy(
bookings = it.bookings.withStatus(id, previousStatus),
cancellingBookingIds = it.cancellingBookingIds - id,
error = exception.toAppError(),
)
}
}
if (!rejected) {
_uiState.update {
it.copy(
bookings = it.bookings.withStatus(id, BookingStatus.CANCELLED),
cancellingBookingIds = it.cancellingBookingIds - id,
)
}
}
} catch (exception: Exception) {
_uiState.update { it.copy(cancellingBookingIds = it.cancellingBookingIds - id) }
if (exception is CancellationException) throw exception
_uiState.update { it.copy(error = exception.toAppError()) }
}
}
}

private fun List<Booking>.withStatus(id: String, status: BookingStatus?): List<Booking> =
if (status == null) this else map { if (it.id == id) it.copy(status = status) else it }
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ class FakeBookingRepository : BookingRepository {
var immediateWriteFailure: Exception? = null
var writeFailure: ((Exception) -> Unit)? = null
var requestJob: Job? = null
var renterBookings: List<Booking> = emptyList()
var pendingLoad: CompletableDeferred<Unit>? = null
var loadFailure: Exception? = null
var loadCount = 0
var cancellationCount = 0
var cancelFailure: Exception? = null
var pendingCancel: CompletableDeferred<Unit>? = null
var cancelWriteFailure: ((Exception) -> Unit)? = null
var immediateCancelWriteFailure: Exception? = null

override suspend fun requestBooking(booking: Booking, onWriteFailure: (Exception) -> Unit) {
requestJob = currentCoroutineContext()[Job]
Expand All @@ -31,4 +40,19 @@ class FakeBookingRepository : BookingRepository {
}

override suspend fun getBookingsForListing(listingId: String): List<Booking> = emptyList()

override suspend fun getBookingsForRenter(): List<Booking> {
loadCount++
pendingLoad?.await()
loadFailure?.let { throw it }
return renterBookings
}

override suspend fun cancelBooking(id: String, onWriteFailure: (Exception) -> Unit) {
cancellationCount++
cancelWriteFailure = onWriteFailure
pendingCancel?.await()
immediateCancelWriteFailure?.let(onWriteFailure)
cancelFailure?.let { throw it }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class FirebaseBookingRepositoryTest {
private val document = mock<DocumentReference>()
private val listingQuery = mock<Query>()
private val lenderQuery = mock<Query>()
private val renterQuery = mock<Query>()
private val snapshot = mock<QuerySnapshot>()
private val stored = mock<DocumentSnapshot>()
private val repository = FirebaseBookingRepository(firestore, auth)
Expand All @@ -58,6 +59,8 @@ class FirebaseBookingRepositoryTest {
whenever(collection.document()).thenReturn(document)
whenever(collection.whereEqualTo("listingId", "listing")).thenReturn(listingQuery)
whenever(listingQuery.whereEqualTo("lenderUid", "lender")).thenReturn(lenderQuery)
whenever(collection.whereEqualTo("renterUid", "renter")).thenReturn(renterQuery)
whenever(collection.document("booking-id")).thenReturn(document)
}

@Test
Expand Down Expand Up @@ -208,4 +211,90 @@ class FirebaseBookingRepositoryTest {
(error as FirebaseFirestoreException).code,
)
}

@Test
fun getBookingsForRenterQueriesAuthenticatedRenterAndDecodesBookings() = runTest {
whenever(renterQuery.get()).thenReturn(Tasks.forResult(snapshot))
whenever(snapshot.documents).thenReturn(listOf(stored))
whenever(stored.getString("listingId")).thenReturn(booking.listingId)
whenever(stored.getString("renterUid")).thenReturn("renter")
whenever(stored.getString("lenderUid")).thenReturn(booking.lenderUid)
whenever(stored.get("days")).thenReturn(booking.days.map { it.toEpochDay() })
whenever(stored.getString("status")).thenReturn("REQUESTED")
whenever(stored.id).thenReturn("booking-id")

assertEquals(
listOf(booking.copy(renterUid = "renter", id = "booking-id")),
repository.getBookingsForRenter(),
)
verify(collection).whereEqualTo("renterUid", "renter")
}

@Test
fun getBookingsForRenterRejectsSignedOutUser() = runTest {
whenever(auth.currentUser).thenReturn(null)

val error = runCatching { repository.getBookingsForRenter() }.exceptionOrNull()

assertTrue(error is FirebaseFirestoreException)
assertEquals(
FirebaseFirestoreException.Code.UNAUTHENTICATED,
(error as FirebaseFirestoreException).code,
)
}

@Test
fun cancelBookingQueuesOfflineWriteWithoutWaitingForServer() = runTest {
val pendingWrite = TaskCompletionSource<Void>()
whenever(document.update("status", "CANCELLED")).thenReturn(pendingWrite.task)

withTimeout(1_000) { repository.cancelBooking("booking-id") }

assertTrue(!pendingWrite.task.isComplete)
verify(document).update("status", "CANCELLED")
}

@Test
fun cancelBookingReportsLaterRejectedWrite() = runTest {
val pendingWrite = TaskCompletionSource<Void>()
whenever(document.update("status", "CANCELLED")).thenReturn(pendingWrite.task)
var reportedFailure: Exception? = null
val repository = FirebaseBookingRepository(firestore, auth) { reportedFailure = it }
var reportedToCaller: Exception? = null

repository.cancelBooking("booking-id", onWriteFailure = { reportedToCaller = it })
val failure = IllegalStateException("Write rejected")
pendingWrite.setException(failure)

assertSame(failure, reportedFailure)
assertSame(failure, reportedToCaller)
}

@Test
fun cancelBookingLogsRejectedWriteWhenCallerPassesNoCallback() = runTest {
val pendingWrite = TaskCompletionSource<Void>()
whenever(document.update("status", "CANCELLED")).thenReturn(pendingWrite.task)
var logged: Exception? = null
val repository = FirebaseBookingRepository(firestore, auth) { logged = it }

repository.cancelBooking("booking-id")
val failure = IllegalStateException("Write rejected")
pendingWrite.setException(failure)

assertSame(failure, logged)
}

@Test
fun cancelBookingRejectsSignedOutUser() = runTest {
whenever(auth.currentUser).thenReturn(null)

val error = runCatching { repository.cancelBooking("booking-id") }.exceptionOrNull()

assertTrue(error is FirebaseFirestoreException)
assertEquals(
FirebaseFirestoreException.Code.UNAUTHENTICATED,
(error as FirebaseFirestoreException).code,
)
verify(document, never()).update(any<String>(), any())
}
}
Loading
Loading