From 4655d598b95871309e6ead3b6660320a6b81de65 Mon Sep 17 00:00:00 2001 From: Lucas Christiansson <98053131+madebylucke@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:36:48 +0100 Subject: [PATCH 1/2] feat(booking): request separate days in one booking A booking stores a list of days instead of a first and last day, so a renter can request 1, 4 and 8-10 Nov together. Every requested day counts towards maxRentalDays. The rules check that every day is offered, once; only the first is checked against today, since rules cannot loop (#346). --- .../polybazaar/booking/model/Booking.kt | 8 +- .../model/FirebaseBookingRepository.kt | 25 ++++-- .../booking/ui/BookingRequestScreen.kt | 7 +- .../viewmodel/BookingRequestViewModel.kt | 64 ++++--------- .../model/FirebaseBookingRepositoryTest.kt | 52 +++++++++-- .../booking/ui/BookingRequestScreenTest.kt | 33 +++++-- .../viewmodel/BookingRequestViewModelTest.kt | 74 ++++++++------- .../booking/viewmodel/BookingViewModelTest.kt | 6 +- firestore.rules | 27 +++--- rules-tests/firestore.test.js | 89 ++++++++++--------- 10 files changed, 222 insertions(+), 163 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 25524f2c..beba52a0 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 @@ -1,5 +1,6 @@ // Co-authored-by: Claude Haiku 5.5 // Co-authored-by: Copilot (GPT-5.6 Terra) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.model import java.time.LocalDate @@ -16,8 +17,8 @@ enum class BookingStatus { * @property listingId ID of the booked listing. * @property renterUid uid of the user who books the listing. * @property lenderUid uid of the listing owner. - * @property startDate first day of the booking. - * @property endDate last day of the booking. + * @property days the days booked, at least one. They need not follow each other: 1, 4 and 8–10 Nov + * can be one booking. * @property status where the booking is in its lifecycle, starting at [BookingStatus.REQUESTED]. * @property id Firestore document ID, populated when the booking is read. */ @@ -25,8 +26,7 @@ data class Booking( val listingId: String, val renterUid: String, val lenderUid: String, - val startDate: LocalDate, - val endDate: LocalDate, + val days: Set, val status: BookingStatus = BookingStatus.REQUESTED, val id: String = "", ) 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 b3a217f0..cd4354b0 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 @@ -1,5 +1,6 @@ // Co-authored-by: Copilot (Auto) // Co-authored-by: Copilot (GPT-5.6 Terra) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.model import android.util.Log @@ -30,7 +31,7 @@ class FirebaseBookingRepository( FirebaseFirestoreException.Code.UNAUTHENTICATED, ) require(booking.status == BookingStatus.REQUESTED) { "A new booking must be requested" } - require(!booking.endDate.isBefore(booking.startDate)) { "Booking end date precedes start date" } + require(booking.days.isNotEmpty()) { "A booking needs at least one day" } firestore .collection("bookings") .document() @@ -39,8 +40,8 @@ class FirebaseBookingRepository( "listingId" to booking.listingId, "renterUid" to renterUid, "lenderUid" to booking.lenderUid, - "startDate" to booking.startDate.toEpochDay(), - "endDate" to booking.endDate.toEpochDay(), + // 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, ) ) @@ -70,19 +71,29 @@ class FirebaseBookingRepository( private fun DocumentSnapshot.toBooking(): Booking { fun string(field: String): String = getString(field) ?: throw IllegalStateException("Booking $id is missing $field") - fun date(field: String): LocalDate = + fun days(): Set { + val epochDays = + (get(DAYS) as? List<*>)?.takeIf { it.isNotEmpty() } + ?: throw IllegalStateException("Booking $id is missing $DAYS") + return epochDays.mapTo(mutableSetOf()) { LocalDate.ofEpochDay( - getLong(field) ?: throw IllegalStateException("Booking $id is missing $field") + (it as? Long) ?: throw IllegalStateException("Booking $id has an invalid day: $it") ) + } + } return Booking( listingId = string("listingId"), renterUid = string("renterUid"), lenderUid = string("lenderUid"), - startDate = date("startDate"), - endDate = date("endDate"), + days = days(), status = BookingStatus.valueOf(string("status")), id = id, ) } + + private companion object { + /** The booked days, as epoch days. */ + const val DAYS = "days" + } } diff --git a/app/src/main/java/com/android/polybazaar/booking/ui/BookingRequestScreen.kt b/app/src/main/java/com/android/polybazaar/booking/ui/BookingRequestScreen.kt index 1e0512af..2102093e 100644 --- a/app/src/main/java/com/android/polybazaar/booking/ui/BookingRequestScreen.kt +++ b/app/src/main/java/com/android/polybazaar/booking/ui/BookingRequestScreen.kt @@ -1,4 +1,5 @@ // Co-authored-by: Claude Code (Claude Fable 5.2) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.ui import androidx.compose.foundation.background @@ -235,8 +236,8 @@ private fun Heading(title: String, listingTitle: String) { } /** - * The period chosen, written as "13–16 Nov". Tapping the field opens the calendar, where only the - * days the lender offers can be chosen. Under it: why the period cannot be requested, if so. + * The days chosen, written as "1, 4, 8–10 Nov". Tapping the field opens the calendar, where only + * the days the lender offers can be chosen. Under it: why the days cannot be requested, if so. */ @Composable private fun DatesField( @@ -317,7 +318,7 @@ private fun DatesField( } /** - * What the request costs: the price for each day and the total once a period is chosen, the damage + * What the request costs: the price for each day and the total once days are chosen, the damage * compensation of an item, and how payment works. */ @Composable diff --git a/app/src/main/java/com/android/polybazaar/booking/viewmodel/BookingRequestViewModel.kt b/app/src/main/java/com/android/polybazaar/booking/viewmodel/BookingRequestViewModel.kt index abc54dec..a5c92bbe 100644 --- a/app/src/main/java/com/android/polybazaar/booking/viewmodel/BookingRequestViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/booking/viewmodel/BookingRequestViewModel.kt @@ -1,4 +1,5 @@ // Co-authored-by: Claude Code (Claude Fable 5.2) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.viewmodel import androidx.lifecycle.ViewModel @@ -6,8 +7,6 @@ import androidx.lifecycle.viewModelScope import com.android.polybazaar.auth.model.AuthRepository import com.android.polybazaar.auth.model.User import com.android.polybazaar.booking.model.Booking -import com.android.polybazaar.booking.model.DateRun -import com.android.polybazaar.booking.model.groupIntoRuns import com.android.polybazaar.booking.model.upcomingDays import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.toAppError @@ -16,7 +15,6 @@ import com.android.polybazaar.listing.model.Listing import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.listing.model.ListingRules import java.time.LocalDate -import java.time.temporal.ChronoUnit import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -24,21 +22,6 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -/** - * [selection] cut down to one period, since a booking runs from a first day to a last day. Days in - * a row are kept as they are. Otherwise the period holding a day that is not in [previous] wins, so - * that choosing a day away from the period chosen so far starts a new one; when no day was added (a - * day in the middle was unselected), the earliest period is kept. - */ -internal fun singlePeriod(previous: Set, selection: Set): Set { - val runs = groupIntoRuns(selection) - if (runs.size <= 1) return selection - fun DateRun.holds(day: LocalDate) = !day.isBefore(start) && !day.isAfter(end) - val added = selection - previous - val kept = runs.firstOrNull { run -> added.any { run.holds(it) } } ?: runs.first() - return selection.filterTo(mutableSetOf()) { kept.holds(it) } -} - /** * State of the screen where a renter requests a listing for some days (#26). * @@ -50,7 +33,8 @@ internal fun singlePeriod(previous: Set, selection: Set): * for example without a connection. The request is then disabled without the user being refused: * loading again reads them again. * @property selectableDays the days the lender offers that are not in the past. - * @property selection the days the renter chose: one period, all among [selectableDays]. + * @property selection the days the renter chose, all among [selectableDays]. They need not follow + * each other. * @property today the day earlier days cannot be requested from, for the calendar to use as well. * @property isLoading true while the listing is being loaded. * @property error why the listing could not be loaded, or null. @@ -69,47 +53,44 @@ data class BookingRequestUiState( val canRequest: Boolean get() = renterUid != null - /** The period chosen, or null when no day is chosen. */ - val period: DateRun? - get() = groupIntoRuns(selection).singleOrNull() - - /** How many days [period] lasts, both ends included; 0 without a period. */ + /** How many days are chosen, counted one by one, whether they follow each other or not. */ val dayCount: Int - get() = period?.let { ChronoUnit.DAYS.between(it.start, it.end).toInt() + 1 } ?: 0 + get() = selection.size /** The longest the item can be kept, in days, or null for a service or an item without limit. */ val maxRentalDays: Int? get() = (listing as? ItemListing)?.maxRentalDays - /** Whether [period] is longer than [maxRentalDays], so that it cannot be requested. */ + /** + * Whether more days are chosen than [maxRentalDays], so that they cannot be requested. Every day + * counts: 1, 4 and 8–10 Nov make 5 days. + */ val isTooLong: Boolean get() = maxRentalDays?.let { dayCount > it } ?: false /** - * The price of [period]: the listing's price for each of its days. Null without a period that can - * be requested, so that no total is shown for one that [isTooLong]. It does not depend on + * The price of [selection]: the listing's price for each day. Null without days that can be + * requested, so that no total is shown for days that [isTooLong]. It does not depend on * [canRequest]: a user who may not request the listing still sees what the days would cost. */ val total: Double? - get() = listing?.takeIf { period != null && !isTooLong }?.let { it.price * dayCount } + get() = listing?.takeIf { selection.isNotEmpty() && !isTooLong }?.let { it.price * dayCount } /** * The request to send, or null while it cannot be sent: no listing, a user who may not request - * it, no day chosen or a period that [isTooLong]. + * it, no day chosen or days that [isTooLong]. */ val booking: Booking? get() { val listingId = listing?.listingId val lenderUid = listing?.ownerUid - val chosen = period if (listingId == null || lenderUid == null || renterUid == null) return null - if (chosen == null || isTooLong) return null + if (selection.isEmpty() || isTooLong) return null return Booking( listingId = listingId, renterUid = renterUid, lenderUid = lenderUid, - startDate = chosen.start, - endDate = chosen.end, + days = selection, ) } } @@ -158,14 +139,9 @@ class BookingRequestViewModel( } } - /** - * Replaces the days chosen by [selection], leaving out any day the lender does not offer and - * keeping one period (see [singlePeriod]). - */ + /** Replaces the days chosen by [selection], leaving out any day the lender does not offer. */ fun updateSelection(selection: Set) { - _uiState.update { - it.copy(selection = singlePeriod(it.selection, selection intersect it.selectableDays)) - } + _uiState.update { it.copy(selection = selection intersect it.selectableDays) } } private suspend fun showListing(listing: Listing) { @@ -181,10 +157,8 @@ class BookingRequestViewModel( renterUid = viewer?.takeIf { user -> ListingRules.canContactLender(user, listing) }?.uid, isViewerUnknown = viewer == null, selectableDays = selectableDays, - // A reload may find days the lender has taken back since, even in the middle of the - // period. - selection = - (it.selection intersect selectableDays).let { left -> singlePeriod(left, left) }, + // A reload may find days the lender has taken back since. + selection = it.selection intersect selectableDays, ) } } 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 f501410d..f64da47b 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 @@ -1,5 +1,6 @@ // Co-authored-by: Copilot (Auto) // Co-authored-by: Copilot (GPT-5.6 Terra) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.model import com.google.android.gms.tasks.TaskCompletionSource @@ -44,8 +45,8 @@ class FirebaseBookingRepositoryTest { listingId = "listing", renterUid = "caller-renter", lenderUid = "lender", - startDate = LocalDate.of(2026, 12, 31), - endDate = LocalDate.of(2027, 1, 2), + // Separate days, given out of order, across two years. + days = setOf(LocalDate.of(2027, 1, 2), LocalDate.of(2026, 12, 31)), ) @Before @@ -72,8 +73,12 @@ class FirebaseBookingRepositoryTest { "listingId" to "listing", "renterUid" to "renter", "lenderUid" to "lender", - "startDate" to booking.startDate.toEpochDay(), - "endDate" to booking.endDate.toEpochDay(), + // Earliest first, as the rules check the first day against today. + "days" to + listOf( + LocalDate.of(2026, 12, 31).toEpochDay(), + LocalDate.of(2027, 1, 2).toEpochDay(), + ), "status" to "REQUESTED", ) ) @@ -108,12 +113,12 @@ class FirebaseBookingRepositoryTest { } @Test - fun requestBookingRejectsInvalidDatesAndStatus() = runTest { - val reversed = booking.copy(endDate = booking.startDate.minusDays(1)) + fun requestBookingRejectsNoDaysAndANonRequestedStatus() = runTest { + val noDays = booking.copy(days = emptySet()) val confirmed = booking.copy(status = BookingStatus.CONFIRMED) assertTrue( - runCatching { repository.requestBooking(reversed) }.exceptionOrNull() + runCatching { repository.requestBooking(noDays) }.exceptionOrNull() is IllegalArgumentException ) assertTrue( @@ -133,8 +138,7 @@ class FirebaseBookingRepositoryTest { whenever(stored.getString("listingId")).thenReturn(booking.listingId) whenever(stored.getString("renterUid")).thenReturn(booking.renterUid) whenever(stored.getString("lenderUid")).thenReturn(booking.lenderUid) - whenever(stored.getLong("startDate")).thenReturn(booking.startDate.toEpochDay()) - whenever(stored.getLong("endDate")).thenReturn(booking.endDate.toEpochDay()) + whenever(stored.get("days")).thenReturn(booking.days.map { it.toEpochDay() }) whenever(stored.getString("status")).thenReturn("CANCELLED") whenever(stored.id).thenReturn("booking-id") @@ -158,6 +162,36 @@ class FirebaseBookingRepositoryTest { ) } + @Test + fun getBookingsRejectsABookingWithoutDaysOrWithAnInvalidDay() = runTest { + val lender = mock() + whenever(lender.uid).thenReturn("lender") + whenever(auth.currentUser).thenReturn(lender) + whenever(lenderQuery.get()).thenReturn(Tasks.forResult(snapshot)) + whenever(snapshot.documents).thenReturn(listOf(stored)) + whenever(stored.getString("listingId")).thenReturn(booking.listingId) + whenever(stored.getString("renterUid")).thenReturn(booking.renterUid) + whenever(stored.getString("lenderUid")).thenReturn(booking.lenderUid) + whenever(stored.getString("status")).thenReturn("REQUESTED") + + // A booking written with the first and last day of earlier versions has no days. + whenever(stored.get("days")).thenReturn(null) + assertTrue( + runCatching { repository.getBookingsForListing("listing") }.exceptionOrNull() + is IllegalStateException + ) + whenever(stored.get("days")).thenReturn(emptyList()) + assertTrue( + runCatching { repository.getBookingsForListing("listing") }.exceptionOrNull() + is IllegalStateException + ) + whenever(stored.get("days")).thenReturn(listOf("20000")) + assertTrue( + runCatching { repository.getBookingsForListing("listing") }.exceptionOrNull() + is IllegalStateException + ) + } + @Test fun getBookingsRejectsSignedOutUser() = runTest { whenever(auth.currentUser).thenReturn(null) diff --git a/app/src/test/java/com/android/polybazaar/booking/ui/BookingRequestScreenTest.kt b/app/src/test/java/com/android/polybazaar/booking/ui/BookingRequestScreenTest.kt index 1d05f8a4..e77ec168 100644 --- a/app/src/test/java/com/android/polybazaar/booking/ui/BookingRequestScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/booking/ui/BookingRequestScreenTest.kt @@ -1,4 +1,5 @@ // Co-authored-by: Claude Code (Claude Fable 5.2) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.ui import android.content.Context @@ -136,7 +137,7 @@ class BookingRequestScreenTest { } @Test - fun aChosenPeriod_showsTheDatesThePriceAndTheTotal() { + fun daysInARow_showTheDatesThePriceAndTheTotal() { setContent(drillState(selection = days(13..15))) composeTestRule.onNodeWithText("13–15 Nov").assertIsDisplayed() @@ -145,6 +146,16 @@ class BookingRequestScreenTest { node(BookingRequestScreenTags.SUBMIT_BUTTON).assertIsEnabled() } + @Test + fun separateDays_showTogether_withThePriceOfEachDay() { + setContent(drillState(selection = setOf(day(13), day(15), day(20)))) + + composeTestRule.onNodeWithText("13, 15, 20 Nov").assertIsDisplayed() + node(BookingRequestScreenTags.PRICE_LINE).assertTextEquals("CHF 8 / day × 3 days") + node(BookingRequestScreenTags.TOTAL).assertTextEquals("CHF 24") + node(BookingRequestScreenTags.SUBMIT_BUTTON).assertIsEnabled() + } + @Test fun aSingleDay_isWrittenInTheSingular() { setContent(drillState(selection = setOf(day(20)))) @@ -190,7 +201,7 @@ class BookingRequestScreenTest { } @Test - fun aPeriodLongerThanTheItemAllows_isRefused() { + fun moreDaysThanTheItemAllows_areRefused() { setContent(drillState(selection = days(13..16))) node(BookingRequestScreenTags.DATES_MESSAGE) @@ -270,6 +281,17 @@ class BookingRequestScreenTest { node(BookingRequestScreenTags.SUBMIT_BUTTON).assertIsEnabled() } + @Test + fun onceSent_confirmsSeparateDays() { + setContent( + drillState(selection = setOf(day(13), day(15), day(16))), + BookingUiState(isQueued = true), + ) + + node(BookingRequestScreenTags.SENT_MESSAGE) + .assertTextEquals("You asked for 13, 15–16 Nov. The lender still has to accept it.") + } + @Test fun onceSent_confirmsTheDays_andDoneLeaves() { var dones = 0 @@ -315,7 +337,7 @@ class BookingRequestScreenTest { } @Test - fun withItsViewModels_aChosenPeriodIsRequested_thenConfirmed() { + fun withItsViewModels_separateDaysAreRequested_thenConfirmed() { val renter = User(uid = "renter", email = "renter@epfl.ch", username = "Rita", isEmailVerified = true) val auth: AuthRepository = mock { onBlocking { getCurrentUser() } doReturn renter } @@ -334,7 +356,7 @@ class BookingRequestScreenTest { } composeTestRule.waitForIdle() - viewModel.updateSelection(days(13..15)) + viewModel.updateSelection(setOf(day(13), day(15), day(20))) node(BookingRequestScreenTags.SUBMIT_BUTTON).performScrollTo().performClick() composeTestRule.waitForIdle() @@ -343,8 +365,7 @@ class BookingRequestScreenTest { listingId = "drill", renterUid = "renter", lenderUid = "lender", - startDate = day(13), - endDate = day(15), + days = setOf(day(13), day(15), day(20)), ), bookings.requestedBooking, ) diff --git a/app/src/test/java/com/android/polybazaar/booking/viewmodel/BookingRequestViewModelTest.kt b/app/src/test/java/com/android/polybazaar/booking/viewmodel/BookingRequestViewModelTest.kt index 069189cd..3d97f200 100644 --- a/app/src/test/java/com/android/polybazaar/booking/viewmodel/BookingRequestViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/booking/viewmodel/BookingRequestViewModelTest.kt @@ -1,10 +1,10 @@ // Co-authored-by: Claude Code (Claude Fable 5.2) +// Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.booking.viewmodel import com.android.polybazaar.auth.model.AuthRepository import com.android.polybazaar.auth.model.User import com.android.polybazaar.booking.model.Booking -import com.android.polybazaar.booking.model.DateRun import com.android.polybazaar.error.model.AppError import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.ItemListing @@ -194,13 +194,12 @@ class BookingRequestViewModelTest { } @Test - fun daysInARow_makeAPeriod_withItsTotalAndBooking() { + fun daysInARow_giveTheirTotalAndBooking() { val viewModel = loadedViewModel() viewModel.updateSelection(days(13..15)) val state = viewModel.uiState.value - assertEquals(DateRun(day(13), day(15)), state.period) assertEquals(3, state.dayCount) assertEquals(24.0, state.total!!, 0.0) assertFalse(state.isTooLong) @@ -209,15 +208,27 @@ class BookingRequestViewModelTest { listingId = "drill", renterUid = "renter", lenderUid = "lender", - startDate = day(13), - endDate = day(15), + days = days(13..15), ), state.booking, ) } @Test - fun aSingleDay_isAPeriodOfOneDay() { + fun separateDays_areRequestedTogether_andEachIsPaid() { + val viewModel = loadedViewModel() + + viewModel.updateSelection(setOf(day(13), day(16), day(20))) + val state = viewModel.uiState.value + + assertEquals(setOf(day(13), day(16), day(20)), state.selection) + assertEquals(3, state.dayCount) + assertEquals(24.0, state.total!!, 0.0) + assertEquals(setOf(day(13), day(16), day(20)), state.booking?.days) + } + + @Test + fun aSingleDay_isRequestedAlone() { val viewModel = loadedViewModel() viewModel.updateSelection(setOf(day(20))) @@ -225,8 +236,7 @@ class BookingRequestViewModelTest { assertEquals(1, state.dayCount) assertEquals(8.0, state.total!!, 0.0) - assertEquals(day(20), state.booking?.startDate) - assertEquals(day(20), state.booking?.endDate) + assertEquals(setOf(day(20)), state.booking?.days) } @Test @@ -234,55 +244,57 @@ class BookingRequestViewModelTest { val state = loadedViewModel().uiState.value assertFalse(state.isTooLong) - assertNull(state.period) assertNull(state.total) assertEquals(0, state.dayCount) assertNull(state.booking) } @Test - fun choosingADayAwayFromThePeriod_startsANewPeriod() { + fun choosingADayAwayFromTheOthers_keepsThemAll() { val viewModel = loadedViewModel() - viewModel.updateSelection(days(13..14)) + viewModel.updateSelection(setOf(day(13))) - viewModel.updateSelection(days(13..14) + day(20)) + viewModel.updateSelection(setOf(day(13), day(15))) - assertEquals(setOf(day(20)), viewModel.uiState.value.selection) - assertEquals(DateRun(day(20), day(20)), viewModel.uiState.value.period) + assertEquals(setOf(day(13), day(15)), viewModel.uiState.value.selection) } @Test - fun choosingTheNextDay_extendsThePeriod() { + fun unselectingADayInTheMiddle_keepsTheDaysOnEitherSide() { val viewModel = loadedViewModel() - viewModel.updateSelection(days(13..14)) - viewModel.updateSelection(days(13..15)) - assertEquals(days(13..15), viewModel.uiState.value.selection) + viewModel.updateSelection(setOf(day(13), day(15))) + + assertEquals(setOf(day(13), day(15)), viewModel.uiState.value.selection) } @Test - fun unselectingADayInTheMiddle_keepsTheEarliestPeriod() { - val viewModel = loadedViewModel() - viewModel.updateSelection(days(13..15)) + fun aRangeOverDaysNotOffered_keepsOnlyTheOfferedOnes() { + val viewModel = loadedViewModel(listing = drill.copy(maxRentalDays = null)) - viewModel.updateSelection(setOf(day(13), day(15))) + // Holding the 13th then tapping the 20th skips the 17th to the 19th, which are not offered. + viewModel.updateSelection(days(13..20)) - assertEquals(setOf(day(13)), viewModel.uiState.value.selection) + assertEquals(days(13..16) + day(20), viewModel.uiState.value.selection) } @Test - fun aRangeOverDaysNotOffered_keepsItsFirstPeriod() { + fun separateDays_countTogether_towardsMaxRentalDays() { val viewModel = loadedViewModel() - // Holding the 13th then tapping the 20th skips the 17th to the 19th, which are not offered. - viewModel.updateSelection(days(13..16) + day(20)) + // Four days, no two of them in a row, are still four days: one more than the drill allows. + viewModel.updateSelection(setOf(day(13), day(15), day(16), day(20))) + val state = viewModel.uiState.value - assertEquals(days(13..16), viewModel.uiState.value.selection) + assertEquals(4, state.dayCount) + assertTrue(state.isTooLong) + assertNull(state.total) + assertNull(state.booking) } @Test - fun aPeriodLongerThanMaxRentalDays_cannotBeRequested() { + fun moreDaysThanMaxRentalDays_cannotBeRequested() { val viewModel = loadedViewModel() viewModel.updateSelection(days(13..16)) @@ -301,7 +313,7 @@ class BookingRequestViewModelTest { viewModel.updateSelection(days(13..16)) assertFalse(viewModel.uiState.value.isTooLong) - assertEquals(day(16), viewModel.uiState.value.booking?.endDate) + assertEquals(days(13..16), viewModel.uiState.value.booking?.days) } @Test @@ -352,7 +364,7 @@ class BookingRequestViewModelTest { } @Test - fun aReload_keepsOnePeriod_whenTheLenderTookBackADayInTheMiddle() { + fun aReload_keepsTheDaysOnEitherSide_whenTheLenderTookBackADayInTheMiddle() { val listings = FakeListingRepository(allListings = listOf(drill)) val viewModel = loadedViewModel(listings = listings) viewModel.updateSelection(days(13..15)) @@ -361,7 +373,7 @@ class BookingRequestViewModelTest { viewModel.loadListing() testDispatcher.scheduler.advanceUntilIdle() - assertEquals(setOf(day(13)), viewModel.uiState.value.selection) + assertEquals(setOf(day(13), day(15)), viewModel.uiState.value.selection) } @Test diff --git a/app/src/test/java/com/android/polybazaar/booking/viewmodel/BookingViewModelTest.kt b/app/src/test/java/com/android/polybazaar/booking/viewmodel/BookingViewModelTest.kt index 105d613f..f01927c6 100644 --- a/app/src/test/java/com/android/polybazaar/booking/viewmodel/BookingViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/booking/viewmodel/BookingViewModelTest.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.viewmodel import com.android.polybazaar.booking.model.Booking @@ -31,8 +32,7 @@ class BookingViewModelTest { listingId = "listing", renterUid = "renter", lenderUid = "lender", - startDate = LocalDate.of(2026, 12, 1), - endDate = LocalDate.of(2026, 12, 3), + days = setOf(LocalDate.of(2026, 12, 1), LocalDate.of(2026, 12, 3)), ) private lateinit var repository: FakeBookingRepository @@ -66,7 +66,7 @@ class BookingViewModelTest { viewModel.requestBooking(booking) testDispatcher.scheduler.advanceUntilIdle() viewModel.acknowledgeQueuedBooking() - viewModel.requestBooking(booking.copy(startDate = LocalDate.of(2026, 12, 4))) + viewModel.requestBooking(booking.copy(days = setOf(LocalDate.of(2026, 12, 4)))) testDispatcher.scheduler.advanceUntilIdle() assertEquals(2, repository.requestCount) diff --git a/firestore.rules b/firestore.rules index 8e2c2993..5e94610d 100644 --- a/firestore.rules +++ b/firestore.rules @@ -94,26 +94,27 @@ service cloud.firestore { match /bookings/{bookingId} { function validBooking(data) { let listing = get(/databases/$(database)/documents/listings/$(data.listingId)).data; - return data.keys().hasAll(['listingId', 'renterUid', 'lenderUid', 'startDate', 'endDate', 'status']) - && data.keys().hasOnly(['listingId', 'renterUid', 'lenderUid', 'startDate', 'endDate', 'status']) + return data.keys().hasAll(['listingId', 'renterUid', 'lenderUid', 'days', 'status']) + && data.keys().hasOnly(['listingId', 'renterUid', 'lenderUid', 'days', 'status']) && data.listingId is string && data.listingId.size() > 0 && data.renterUid == request.auth.uid && data.lenderUid is string && data.lenderUid == listing.ownerUid && listing.paused == false && data.renterUid != data.lenderUid - // LocalDate epoch days, bounded to the range supported by java.time.LocalDate. - && data.startDate is int && data.startDate >= -365243219162 - && data.endDate is int && data.endDate <= 365241780471 - // Compare against server time so client clock changes cannot create past bookings. - && data.startDate >= request.time.toMillis() / 86400000 - && data.startDate <= data.endDate - // Both ends are inclusive. A listing without maxRentalDays has no limit. - && (!('maxRentalDays' in listing) || data.endDate - data.startDate + 1 <= listing.maxRentalDays) - // Rules cannot loop over the range: only its first and last days must be on offer. + // The days booked, as LocalDate epoch days. They need not follow each other. Every one + // must be on offer, once: so there are at most as many as the listing offers (366). + && data.days is list && data.days.size() > 0 + && data.days.toSet().size() == data.days.size() && 'availableDates' in listing - && data.startDate in listing.availableDates - && data.endDate in listing.availableDates + && listing.availableDates.hasAll(data.days) + // Every day counts. A listing without maxRentalDays has no limit. + && (!('maxRentalDays' in listing) || data.days.size() <= listing.maxRentalDays) + // Rules cannot loop over the days, so only the first is checked against server time + // (not the client clock). The app sends them earliest first; a modified client could + // still add a past day the listing offers (#346). + && data.days[0] is int + && data.days[0] >= request.time.toMillis() / 86400000 && data.status == 'REQUESTED'; } diff --git a/rules-tests/firestore.test.js b/rules-tests/firestore.test.js index 3a245f3b..af14e8ca 100644 --- a/rules-tests/firestore.test.js +++ b/rules-tests/firestore.test.js @@ -328,15 +328,11 @@ describe("listings", () => { describe("bookings", () => { // First booked day, 30 days from now, so these tests never book a day in the past. const day0 = Math.floor(Date.now() / 86_400_000) + 30; - // Epoch-day bounds of java.time.LocalDate, the same as in validBooking. - const MIN_EPOCH_DAY = -365243219162; - const MAX_EPOCH_DAY = 365241780471; const booking = (overrides = {}) => ({ listingId: "l1", renterUid: BOB, lenderUid: ALICE, - startDate: day0, - endDate: day0 + 2, + days: [day0, day0 + 1, day0 + 2], status: "REQUESTED", ...overrides, }); @@ -360,10 +356,24 @@ describe("listings", () => { await assertFails(setDoc(doc(db, "bookings/b3"), booking({ listingId: "missing" }))); }); - test("a booking cannot be longer than the listing's maximum rental", async () => { - await seed("listings/l1", offering(days(day0, day0 + 3), { type: "ITEM", maxRentalDays: 3 })); - await assertSucceeds(setDoc(doc(verified(BOB), "bookings/b1"), booking({ startDate: day0, endDate: day0 + 2 }))); - await assertFails(setDoc(doc(verified(BOB), "bookings/b2"), booking({ startDate: day0, endDate: day0 + 3 }))); + test("separate days can be booked together", async () => { + await seed("listings/l1", offering([day0, day0 + 3, ...days(day0 + 7, day0 + 9)])); + await assertSucceeds( + setDoc(doc(verified(BOB), "bookings/b1"), booking({ days: [day0, day0 + 3, day0 + 7, day0 + 8, day0 + 9] })), + ); + }); + + test("every booked day counts towards the listing's maximum rental", async () => { + await seed("listings/l1", offering(days(day0, day0 + 9), { type: "ITEM", maxRentalDays: 3 })); + const db = verified(BOB); + await assertSucceeds(setDoc(doc(db, "bookings/b1"), booking({ days: [day0, day0 + 4, day0 + 9] }))); + // Four separate days, none of them next to another, are still four days. + await assertFails(setDoc(doc(db, "bookings/b2"), booking({ days: [day0, day0 + 3, day0 + 6, day0 + 9] }))); + }); + + test("a listing without maxRentalDays has no limit", async () => { + await seed("listings/l1", offering(days(day0, day0 + 9))); + await assertSucceeds(setDoc(doc(verified(BOB), "bookings/b1"), booking({ days: days(day0, day0 + 9) }))); }); test("a paused listing cannot be booked", async () => { @@ -378,40 +388,33 @@ describe("listings", () => { ); }); - test("bookings have valid dates, requested status and no extra fields", async () => { + test("bookings have valid days, requested status and no extra fields", async () => { const today = Math.floor(Date.now() / 86_400_000); - // Every day used below is offered, so each refusal comes from the date checks. - await seed( - "listings/l1", - offering([MIN_EPOCH_DAY - 1, today - 1, today, ...days(day0 - 1, day0 + 2), MAX_EPOCH_DAY + 1]), - ); + // Every day used below is offered, so each refusal comes from the checks on the booking. + await seed("listings/l1", offering([today - 1, today, ...days(day0, day0 + 2)])); const db = verified(BOB); - await assertSucceeds(setDoc(doc(db, "bookings/same-day"), booking({ endDate: day0 }))); - await assertFails(setDoc(doc(db, "bookings/b1"), booking({ endDate: day0 - 1 }))); - await assertFails(setDoc(doc(db, "bookings/b2"), booking({ startDate: String(day0) }))); - await assertFails(setDoc(doc(db, "bookings/b3"), booking({ endDate: MAX_EPOCH_DAY + 1 }))); - await assertFails(setDoc(doc(db, "bookings/b4"), booking({ startDate: MIN_EPOCH_DAY - 1 }))); - await assertFails(setDoc(doc(db, "bookings/b5"), booking({ status: "CONFIRMED" }))); - await assertFails(setDoc(doc(db, "bookings/b6"), booking({ extra: true }))); - await assertFails(setDoc(doc(db, "bookings/past"), booking({ startDate: today - 1, endDate: today }))); - await assertSucceeds(setDoc(doc(db, "bookings/today"), booking({ startDate: today, endDate: today }))); + await assertSucceeds(setDoc(doc(db, "bookings/one-day"), booking({ days: [day0] }))); + await assertSucceeds(setDoc(doc(db, "bookings/today"), booking({ days: [today, day0] }))); + await assertFails(setDoc(doc(db, "bookings/empty"), booking({ days: [] }))); + await assertFails(setDoc(doc(db, "bookings/not-a-list"), booking({ days: day0 }))); + await assertFails(setDoc(doc(db, "bookings/twice"), booking({ days: [day0, day0] }))); + await assertFails(setDoc(doc(db, "bookings/string"), booking({ days: [String(day0)] }))); + await assertFails(setDoc(doc(db, "bookings/past"), booking({ days: [today - 1, today] }))); + const { days: _, ...withoutDays } = booking(); + await assertFails(setDoc(doc(db, "bookings/missing"), withoutDays)); + // The first and last day of earlier versions are no longer accepted. + await assertFails(setDoc(doc(db, "bookings/old-shape"), { ...withoutDays, startDate: day0, endDate: day0 })); + await assertFails(setDoc(doc(db, "bookings/status"), booking({ status: "CONFIRMED" }))); + await assertFails(setDoc(doc(db, "bookings/extra"), booking({ extra: true }))); }); - test("a booking whose first and last days are offered is allowed", async () => { - await seed("listings/l1", offering(days(day0, day0 + 2))); + test("a booking with any day the listing does not offer is refused", async () => { + await seed("listings/l1", offering([day0, day0 + 2, day0 + 4])); const db = verified(BOB); - await assertSucceeds(setDoc(doc(db, "bookings/b1"), booking({ startDate: day0, endDate: day0 + 2 }))); - await assertSucceeds(setDoc(doc(db, "bookings/one-day"), booking({ startDate: day0 + 1, endDate: day0 + 1 }))); - }); - - test("a booking whose first day is not offered is refused", async () => { - await seed("listings/l1", offering(days(day0 + 1, day0 + 2))); - await assertFails(setDoc(doc(verified(BOB), "bookings/b1"), booking({ startDate: day0, endDate: day0 + 2 }))); - }); - - test("a booking whose last day is not offered is refused", async () => { - await seed("listings/l1", offering(days(day0, day0 + 1))); - await assertFails(setDoc(doc(verified(BOB), "bookings/b1"), booking({ startDate: day0, endDate: day0 + 2 }))); + await assertSucceeds(setDoc(doc(db, "bookings/b1"), booking({ days: [day0, day0 + 2, day0 + 4] }))); + // A day in the middle, not only the first or last, is checked. + await assertFails(setDoc(doc(db, "bookings/b2"), booking({ days: [day0, day0 + 1, day0 + 2] }))); + await assertFails(setDoc(doc(db, "bookings/b3"), booking({ days: [day0 + 1] }))); }); test("a listing without available days cannot be booked", async () => { @@ -424,10 +427,12 @@ describe("listings", () => { await assertFails(setDoc(doc(verified(BOB), "bookings/b1"), booking())); }); - test("only the first and last days are checked, so a gap in between is allowed", async () => { - // Known limit: rules cannot loop over the range. The renter's screen only offers available days. - await seed("listings/l1", offering([day0, day0 + 2])); - await assertSucceeds(setDoc(doc(verified(BOB), "bookings/b1"), booking({ startDate: day0, endDate: day0 + 2 }))); + test("only the first day is checked against today, so a later past day the listing offers is allowed", async () => { + // Known limit (#346): rules cannot loop over the days. The app sends them earliest first and + // never offers a past day. + const today = Math.floor(Date.now() / 86_400_000); + await seed("listings/l1", offering([today - 1, day0])); + await assertSucceeds(setDoc(doc(verified(BOB), "bookings/b1"), booking({ days: [day0, today - 1] }))); }); test("verified lenders and renters can read their own bookings", async () => { From 7abcf66fac091a038d6976da5e78b0e4d8eda176 Mon Sep 17 00:00:00 2001 From: Lucas Christiansson <98053131+madebylucke@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:41:24 +0100 Subject: [PATCH 2/2] fix(booking): rethrow an out-of-range booking day as IllegalStateException Also say in the rules why a booking has at most 366 days. --- .../booking/model/FirebaseBookingRepository.kt | 11 ++++++++--- .../booking/model/FirebaseBookingRepositoryTest.kt | 6 ++++++ firestore.rules | 3 ++- 3 files changed, 16 insertions(+), 4 deletions(-) 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 cd4354b0..c7669be8 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 @@ -8,6 +8,7 @@ import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException +import java.time.DateTimeException import java.time.LocalDate import java.util.concurrent.Executor import kotlinx.coroutines.tasks.await @@ -76,9 +77,13 @@ class FirebaseBookingRepository( (get(DAYS) as? List<*>)?.takeIf { it.isNotEmpty() } ?: throw IllegalStateException("Booking $id is missing $DAYS") return epochDays.mapTo(mutableSetOf()) { - LocalDate.ofEpochDay( - (it as? Long) ?: throw IllegalStateException("Booking $id has an invalid day: $it") - ) + val epochDay = + it as? Long ?: throw IllegalStateException("Booking $id has an invalid day: $it") + try { + LocalDate.ofEpochDay(epochDay) + } catch (e: DateTimeException) { + throw IllegalStateException("Booking $id has an invalid day: $it", e) + } } } 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 f64da47b..9797aadc 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 @@ -190,6 +190,12 @@ class FirebaseBookingRepositoryTest { runCatching { repository.getBookingsForListing("listing") }.exceptionOrNull() is IllegalStateException ) + // Out of LocalDate's range: ofEpochDay throws DateTimeException, rethrown as above. + whenever(stored.get("days")).thenReturn(listOf(Long.MAX_VALUE)) + assertTrue( + runCatching { repository.getBookingsForListing("listing") }.exceptionOrNull() + is IllegalStateException + ) } @Test diff --git a/firestore.rules b/firestore.rules index 5e94610d..d958b011 100644 --- a/firestore.rules +++ b/firestore.rules @@ -103,7 +103,8 @@ service cloud.firestore { && listing.paused == false && data.renterUid != data.lenderUid // The days booked, as LocalDate epoch days. They need not follow each other. Every one - // must be on offer, once: so there are at most as many as the listing offers (366). + // must be on offer, once: hasAll plus no duplicates bounds the size by the listing's + // availableDates, which are at most 366. && data.days is list && data.days.size() > 0 && data.days.toSet().size() == data.days.size() && 'availableDates' in listing