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 1ed61ac2..afbcc9bc 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 @@ -31,5 +31,8 @@ data class Booking( 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 } + /** Whether every day is before [today]: the booking is history and stays as it is. */ fun Booking.isFinished(today: LocalDate): Boolean = days.all { it.isBefore(today) } 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..975fcfd7 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 @@ -16,6 +17,8 @@ import kotlinx.coroutines.tasks.await class FirebaseBookingRepository( private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance(), private val auth: FirebaseAuth = FirebaseAuth.getInstance(), + /** The current day, to leave finished requests alone when accepting. */ + private val today: () -> LocalDate = LocalDate::now, private val logWriteFailure: (Exception) -> Unit = { Log.e("BookingRepository", "Booking write failed", it) }, @@ -25,16 +28,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 +41,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 +51,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 +63,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 +74,56 @@ 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. A finished request is history: + // the rules refuse to cancel it, which would refuse the whole accept, so it is left as it is. + val today = today() + val overlapping = + getBookingsForListing(booking.listingId).filter { + it.id != booking.id && + it.status == BookingStatus.REQUESTED && + it.overlaps(booking) && + !it.isFinished(today) + } + 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 +147,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 d0af4d83..998c996c 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 @@ -47,6 +48,9 @@ class FakeBookingRepository : BookingRepository { return listingBookings } + /** 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..b6a4c143 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 @@ -40,7 +45,9 @@ class FirebaseBookingRepositoryTest { private val renterQuery = mock() private val snapshot = mock() private val stored = mock() - private val repository = FirebaseBookingRepository(firestore, auth) + // A fixed day before every booking these tests store, so none of them is ever finished. + private val repository = + FirebaseBookingRepository(firestore, auth, today = { LocalDate.of(2026, 11, 1) }) private val booking = Booking( listingId = "listing", @@ -297,4 +304,164 @@ 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()) + } + + @Test + fun acceptBookingLeavesFinishedRequestsSharingADayAsTheyAre() = runTest { + val batch = + givenLenderWith( + storedBooking("accepted", listOf(2, 3), BookingStatus.REQUESTED), + storedBooking("finished", listOf(1, 2), BookingStatus.REQUESTED), + storedBooking("current", listOf(3), BookingStatus.REQUESTED), + ) + val bookingDocuments = + listOf("accepted", "finished", "current").associateWith { + mock().also { reference -> + whenever(collection.document(it)).thenReturn(reference) + } + } + whenever(firestore.collection("listings")).thenReturn(mock()) + val repository = + FirebaseBookingRepository(firestore, auth, today = { LocalDate.of(2026, 12, 3) }) + val accepted = + Booking( + listingId = "listing", + renterUid = "renter-accepted", + lenderUid = "lender", + days = setOf(LocalDate.of(2026, 12, 2), LocalDate.of(2026, 12, 3)), + id = "accepted", + ) + + repository.acceptBooking(accepted) + + // Every day of "finished" is before today; "current" ends today, so it is still cancelled. + verify(batch).update(bookingDocuments.getValue("current"), "status", "CANCELLED") + verify(batch, never()).update(eq(bookingDocuments.getValue("finished")), 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 62b24d26..f78b6470 100644 --- a/firestore.rules +++ b/firestore.rules @@ -119,17 +119,40 @@ 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) + && request.resource.data.status == 'CANCELLED' + // Cancelling a cancelled booking changes nothing, so it is allowed: the renter may cancel + // a request while the lender's accept is cancelling it too, and the accept must not fail. + && (resource.data.status == 'CANCELLED' + || (resource.data.status in ['REQUESTED', 'CONFIRMED'] + // A finished booking is history. The app stores the days earliest first, so the + // last one decides; it must not be before today by server time. + && resource.data.days[resource.data.days.size() - 1] >= request.time.toMillis() / 86400000)); + } + + // 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'] - // A finished booking is history. The app stores the days earliest first, so the last - // one decides; it must not be before today by server time. - && resource.data.days[resource.data.days.size() - 1] >= request.time.toMillis() / 86400000 - && 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 f6770d52..c96d88a9 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, @@ -476,13 +477,26 @@ describe("listings", () => { await seed("bookings/confirmed", booking({ status: "CONFIRMED" })); await seed("bookings/cancelled", booking({ status: "CANCELLED" })); - await assertFails(updateDoc(doc(verified(BOB), "bookings/cancelled"), { status: "CANCELLED" })); + await assertFails(updateDoc(doc(verified(BOB), "bookings/cancelled"), { status: "REQUESTED" })); await assertFails(updateDoc(doc(verified(BOB), "bookings/requested"), { status: "CONFIRMED" })); await assertFails(updateDoc(doc(verified(BOB), "bookings/requested"), { status: "INVALID" })); await assertFails(updateDoc(doc(verified(ALICE), "bookings/confirmed"), { status: "REQUESTED" })); await assertFails(deleteDoc(doc(verified(BOB), "bookings/requested"))); }); + test("cancelling a cancelled booking changes nothing and is allowed to its renter and lender", async () => { + const today = Math.floor(Date.now() / 86_400_000); + await seed("bookings/cancelled", booking({ status: "CANCELLED" })); + await seed("bookings/finished", booking({ status: "CANCELLED", days: [today - 5, today - 3] })); + + await assertSucceeds(updateDoc(doc(verified(BOB), "bookings/cancelled"), { status: "CANCELLED" })); + await assertSucceeds(updateDoc(doc(verified(ALICE), "bookings/cancelled"), { status: "CANCELLED" })); + await assertSucceeds(updateDoc(doc(verified(ALICE), "bookings/finished"), { status: "CANCELLED" })); + await assertFails(updateDoc(doc(verified(EVE), "bookings/cancelled"), { status: "CANCELLED" })); + await assertFails(updateDoc(doc(unverified(BOB), "bookings/cancelled"), { status: "CANCELLED" })); + await assertFails(updateDoc(doc(verified(BOB), "bookings/cancelled"), { status: "CANCELLED", extra: true })); + }); + test("a finished booking cannot be cancelled", async () => { const today = Math.floor(Date.now() / 86_400_000); await seed("bookings/finished", booking({ days: [today - 5, today - 3] })); @@ -500,6 +514,84 @@ 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("the accept still succeeds when a renter cancels an overlapping request just before it", 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); + // The lender's app read b2 as requested; its renter cancels it before the accept is written. + await assertSucceeds(updateDoc(doc(verified(EVE), "bookings/b2"), { status: "CANCELLED" })); + + 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"); + }); + + 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 () => {