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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -16,17 +17,16 @@ 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.
*/
data class Booking(
val listingId: String,
val renterUid: String,
val lenderUid: String,
val startDate: LocalDate,
val endDate: LocalDate,
val days: Set<LocalDate>,
val status: BookingStatus = BookingStatus.REQUESTED,
val id: String = "",
)
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
// 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
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
Expand All @@ -30,7 +32,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()
Expand All @@ -39,8 +41,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,
)
)
Expand Down Expand Up @@ -70,19 +72,33 @@ 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 =
LocalDate.ofEpochDay(
getLong(field) ?: throw IllegalStateException("Booking $id is missing $field")
)
fun days(): Set<LocalDate> {
val epochDays =
(get(DAYS) as? List<*>)?.takeIf { it.isNotEmpty() }
?: throw IllegalStateException("Booking $id is missing $DAYS")
return epochDays.mapTo(mutableSetOf()) {
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)
}
}
}

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"
}
}
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
// 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
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
Expand All @@ -16,29 +15,13 @@ 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
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<LocalDate>, selection: Set<LocalDate>): Set<LocalDate> {
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).
*
Expand All @@ -50,7 +33,8 @@ internal fun singlePeriod(previous: Set<LocalDate>, selection: Set<LocalDate>):
* 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.
Expand All @@ -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,
)
}
}
Expand Down Expand Up @@ -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<LocalDate>) {
_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) {
Expand All @@ -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,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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",
)
)
Expand Down Expand Up @@ -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(
Expand All @@ -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")

Expand All @@ -158,6 +162,42 @@ class FirebaseBookingRepositoryTest {
)
}

@Test
fun getBookingsRejectsABookingWithoutDaysOrWithAnInvalidDay() = runTest {
val lender = mock<FirebaseUser>()
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<Long>())
assertTrue(
runCatching { repository.getBookingsForListing("listing") }.exceptionOrNull()
is IllegalStateException
)
whenever(stored.get("days")).thenReturn(listOf("20000"))
assertTrue(
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
fun getBookingsRejectsSignedOutUser() = runTest {
whenever(auth.currentUser).thenReturn(null)
Expand Down
Loading
Loading