diff --git a/app/src/main/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModel.kt b/app/src/main/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModel.kt new file mode 100644 index 00000000..8a41f0da --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModel.kt @@ -0,0 +1,199 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.booking.viewmodel + +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.booking.model.overlaps +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.error.model.toAppError +import com.android.polybazaar.listing.model.ListingRepository +import com.android.polybazaar.profile.model.ProfileRepository +import java.time.LocalDate +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** + * State of the screen where a lender answers the booking requests on one of their listings. + * + * Only bookings with a day from today on are shown: a request whose days have all passed can no + * longer be lent, and an accepted one is over. + * + * @property requests the requests waiting for an answer, earliest first day first. + * @property accepted the requests the lender accepted, earliest first day first. + * @property renterNames the username of each renter whose profile could be read, by uid. A renter + * missing here is shown without a name. + * @property offeredDays the days the listing still offers, read with the bookings. See [canAccept]. + * @property hasLoaded true once the bookings were read at least once. + * @property isLoading true while the bookings are being read. + * @property acceptingId the id of the request being accepted, or null. Nothing else can be accepted + * meanwhile. + * @property error why the bookings or the listing could not be read, or null. + * @property acceptError why the last accept failed, or null. Cleared when the lender tries again. + */ +data class ReceivedRequestsUiState( + val requests: List = emptyList(), + val accepted: List = emptyList(), + val renterNames: Map = emptyMap(), + val offeredDays: Set = emptySet(), + val hasLoaded: Boolean = false, + val isLoading: Boolean = false, + val acceptingId: String? = null, + val error: AppError? = null, + val acceptError: AppError? = null, +) { + /** + * Whether [request] can be accepted: every one of its days is still offered on the listing, as + * the rules require. A request stays listed without Accept when the owner no longer offers one of + * its days (an edit drops the past ones), or when another accepted booking took one. + */ + fun canAccept(request: Booking): Boolean = request.days.all { it in offeredDays } + + /** The other waiting requests that accepting [request] cancels: those sharing one of its days. */ + fun conflictsOf(request: Booking): List = requests.filter { + it.id != request.id && it.overlaps(request) + } +} + +/** The booking's earliest day, which orders the lists. */ +private val Booking.firstDay: LocalDate + get() = days.min() + +/** + * Loads the bookings of the listing [listingId] for its owner, and accepts the one they choose. + * + * @param listingRepository reads the days the listing still offers, which decide what can be + * accepted. + * @param today the day the screen is opened on: bookings whose days are all before it are hidden. + */ +class ReceivedRequestsViewModel( + private val listingId: String, + private val bookingRepository: BookingRepository, + private val listingRepository: ListingRepository, + private val profileRepository: ProfileRepository, + private val today: LocalDate = LocalDate.now(), +) : ViewModel() { + + private val _uiState = MutableStateFlow(ReceivedRequestsUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + /** The renters whose name was read or is being read, so that each is read once. */ + private val namesRequested = mutableSetOf() + + init { + loadRequests() + } + + /** + * Reads the bookings and the listing's offered days again, for example after a failure (Retry). + * Ignored while a read or an accept is running. On failure what is already shown stays shown. + */ + fun loadRequests() { + val state = _uiState.value + if (state.isLoading || state.acceptingId != null) return + _uiState.update { it.copy(isLoading = true, error = null) } + viewModelScope.launch { + try { + val bookings = bookingRepository.getBookingsForListing(listingId) + val offeredDays = listingRepository.getListing(listingId).getOrThrow().availableDates + show(bookings, offeredDays) + } catch (exception: Exception) { + // Cancellation means the screen was closed: it is not an error to show. + if (exception is CancellationException) throw exception + _uiState.update { it.copy(error = exception.toAppError()) } + } finally { + // Also on cancellation, otherwise the guard above would block every later read. + _uiState.update { it.copy(isLoading = false) } + } + } + } + + /** + * Accepts [request], which cancels the other requests sharing one of its days (see + * [BookingRepository.acceptBooking]). Ignored while a read or another accept is running, for a + * booking that is not waiting for an answer, and for one that [ReceivedRequestsUiState.canAccept] + * refuses. On failure the requests stay as they were and [ReceivedRequestsUiState.acceptError] + * says why. + */ + fun accept(request: Booking) { + val state = _uiState.value + if (state.isLoading || state.acceptingId != null) return + if (state.requests.none { it.id == request.id } || !state.canAccept(request)) return + // Set before launching, so a second tap in the same frame is already refused. + _uiState.update { it.copy(acceptingId = request.id, acceptError = null) } + viewModelScope.launch { + try { + bookingRepository.acceptBooking(request) + // Shown from what was saved, then read again below: the repository may also have cancelled + // a request sent since the screen loaded. The request shares its own days, so it leaves + // the waiting list with those it cancels. + _uiState.update { + it.copy( + requests = it.requests.filterNot { booking -> booking.overlaps(request) }, + // The accept took its days off the listing. + offeredDays = it.offeredDays - request.days, + accepted = + (it.accepted + request.copy(status = BookingStatus.CONFIRMED)).sortedBy( + Booking::firstDay + ), + ) + } + } catch (exception: Exception) { + if (exception is CancellationException) throw exception + _uiState.update { it.copy(acceptError = exception.toAppError()) } + return@launch + } finally { + // Also on cancellation, as in loadRequests. + _uiState.update { it.copy(acceptingId = null) } + } + loadRequests() + } + } + + private fun show(bookings: List, offeredDays: Set) { + val upcoming = + bookings + .filter { booking -> booking.days.any { !it.isBefore(today) } } + .sortedBy(Booking::firstDay) + _uiState.update { + it.copy( + requests = upcoming.filter { booking -> booking.status == BookingStatus.REQUESTED }, + accepted = upcoming.filter { booking -> booking.status == BookingStatus.CONFIRMED }, + offeredDays = offeredDays, + hasLoaded = true, + ) + } + upcoming.map { it.renterUid }.distinct().forEach { loadRenterName(it) } + } + + /** + * Reads the username of [renterUid] into [ReceivedRequestsUiState.renterNames], in its own + * coroutine so the list never waits for it. On failure the renter is shown without a name, and + * the next read of the bookings tries again. + */ + private fun loadRenterName(renterUid: String) { + if (!namesRequested.add(renterUid)) return + viewModelScope.launch { + try { + val renter = profileRepository.observeProfile(renterUid).first() + if (renter != null) { + _uiState.update { it.copy(renterNames = it.renterNames + (renterUid to renter.username)) } + } else { + namesRequested.remove(renterUid) + } + } catch (exception: Exception) { + namesRequested.remove(renterUid) + if (exception is CancellationException) throw exception + // Logged when unexpected, but not shown: a name is not worth an error. + exception.toAppError() + } + } + } +} diff --git a/app/src/sharedTest/java/com/android/polybazaar/booking/model/FakeBookingRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/booking/model/FakeBookingRepository.kt index e7607529..58cfb57c 100644 --- a/app/src/sharedTest/java/com/android/polybazaar/booking/model/FakeBookingRepository.kt +++ b/app/src/sharedTest/java/com/android/polybazaar/booking/model/FakeBookingRepository.kt @@ -12,6 +12,13 @@ import kotlinx.coroutines.currentCoroutineContext * were, and can hold a request back ([pendingRequest]), make it throw ([failure]) or report a write * failure, at once ([immediateWriteFailure]) or later through [writeFailure]. * + * [getBookingsForListing] returns the [listingBookings] of that listing. Like + * [getBookingsForRenter], it is counted in [loadCount], waits for [pendingLoad] when set and fails + * with [loadFailure] when set. [acceptBooking] changes [listingBookings] as the real repository + * does: the booking is confirmed and the other requests sharing a day with it cancelled. It waits + * for [acceptGate] when set and fails with [acceptFailure] when set, leaving [listingBookings] + * unchanged. + * * [getBookingsForLender] returns [lenderBookings], or throws [lenderLoadFailure], after * [pendingLenderLoad]; it has its own fields so that a screen loading both kinds of bookings can * fail one alone. @@ -39,6 +46,10 @@ class FakeBookingRepository : BookingRepository { var cancelWriteFailure: ((Exception) -> Unit)? = null var immediateCancelWriteFailure: Exception? = null + val accepted = mutableListOf() + var acceptGate: CompletableDeferred? = null + var acceptFailure: Exception? = null + override suspend fun requestBooking(booking: Booking, onWriteFailure: (Exception) -> Unit) { requestJob = currentCoroutineContext()[Job] requestedBooking = booking @@ -53,7 +64,7 @@ class FakeBookingRepository : BookingRepository { loadCount++ pendingLoad?.await() loadFailure?.let { throw it } - return listingBookings + return listingBookings.filter { it.listingId == listingId } } override suspend fun getBookingsForLender(): List { @@ -63,8 +74,20 @@ class FakeBookingRepository : BookingRepository { return lenderBookings } - /** Does nothing: no test answers a booking request yet. */ - override suspend fun acceptBooking(booking: Booking) = Unit + override suspend fun acceptBooking(booking: Booking) { + accepted += booking + acceptGate?.await() + acceptFailure?.let { throw it } + listingBookings = listingBookings.map { + when { + it.id == booking.id -> it.copy(status = BookingStatus.CONFIRMED) + it.status == BookingStatus.REQUESTED && + it.listingId == booking.listingId && + it.overlaps(booking) -> it.copy(status = BookingStatus.CANCELLED) + else -> it + } + } + } override suspend fun getBookingsForRenter(): List { loadCount++ diff --git a/app/src/test/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModelTest.kt b/app/src/test/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModelTest.kt new file mode 100644 index 00000000..02decc37 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModelTest.kt @@ -0,0 +1,324 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.booking.viewmodel + +import com.android.polybazaar.auth.model.User +import com.android.polybazaar.booking.model.Booking +import com.android.polybazaar.booking.model.BookingStatus +import com.android.polybazaar.booking.model.FakeBookingRepository +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.listing.model.FakeListingRepository +import com.android.polybazaar.listing.model.ItemListing +import com.android.polybazaar.listing.model.ListingCategory +import com.android.polybazaar.profile.model.FakeProfileRepository +import java.net.UnknownHostException +import java.time.LocalDate +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class ReceivedRequestsViewModelTest { + + private val testDispatcher = StandardTestDispatcher() + private val today = LocalDate.of(2026, 11, 18) + + private fun days(range: IntRange): Set = + range.mapTo(mutableSetOf()) { LocalDate.of(2026, 11, it) } + + private fun booking( + id: String, + renter: String, + days: Set, + status: BookingStatus = BookingStatus.REQUESTED, + listingId: String = "drill", + ) = Booking(listingId, renter, "lender", days, status, id) + + // Bob's request shares the 21st with Ann's; Cy's asks for other days. + private val ann = booking("ann", "uid-ann", days(20..21)) + private val bob = booking("bob", "uid-bob", days(21..22)) + private val cy = booking("cy", "uid-cy", days(25..26)) + + private val profiles = + FakeProfileRepository( + mapOf( + "uid-ann" to User(uid = "uid-ann", email = "", username = "ann_m"), + "uid-bob" to User(uid = "uid-bob", email = "", username = "bob.k"), + ) + ) + private lateinit var bookings: FakeBookingRepository + + /** The listing "drill", offering [days]: by default every day the requests above ask for. */ + private fun drill(days: Set = days(17..30)) = + ItemListing( + category = ListingCategory.ITEM_TOOLS, + price = 8.0, + title = "Drill", + description = "Cordless drill.", + refundValue = 120.0, + listingId = "drill", + ownerUid = "lender", + availableDates = days, + ) + + private val listings = FakeListingRepository(listOf(drill())) + + @Before + fun setUp() { + Dispatchers.setMain(testDispatcher) + bookings = FakeBookingRepository().apply { listingBookings = listOf(cy, bob, ann) } + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun newViewModel() = + ReceivedRequestsViewModel("drill", bookings, listings, profiles, today).also { + testDispatcher.scheduler.advanceUntilIdle() + } + + @Test + fun loads_theWaitingRequestsEarliestFirst_withTheRenterNames() = runTest { + val viewModel = newViewModel() + + val state = viewModel.uiState.value + assertTrue(state.hasLoaded) + assertFalse(state.isLoading) + assertEquals(listOf(ann, bob, cy), state.requests) + assertEquals(emptyList(), state.accepted) + // Cy has no profile: shown without a name. + assertEquals(mapOf("uid-ann" to "ann_m", "uid-bob" to "bob.k"), state.renterNames) + } + + @Test + fun loads_onlyThisListing_andHidesCancelledAndPastBookings() = runTest { + val accepted = booking("ok", "uid-ann", days(28..28), BookingStatus.CONFIRMED) + bookings.listingBookings = + listOf( + ann, + accepted, + booking("gone", "uid-bob", days(23..23), BookingStatus.CANCELLED), + booking("past", "uid-bob", days(10..17)), + booking("other", "uid-bob", days(20..20), listingId = "tent"), + ) + + val state = newViewModel().uiState.value + + assertEquals(listOf(ann), state.requests) + assertEquals(listOf(accepted), state.accepted) + } + + @Test + fun aRequestStartedBeforeToday_isStillShownWhileItHasDaysToCome() = runTest { + val ongoing = booking("now", "uid-ann", days(17..19)) + bookings.listingBookings = listOf(ongoing) + + assertEquals(listOf(ongoing), newViewModel().uiState.value.requests) + } + + @Test + fun conflictsOf_areTheOtherWaitingRequestsSharingADay() = runTest { + val state = newViewModel().uiState.value + + assertEquals(listOf(bob), state.conflictsOf(ann)) + assertEquals(listOf(ann), state.conflictsOf(bob)) + assertEquals(emptyList(), state.conflictsOf(cy)) + } + + @Test + fun aLoadFailure_isShown_andRetryLoads() = runTest { + bookings.loadFailure = UnknownHostException("offline") + val viewModel = newViewModel() + assertEquals(AppError.NETWORK, viewModel.uiState.value.error) + assertFalse(viewModel.uiState.value.hasLoaded) + + bookings.loadFailure = null + viewModel.loadRequests() + testDispatcher.scheduler.advanceUntilIdle() + + assertNull(viewModel.uiState.value.error) + assertEquals(listOf(ann, bob, cy), viewModel.uiState.value.requests) + } + + @Test + fun aFailedName_isReadAgainOnTheNextLoad() = runTest { + profiles.failingUids += "uid-ann" + val viewModel = newViewModel() + assertNull(viewModel.uiState.value.renterNames["uid-ann"]) + + profiles.failingUids.clear() + viewModel.loadRequests() + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals("ann_m", viewModel.uiState.value.renterNames["uid-ann"]) + // Bob's name was read the first time, and is not read again. + assertEquals(1, profiles.lookups["uid-bob"]) + } + + @Test + fun accept_confirmsTheRequest_andRemovesTheRequestsSharingItsDays() = runTest { + val viewModel = newViewModel() + + viewModel.accept(ann) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(listOf(ann), bookings.accepted) + val state = viewModel.uiState.value + assertEquals(listOf(cy), state.requests) + assertEquals(listOf(ann.copy(status = BookingStatus.CONFIRMED)), state.accepted) + assertNull(state.acceptingId) + // Read again after the accept, to catch requests sent since the screen loaded. + assertEquals(2, bookings.loadCount) + } + + @Test + fun accept_whileRunning_disablesAnotherAccept() = runTest { + val gate = CompletableDeferred() + bookings.acceptGate = gate + val viewModel = newViewModel() + + viewModel.accept(ann) + viewModel.accept(cy) + testDispatcher.scheduler.advanceUntilIdle() + assertEquals("ann", viewModel.uiState.value.acceptingId) + + gate.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + assertEquals(listOf(ann), bookings.accepted) + assertNull(viewModel.uiState.value.acceptingId) + } + + @Test + fun accept_ignoresABookingThatIsNotWaiting() = runTest { + val viewModel = newViewModel() + + viewModel.accept(booking("unknown", "uid-ann", days(20..20))) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(emptyList(), bookings.accepted) + } + + @Test + fun aFailedAccept_keepsTheRequests_andSaysWhy() = runTest { + bookings.acceptFailure = UnknownHostException("offline") + val viewModel = newViewModel() + + viewModel.accept(ann) + testDispatcher.scheduler.advanceUntilIdle() + + val state = viewModel.uiState.value + assertEquals(AppError.NETWORK, state.acceptError) + assertEquals(listOf(ann, bob, cy), state.requests) + assertNull(state.acceptingId) + + bookings.acceptFailure = null + viewModel.accept(ann) + testDispatcher.scheduler.advanceUntilIdle() + assertNull(viewModel.uiState.value.acceptError) + } + + @Test + fun aFailedReloadAfterAnAccept_keepsTheAcceptShown() = runTest { + val viewModel = newViewModel() + bookings.loadFailure = UnknownHostException("offline") + + viewModel.accept(ann) + testDispatcher.scheduler.advanceUntilIdle() + + val state = viewModel.uiState.value + assertEquals(listOf(cy), state.requests) + assertEquals(listOf(ann.copy(status = BookingStatus.CONFIRMED)), state.accepted) + } + + @Test + fun aRequestWithADayNoLongerOffered_isListedButCannotBeAccepted() = runTest { + // The owner edited the listing after the request was sent: saving dropped the past days, so + // the 17th, the first day of this ongoing request, is no longer offered. + val ongoing = booking("now", "uid-ann", days(17..19)) + bookings.listingBookings = listOf(ongoing, cy) + listings.allListings = listOf(drill(days(18..30))) + val viewModel = newViewModel() + + val state = viewModel.uiState.value + assertEquals(listOf(ongoing, cy), state.requests) + assertFalse(state.canAccept(ongoing)) + assertTrue(state.canAccept(cy)) + + viewModel.accept(ongoing) + testDispatcher.scheduler.advanceUntilIdle() + assertEquals(emptyList(), bookings.accepted) + assertNull(viewModel.uiState.value.acceptingId) + } + + @Test + fun aRequestSharingADayWithAnAcceptedBooking_cannotBeAccepted() = runTest { + // Left waiting by the accept race: the accept took the 21st and 22nd off the listing. + val confirmed = booking("ok", "uid-cy", days(21..22), BookingStatus.CONFIRMED) + bookings.listingBookings = listOf(confirmed, ann, cy) + listings.allListings = listOf(drill(days(17..20) + days(23..30))) + + val state = newViewModel().uiState.value + + assertEquals(listOf(ann, cy), state.requests) + assertFalse(state.canAccept(ann)) + assertTrue(state.canAccept(cy)) + } + + @Test + fun accept_takesTheAcceptedDaysOffTheOfferedDays() = runTest { + val gate = CompletableDeferred() + val viewModel = newViewModel() + // Hold back the reload, to see the state right after the accept. + bookings.pendingLoad = gate + + viewModel.accept(ann) + testDispatcher.scheduler.advanceUntilIdle() + + assertFalse(viewModel.uiState.value.offeredDays.any { it in ann.days }) + assertTrue(viewModel.uiState.value.canAccept(cy)) + gate.complete(Unit) + } + + @Test + fun aListingReadFailure_isShownAsALoadFailure_andRetryLoads() = runTest { + listings.failure = UnknownHostException("offline") + val viewModel = newViewModel() + assertEquals(AppError.NETWORK, viewModel.uiState.value.error) + assertFalse(viewModel.uiState.value.hasLoaded) + + listings.failure = null + viewModel.loadRequests() + testDispatcher.scheduler.advanceUntilIdle() + + assertNull(viewModel.uiState.value.error) + assertTrue(viewModel.uiState.value.canAccept(ann)) + } + + @Test + fun loadRequests_isIgnoredWhileALoadRuns() = runTest { + val gate = CompletableDeferred() + bookings.pendingLoad = gate + val viewModel = newViewModel() + assertTrue(viewModel.uiState.value.isLoading) + + viewModel.loadRequests() + viewModel.accept(ann) + gate.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, bookings.loadCount) + assertEquals(emptyList(), bookings.accepted) + } +}