From 94f46ff75866b6d1f888fbc3cb735ef0afaf0bd1 Mon Sep 17 00:00:00 2001 From: Lucas Christiansson <98053131+madebylucke@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:40:53 +0100 Subject: [PATCH 1/3] feat(booking): let lenders accept booking requests Accepting confirms the request, takes its days off the listing and cancels the other requests for those days, in one batched write. The rules only confirm a request whose days the same write removes, so two requests sharing a day can never both be accepted. Part of #28. --- .../polybazaar/booking/model/Booking.kt | 3 + .../booking/model/BookingRepository.kt | 13 ++ .../model/FirebaseBookingRepository.kt | 84 +++++++---- .../booking/model/FakeBookingRepository.kt | 4 + .../model/FirebaseBookingRepositoryTest.kt | 132 ++++++++++++++++++ firestore.rules | 28 +++- rules-tests/firestore.test.js | 64 +++++++++ 7 files changed, 293 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/booking/model/Booking.kt b/app/src/main/java/com/android/polybazaar/booking/model/Booking.kt index beba52a0..3a736b8e 100644 --- a/app/src/main/java/com/android/polybazaar/booking/model/Booking.kt +++ b/app/src/main/java/com/android/polybazaar/booking/model/Booking.kt @@ -30,3 +30,6 @@ data class Booking( val status: BookingStatus = BookingStatus.REQUESTED, val id: String = "", ) + +/** Whether this booking and [other] share at least one day. */ +fun Booking.overlaps(other: Booking): Boolean = days.any { it in other.days } diff --git a/app/src/main/java/com/android/polybazaar/booking/model/BookingRepository.kt b/app/src/main/java/com/android/polybazaar/booking/model/BookingRepository.kt index cdd91432..fc859c9b 100644 --- a/app/src/main/java/com/android/polybazaar/booking/model/BookingRepository.kt +++ b/app/src/main/java/com/android/polybazaar/booking/model/BookingRepository.kt @@ -1,4 +1,5 @@ // Co-authored-by: Copilot (Auto) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.model interface BookingRepository { @@ -27,4 +28,16 @@ interface BookingRepository { * @param onWriteFailure receives a write failure that arrives after local queuing. */ suspend fun cancelBooking(id: String, onWriteFailure: (Exception) -> Unit = {}) + + /** + * Accepts [booking], a request on one of the signed-in lender's listings, in a single write: it + * becomes [BookingStatus.CONFIRMED], its days are taken off the listing's available days so no + * one can request them again, and every other request on the listing that asks for one of those + * days becomes [BookingStatus.CANCELLED]. Requests for other days stay as they are. + * + * Fails when nobody is signed in, or when Firestore cannot answer or refuses the write: for + * example when [booking] was already answered, or one of its days was taken by another request + * accepted first. + */ + suspend fun acceptBooking(booking: Booking) } diff --git a/app/src/main/java/com/android/polybazaar/booking/model/FirebaseBookingRepository.kt b/app/src/main/java/com/android/polybazaar/booking/model/FirebaseBookingRepository.kt index 06d34210..b6321e23 100644 --- a/app/src/main/java/com/android/polybazaar/booking/model/FirebaseBookingRepository.kt +++ b/app/src/main/java/com/android/polybazaar/booking/model/FirebaseBookingRepository.kt @@ -6,6 +6,7 @@ package com.android.polybazaar.booking.model import android.util.Log import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.DocumentSnapshot +import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import java.time.DateTimeException @@ -25,16 +26,11 @@ class FirebaseBookingRepository( booking: Booking, onWriteFailure: (Exception) -> Unit, ) { - val renterUid = - auth.currentUser?.uid - ?: throw FirebaseFirestoreException( - "Sign in to request a booking", - FirebaseFirestoreException.Code.UNAUTHENTICATED, - ) + val renterUid = signedInUid("Sign in to request a booking") require(booking.status == BookingStatus.REQUESTED) { "A new booking must be requested" } require(booking.days.isNotEmpty()) { "A booking needs at least one day" } firestore - .collection("bookings") + .collection(BOOKINGS) .document() .set( mapOf( @@ -43,7 +39,7 @@ class FirebaseBookingRepository( "lenderUid" to booking.lenderUid, // Earliest first: the rules check that the first day is not in the past. DAYS to booking.days.sorted().map { it.toEpochDay() }, - "status" to booking.status.name, + STATUS to booking.status.name, ) ) .addOnFailureListener(Executor { it.run() }) { @@ -53,14 +49,9 @@ class FirebaseBookingRepository( } override suspend fun getBookingsForListing(listingId: String): List { - val uid = - auth.currentUser?.uid - ?: throw FirebaseFirestoreException( - "Sign in to read bookings", - FirebaseFirestoreException.Code.UNAUTHENTICATED, - ) + val uid = signedInUid("Sign in to read bookings") return firestore - .collection("bookings") + .collection(BOOKINGS) .whereEqualTo("listingId", listingId) .whereEqualTo("lenderUid", uid) .get() @@ -70,14 +61,9 @@ class FirebaseBookingRepository( } override suspend fun getBookingsForRenter(): List { - val uid = - auth.currentUser?.uid - ?: throw FirebaseFirestoreException( - "Sign in to read bookings", - FirebaseFirestoreException.Code.UNAUTHENTICATED, - ) + val uid = signedInUid("Sign in to read bookings") return firestore - .collection("bookings") + .collection(BOOKINGS) .whereEqualTo("renterUid", uid) .get() .await() @@ -86,22 +72,51 @@ class FirebaseBookingRepository( } override suspend fun cancelBooking(id: String, onWriteFailure: (Exception) -> Unit) { - if (auth.currentUser == null) { - throw FirebaseFirestoreException( - "Sign in to cancel a booking", - FirebaseFirestoreException.Code.UNAUTHENTICATED, - ) - } + signedInUid("Sign in to cancel a booking") firestore - .collection("bookings") + .collection(BOOKINGS) .document(id) - .update("status", BookingStatus.CANCELLED.name) + .update(STATUS, BookingStatus.CANCELLED.name) .addOnFailureListener(Executor { it.run() }) { logWriteFailure(it) onWriteFailure(it) } } + override suspend fun acceptBooking(booking: Booking) { + signedInUid("Sign in to accept a booking") + require(booking.status == BookingStatus.REQUESTED) { "Only a request can be accepted" } + require(booking.id.isNotEmpty()) { "Only a stored booking can be accepted" } + // Read again rather than taken from the screen: a request sent since it loaded must be + // cancelled too. One sent between this read and the write stays requested; the rules then + // refuse to accept it, since its days are no longer offered. + val overlapping = + getBookingsForListing(booking.listingId).filter { + it.id != booking.id && it.status == BookingStatus.REQUESTED && it.overlaps(booking) + } + val bookings = firestore.collection(BOOKINGS) + val batch = firestore.batch() + batch.update(bookings.document(booking.id), STATUS, BookingStatus.CONFIRMED.name) + overlapping.forEach { + batch.update(bookings.document(it.id), STATUS, BookingStatus.CANCELLED.name) + } + // The rules only confirm a booking whose days this same write takes off the listing. + batch.update( + firestore.collection(LISTINGS).document(booking.listingId), + AVAILABLE_DATES, + FieldValue.arrayRemove(*booking.days.map { it.toEpochDay() }.toTypedArray()), + ) + batch.commit().await() + } + + /** The signed-in user's uid, or an UNAUTHENTICATED failure saying [message]. */ + private fun signedInUid(message: String): String = + auth.currentUser?.uid + ?: throw FirebaseFirestoreException( + message, + FirebaseFirestoreException.Code.UNAUTHENTICATED, + ) + private fun DocumentSnapshot.toBooking(): Booking { fun string(field: String): String = getString(field) ?: throw IllegalStateException("Booking $id is missing $field") @@ -125,13 +140,20 @@ class FirebaseBookingRepository( renterUid = string("renterUid"), lenderUid = string("lenderUid"), days = days(), - status = BookingStatus.valueOf(string("status")), + status = BookingStatus.valueOf(string(STATUS)), id = id, ) } private companion object { + const val BOOKINGS = "bookings" + const val STATUS = "status" + /** The booked days, as epoch days. */ const val DAYS = "days" + + /** The listings, and their offered days, as FirebaseListingRepository stores them. */ + const val LISTINGS = "listings" + const val AVAILABLE_DATES = "availableDates" } } 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 b1b88251..3918944a 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 @@ -1,5 +1,6 @@ // Co-authored-by: Copilot (Auto) // Co-authored-by: Claude Code (Claude Fable 5.2) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.model import kotlinx.coroutines.CompletableDeferred @@ -41,6 +42,9 @@ class FakeBookingRepository : BookingRepository { override suspend fun getBookingsForListing(listingId: String): List = emptyList() + /** Does nothing: no test answers a booking request yet. */ + override suspend fun acceptBooking(booking: Booking) = Unit + override suspend fun getBookingsForRenter(): List { loadCount++ pendingLoad?.await() diff --git a/app/src/test/java/com/android/polybazaar/booking/model/FirebaseBookingRepositoryTest.kt b/app/src/test/java/com/android/polybazaar/booking/model/FirebaseBookingRepositoryTest.kt index 2209775d..f9538ce5 100644 --- a/app/src/test/java/com/android/polybazaar/booking/model/FirebaseBookingRepositoryTest.kt +++ b/app/src/test/java/com/android/polybazaar/booking/model/FirebaseBookingRepositoryTest.kt @@ -10,20 +10,25 @@ import com.google.firebase.auth.FirebaseUser import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot +import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.Query import com.google.firebase.firestore.QuerySnapshot +import com.google.firebase.firestore.WriteBatch import java.time.LocalDate import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withTimeout import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify @@ -297,4 +302,131 @@ class FirebaseBookingRepositoryTest { ) verify(document, never()).update(any(), any()) } + + /** A stored booking of the lender on "listing", as the query returns it. */ + private fun storedBooking(id: String, days: List, status: BookingStatus): DocumentSnapshot { + val document = mock() + whenever(document.id).thenReturn(id) + whenever(document.getString("listingId")).thenReturn("listing") + whenever(document.getString("renterUid")).thenReturn("renter-$id") + whenever(document.getString("lenderUid")).thenReturn("lender") + whenever(document.get("days")).thenReturn(days.map { LocalDate.of(2026, 12, it).toEpochDay() }) + whenever(document.getString("status")).thenReturn(status.name) + return document + } + + /** The signed-in lender, their bookings on "listing", and a batch that commits. */ + private fun givenLenderWith(vararg documents: DocumentSnapshot): WriteBatch { + val lender = mock() + whenever(lender.uid).thenReturn("lender") + whenever(auth.currentUser).thenReturn(lender) + whenever(lenderQuery.get()).thenReturn(Tasks.forResult(snapshot)) + whenever(snapshot.documents).thenReturn(documents.toList()) + val batch = mock() + whenever(firestore.batch()).thenReturn(batch) + whenever(batch.commit()).thenReturn(Tasks.forResult(null)) + return batch + } + + @Test + fun acceptBookingConfirmsIt_takesItsDaysOff_andCancelsTheRequestsSharingADay() = runTest { + val batch = + givenLenderWith( + storedBooking("accepted", listOf(1, 2), BookingStatus.REQUESTED), + storedBooking("overlapping", listOf(2, 3), BookingStatus.REQUESTED), + storedBooking("elsewhere", listOf(5), BookingStatus.REQUESTED), + storedBooking("answered", listOf(1), BookingStatus.CANCELLED), + ) + val bookingDocuments = + listOf("accepted", "overlapping", "elsewhere", "answered").associateWith { + mock().also { reference -> + whenever(collection.document(it)).thenReturn(reference) + } + } + val listings = mock() + val listing = mock() + whenever(firestore.collection("listings")).thenReturn(listings) + whenever(listings.document("listing")).thenReturn(listing) + val accepted = + Booking( + listingId = "listing", + renterUid = "renter-accepted", + lenderUid = "lender", + days = setOf(LocalDate.of(2026, 12, 2), LocalDate.of(2026, 12, 1)), + id = "accepted", + ) + + repository.acceptBooking(accepted) + + val removed = argumentCaptor() + inOrder(batch) { + verify(batch).update(bookingDocuments.getValue("accepted"), "status", "CONFIRMED") + verify(batch).update(bookingDocuments.getValue("overlapping"), "status", "CANCELLED") + verify(batch).update(eq(listing), eq("availableDates"), removed.capture()) + verify(batch).commit() + } + // FieldValue has no equals: its elements are read instead, the stored epoch days. + assertEquals( + listOf(LocalDate.of(2026, 12, 1).toEpochDay(), LocalDate.of(2026, 12, 2).toEpochDay()), + arrayRemoveElements(removed.firstValue as FieldValue).map { it as Long }.sorted(), + ) + verify(batch, never()).update(eq(bookingDocuments.getValue("elsewhere")), any(), any()) + verify(batch, never()).update(eq(bookingDocuments.getValue("answered")), any(), any()) + } + + /** The elements of an arrayRemove, which the SDK keeps package-private. */ + private fun arrayRemoveElements(value: FieldValue): List<*> = + value.javaClass.getDeclaredMethod("getElements").apply { isAccessible = true }.invoke(value) + as List<*> + + @Test + fun acceptBookingFailsWhenTheWriteIsRefused() = runTest { + val batch = givenLenderWith(storedBooking("accepted", listOf(1), BookingStatus.REQUESTED)) + whenever(collection.document("accepted")).thenReturn(document) + whenever(firestore.collection("listings")).thenReturn(mock()) + val refused = + FirebaseFirestoreException("refused", FirebaseFirestoreException.Code.PERMISSION_DENIED) + whenever(batch.commit()).thenReturn(Tasks.forException(refused)) + val accepted = + Booking( + "listing", + "renter-accepted", + "lender", + setOf(LocalDate.of(2026, 12, 1)), + id = "accepted", + ) + + assertSame(refused, runCatching { repository.acceptBooking(accepted) }.exceptionOrNull()) + } + + @Test + fun acceptBookingNeedsASignedInUser_andAStoredRequest() = runTest { + val request = booking.copy(id = "b1") + whenever(auth.currentUser).thenReturn(null) + val signedOut = runCatching { repository.acceptBooking(request) }.exceptionOrNull() + assertEquals( + FirebaseFirestoreException.Code.UNAUTHENTICATED, + (signedOut as FirebaseFirestoreException).code, + ) + + val lender = mock() + whenever(lender.uid).thenReturn("lender") + whenever(auth.currentUser).thenReturn(lender) + assertTrue( + runCatching { repository.acceptBooking(booking) }.exceptionOrNull() + is IllegalArgumentException + ) + assertTrue( + runCatching { repository.acceptBooking(request.copy(status = BookingStatus.CONFIRMED)) } + .exceptionOrNull() is IllegalArgumentException + ) + verify(firestore, never()).batch() + } + + @Test + fun overlapsIsTrueOnlyWhenTheBookingsShareADay() { + val other = booking.copy(days = setOf(LocalDate.of(2027, 1, 2), LocalDate.of(2027, 1, 5))) + assertTrue(booking.overlaps(other)) + assertFalse(booking.overlaps(other.copy(days = setOf(LocalDate.of(2027, 1, 1))))) + } } diff --git a/firestore.rules b/firestore.rules index e9a4ba70..41e41b7d 100644 --- a/firestore.rules +++ b/firestore.rules @@ -119,14 +119,34 @@ service cloud.firestore { && data.status == 'REQUESTED'; } + // Either party cancels a request, or a confirmed booking. Accepting a request also cancels + // the other requests for its days, through this rule. + function isCancel() { + return (resource.data.lenderUid == request.auth.uid || resource.data.renterUid == request.auth.uid) + && resource.data.status in ['REQUESTED', 'CONFIRMED'] + && request.resource.data.status == 'CANCELLED'; + } + + // The lender accepts a request once. Accepting takes the booked days off the listing in the + // same write, so no one can request them again. They must still be offered before it, so two + // requests sharing a day can never both be accepted, even when accepted at the same time: the + // second sees the day gone. + function isAccept() { + let listingPath = /databases/$(database)/documents/listings/$(resource.data.listingId); + return resource.data.lenderUid == request.auth.uid + && resource.data.status == 'REQUESTED' + && request.resource.data.status == 'CONFIRMED' + && get(listingPath).data.get('availableDates', []).hasAll(resource.data.days) + && !getAfter(listingPath).data.get('availableDates', []).hasAny(resource.data.days); + } + allow read: if isVerified() && (resource.data.lenderUid == request.auth.uid || resource.data.renterUid == request.auth.uid); allow create: if isVerified() && validBooking(request.resource.data); + // Only the status changes. allow update: if isVerified() - && (resource.data.lenderUid == request.auth.uid || resource.data.renterUid == request.auth.uid) - && resource.data.status in ['REQUESTED', 'CONFIRMED'] - && request.resource.data.status == 'CANCELLED' - && request.resource.data.diff(resource.data).affectedKeys().hasOnly(['status']); + && request.resource.data.diff(resource.data).affectedKeys().hasOnly(['status']) + && (isCancel() || isAccept()); allow delete: if false; } diff --git a/rules-tests/firestore.test.js b/rules-tests/firestore.test.js index c2ab2f82..cb13fbd4 100644 --- a/rules-tests/firestore.test.js +++ b/rules-tests/firestore.test.js @@ -11,6 +11,7 @@ import { initializeTestEnvironment, } from "@firebase/rules-unit-testing"; import { + arrayRemove, collection, deleteDoc, deleteField, @@ -490,6 +491,69 @@ describe("listings", () => { await assertFails(updateDoc(ref, { status: "CANCELLED", days: [day0] })); await assertFails(updateDoc(ref, { status: "CANCELLED", extra: true })); }); + + /** Accepting as the app does: confirm, take the days off the listing, cancel the overlapping. */ + function accept(db, bookingId, bookedDays, cancelledIds = []) { + const batch = writeBatch(db); + batch.update(doc(db, `bookings/${bookingId}`), { status: "CONFIRMED" }); + cancelledIds.forEach((id) => batch.update(doc(db, `bookings/${id}`), { status: "CANCELLED" })); + batch.update(doc(db, "listings/l1"), { availableDates: arrayRemove(...bookedDays) }); + return batch.commit(); + } + + test("the lender accepts a request and cancels the requests that share its days", async () => { + await seed("listings/l1", offering(days(day0, day0 + 5))); + await seed("bookings/b1", booking({ days: [day0, day0 + 1] })); + await seed("bookings/b2", booking({ renterUid: EVE, days: [day0 + 1, day0 + 2] })); + await seed("bookings/b3", booking({ renterUid: EVE, days: [day0 + 4] })); + const db = verified(ALICE); + + await assertSucceeds(accept(db, "b1", [day0, day0 + 1], ["b2"])); + + const status = async (id) => (await getDoc(doc(db, `bookings/${id}`))).data().status; + assert.equal(await status("b1"), "CONFIRMED"); + assert.equal(await status("b2"), "CANCELLED"); + assert.equal(await status("b3"), "REQUESTED"); + const listing = (await getDoc(doc(db, "listings/l1"))).data(); + assert.deepEqual(listing.availableDates, days(day0 + 2, day0 + 5)); + // The accepted days can no longer be requested; the others still can. + await assertFails(setDoc(doc(verified(BOB), "bookings/b4"), booking({ days: [day0 + 1] }))); + await assertSucceeds(setDoc(doc(verified(BOB), "bookings/b5"), booking({ days: [day0 + 2] }))); + }); + + test("a request is only confirmed when the same write takes all its days off the listing", async () => { + await seed("listings/l1", offering(days(day0, day0 + 5))); + await seed("bookings/b1", booking({ days: [day0, day0 + 1] })); + const db = verified(ALICE); + await assertFails(updateDoc(doc(db, "bookings/b1"), { status: "CONFIRMED" })); + await assertFails(accept(db, "b1", [day0])); + await assertSucceeds(accept(db, "b1", [day0, day0 + 1])); + }); + + test("two requests sharing a day cannot both be accepted", async () => { + await seed("listings/l1", offering(days(day0, day0 + 5))); + await seed("bookings/b1", booking({ days: [day0, day0 + 1] })); + await seed("bookings/b2", booking({ renterUid: EVE, days: [day0 + 1, day0 + 2] })); + const db = verified(ALICE); + await assertSucceeds(accept(db, "b1", [day0, day0 + 1])); + // day0 + 1 is no longer offered, even though day0 + 2 still is. + await assertFails(accept(db, "b2", [day0 + 1, day0 + 2])); + }); + + test("only the verified lender accepts, and only a request still waiting", async () => { + await seed("listings/l1", offering(days(day0, day0 + 5))); + await seed("bookings/b1", booking({ days: [day0] })); + // Their days are still offered: only their status stops them being accepted. + await seed("bookings/confirmed", booking({ status: "CONFIRMED", days: [day0 + 3] })); + await seed("bookings/cancelled", booking({ status: "CANCELLED", days: [day0 + 4] })); + + await assertFails(accept(verified(BOB), "b1", [day0])); + await assertFails(accept(verified(EVE), "b1", [day0])); + await assertFails(accept(unverified(ALICE), "b1", [day0])); + await assertFails(accept(verified(ALICE), "confirmed", [day0 + 3])); + await assertFails(accept(verified(ALICE), "cancelled", [day0 + 4])); + await assertSucceeds(accept(verified(ALICE), "b1", [day0])); + }); }); test("a verified user can create a service listing", async () => { From c23d6196e5e2ad4fe3a443641a441cbe5a20aaef Mon Sep 17 00:00:00 2001 From: Lucas Christiansson <98053131+madebylucke@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:56:34 +0100 Subject: [PATCH 2/3] feat(booking): add the view model for answering booking requests Loads the bookings of one listing for its owner, waiting and accepted, with the renters' names, and accepts the request the owner chooses. Part of #28. --- .../viewmodel/ReceivedRequestsViewModel.kt | 180 +++++++++++++ .../booking/model/FakeBookingRepository.kt | 38 ++- .../ReceivedRequestsViewModelTest.kt | 242 ++++++++++++++++++ 3 files changed, 456 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModel.kt create mode 100644 app/src/test/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModelTest.kt 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..94a2f3e2 --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModel.kt @@ -0,0 +1,180 @@ +// 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.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 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 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 hasLoaded: Boolean = false, + val isLoading: Boolean = false, + val acceptingId: String? = null, + val error: AppError? = null, + val acceptError: AppError? = null, +) { + /** 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 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 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 again, for example after a failure (Retry). Ignored while a read or an + * accept is running. On failure the bookings already shown stay 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 { + show(bookingRepository.getBookingsForListing(listingId)) + } 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, and for + * a booking that is not waiting for an answer. 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 }) 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) }, + 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) { + 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 }, + 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 3918944a..9faf22d3 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 @@ -11,8 +11,14 @@ import kotlinx.coroutines.currentCoroutineContext * A [BookingRepository] in memory, for tests. It records the last booking requested and how many * 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 [bookings] of that listing, counted in [reads]; it waits for + * [readGate] when set and fails with [readFailure] when set. [acceptBooking] changes [bookings] 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 + * [bookings] unchanged. */ -class FakeBookingRepository : BookingRepository { +class FakeBookingRepository(var bookings: List = emptyList()) : BookingRepository { var requestedBooking: Booking? = null var requestCount = 0 var pendingRequest: CompletableDeferred? = null @@ -30,6 +36,13 @@ class FakeBookingRepository : BookingRepository { var cancelWriteFailure: ((Exception) -> Unit)? = null var immediateCancelWriteFailure: Exception? = null + var reads = 0 + var readGate: CompletableDeferred? = null + var readFailure: 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 @@ -40,10 +53,27 @@ class FakeBookingRepository : BookingRepository { failure?.let { throw it } } - override suspend fun getBookingsForListing(listingId: String): List = emptyList() + override suspend fun getBookingsForListing(listingId: String): List { + reads++ + readGate?.await() + readFailure?.let { throw it } + return bookings.filter { it.listingId == listingId } + } - /** 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 } + bookings = bookings.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..f5f37eda --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModelTest.kt @@ -0,0 +1,242 @@ +// 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.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 + + @Before + fun setUp() { + Dispatchers.setMain(testDispatcher) + bookings = FakeBookingRepository(listOf(cy, bob, ann)) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun newViewModel() = + ReceivedRequestsViewModel("drill", bookings, 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.bookings = + 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.bookings = 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.readFailure = UnknownHostException("offline") + val viewModel = newViewModel() + assertEquals(AppError.NETWORK, viewModel.uiState.value.error) + assertFalse(viewModel.uiState.value.hasLoaded) + + bookings.readFailure = 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.reads) + } + + @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.readFailure = 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 loadRequests_isIgnoredWhileALoadRuns() = runTest { + val gate = CompletableDeferred() + bookings.readGate = gate + val viewModel = newViewModel() + assertTrue(viewModel.uiState.value.isLoading) + + viewModel.loadRequests() + viewModel.accept(ann) + gate.complete(Unit) + testDispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, bookings.reads) + assertEquals(emptyList(), bookings.accepted) + } +} From 0f6701709e25475281fbd2b82d240ce1425f309c Mon Sep 17 00:00:00 2001 From: Lucas Christiansson <98053131+madebylucke@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:17:52 +0100 Subject: [PATCH 3/3] fix(booking): only offer Accept when every day of the request is still offered --- .../viewmodel/ReceivedRequestsViewModel.kt | 37 ++++++-- .../ReceivedRequestsViewModelTest.kt | 84 ++++++++++++++++++- 2 files changed, 111 insertions(+), 10 deletions(-) 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 index 94a2f3e2..8a41f0da 100644 --- a/app/src/main/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModel.kt @@ -9,6 +9,7 @@ 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 @@ -29,23 +30,32 @@ import kotlinx.coroutines.launch * @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 could not be read, or null. + * @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) @@ -59,11 +69,14 @@ private val Booking.firstDay: LocalDate /** * 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() { @@ -79,8 +92,8 @@ class ReceivedRequestsViewModel( } /** - * Reads the bookings again, for example after a failure (Retry). Ignored while a read or an - * accept is running. On failure the bookings already shown stay shown. + * 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 @@ -88,7 +101,9 @@ class ReceivedRequestsViewModel( _uiState.update { it.copy(isLoading = true, error = null) } viewModelScope.launch { try { - show(bookingRepository.getBookingsForListing(listingId)) + 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 @@ -102,14 +117,15 @@ class ReceivedRequestsViewModel( /** * Accepts [request], which cancels the other requests sharing one of its days (see - * [BookingRepository.acceptBooking]). Ignored while a read or another accept is running, and for - * a booking that is not waiting for an answer. On failure the requests stay as they were and - * [ReceivedRequestsUiState.acceptError] says why. + * [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 }) 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 { @@ -121,6 +137,8 @@ class ReceivedRequestsViewModel( _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 @@ -139,7 +157,7 @@ class ReceivedRequestsViewModel( } } - private fun show(bookings: List) { + private fun show(bookings: List, offeredDays: Set) { val upcoming = bookings .filter { booking -> booking.days.any { !it.isBefore(today) } } @@ -148,6 +166,7 @@ class ReceivedRequestsViewModel( it.copy( requests = upcoming.filter { booking -> booking.status == BookingStatus.REQUESTED }, accepted = upcoming.filter { booking -> booking.status == BookingStatus.CONFIRMED }, + offeredDays = offeredDays, hasLoaded = true, ) } 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 index d7a07aeb..02decc37 100644 --- a/app/src/test/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/booking/viewmodel/ReceivedRequestsViewModelTest.kt @@ -6,6 +6,9 @@ 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 @@ -55,6 +58,21 @@ class ReceivedRequestsViewModelTest { ) 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) @@ -67,7 +85,7 @@ class ReceivedRequestsViewModelTest { } private fun newViewModel() = - ReceivedRequestsViewModel("drill", bookings, profiles, today).also { + ReceivedRequestsViewModel("drill", bookings, listings, profiles, today).also { testDispatcher.scheduler.advanceUntilIdle() } @@ -224,6 +242,70 @@ class ReceivedRequestsViewModelTest { 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()