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/main/java/com/android/polybazaar/booking/ui/ReceivedRequestsScreen.kt b/app/src/main/java/com/android/polybazaar/booking/ui/ReceivedRequestsScreen.kt new file mode 100644 index 00000000..6bfe62b6 --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/booking/ui/ReceivedRequestsScreen.kt @@ -0,0 +1,406 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.booking.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.android.polybazaar.R +import com.android.polybazaar.auth.ui.AuthBackButton +import com.android.polybazaar.auth.ui.AuthColors +import com.android.polybazaar.auth.ui.AuthPrimaryButton +import com.android.polybazaar.booking.model.Booking +import com.android.polybazaar.booking.model.BookingStatus +import com.android.polybazaar.booking.model.formatRuns +import com.android.polybazaar.booking.model.groupIntoRuns +import com.android.polybazaar.booking.viewmodel.ReceivedRequestsUiState +import com.android.polybazaar.booking.viewmodel.ReceivedRequestsViewModel +import com.android.polybazaar.error.ui.message +import java.time.LocalDate + +object ReceivedRequestsScreenTags { + const val SCREEN = "received_requests_screen" + const val BACK_BUTTON = "received_requests_back_button" + const val LOADING_INDICATOR = "received_requests_loading_indicator" + const val ERROR_MESSAGE = "received_requests_error_message" + const val RETRY_BUTTON = "received_requests_retry_button" + const val EMPTY_MESSAGE = "received_requests_empty_message" + const val ACCEPT_ERROR = "received_requests_accept_error" + const val ACCEPT_DIALOG = "received_requests_accept_dialog" + const val ACCEPT_DIALOG_TEXT = "received_requests_accept_dialog_text" + const val ACCEPT_CONFIRM = "received_requests_accept_confirm" + const val ACCEPT_CANCEL = "received_requests_accept_cancel" + + /** The card of the waiting request with this id. */ + fun request(id: String) = "received_requests_request_$id" + + /** The "Accept" button of the waiting request with this id. */ + fun acceptButton(id: String) = "received_requests_accept_$id" + + /** The card of the accepted booking with this id. */ + fun accepted(id: String) = "received_requests_accepted_$id" +} + +/** What the screen can do; every action does nothing by default. */ +class ReceivedRequestsActions( + val onBack: () -> Unit = {}, + val onRetry: () -> Unit = {}, + val onAccept: (Booking) -> Unit = {}, +) + +/** + * The screen where the owner of a listing sees the requests renters made on it and accepts the ones + * they want. Accepting asks for confirmation first, saying how many other requests for the same + * days it cancels. + */ +@Composable +fun ReceivedRequestsScreen(viewModel: ReceivedRequestsViewModel, onBack: () -> Unit) { + val uiState by viewModel.uiState.collectAsState() + ReceivedRequestsContent( + uiState = uiState, + actions = + ReceivedRequestsActions( + onBack = onBack, + onRetry = viewModel::loadRequests, + onAccept = viewModel::accept, + ), + ) +} + +/** Side margin of the page, as on the listing detail. */ +private val PageMargin = 18.dp + +@Composable +fun ReceivedRequestsContent(uiState: ReceivedRequestsUiState, actions: ReceivedRequestsActions) { + Column( + modifier = + Modifier.fillMaxSize() + .background(AuthColors.Background) + .safeDrawingPadding() + .testTag(ReceivedRequestsScreenTags.SCREEN) + ) { + AuthBackButton( + onClick = actions.onBack, + modifier = + Modifier.padding(start = 20.dp, top = 6.dp) + .testTag(ReceivedRequestsScreenTags.BACK_BUTTON), + ) + val error = uiState.error + when { + // Requests already shown stay shown if reading them again fails. + uiState.hasLoaded -> RequestLists(uiState, actions) + error != null -> LoadError(text = error.message(), onRetry = actions.onRetry) + else -> LoadingIndicator() + } + } +} + +@Composable +private fun RequestLists(uiState: ReceivedRequestsUiState, actions: ReceivedRequestsActions) { + // The id of the request waiting for confirmation. Saveable, so the dialog survives a rotation. + var confirmingId by rememberSaveable { mutableStateOf(null) } + Column( + modifier = + Modifier.fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = PageMargin, vertical = 16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Text( + text = stringResource(R.string.received_requests_title), + color = AuthColors.TextPrimary, + fontSize = 22.sp, + fontWeight = FontWeight.Bold, + ) + uiState.acceptError?.let { + Text( + text = it.message(), + color = AuthColors.Danger, + fontSize = 13.sp, + lineHeight = 18.sp, + modifier = Modifier.testTag(ReceivedRequestsScreenTags.ACCEPT_ERROR), + ) + } + if (uiState.requests.isEmpty() && uiState.accepted.isEmpty()) { + Text( + text = stringResource(R.string.received_requests_empty), + color = AuthColors.TextSecondary, + fontSize = 13.sp, + modifier = Modifier.testTag(ReceivedRequestsScreenTags.EMPTY_MESSAGE), + ) + } + if (uiState.requests.isNotEmpty()) { + SectionTitle(stringResource(R.string.received_requests_waiting)) + uiState.requests.forEach { request -> + RequestCard( + booking = request, + renterName = uiState.renterNames[request.renterUid], + tag = ReceivedRequestsScreenTags.request(request.id), + ) { + AuthPrimaryButton( + text = stringResource(R.string.received_requests_accept), + onClick = { confirmingId = request.id }, + enabled = uiState.acceptingId == null && !uiState.isLoading, + modifier = + Modifier.fillMaxWidth() + .height(44.dp) + .testTag(ReceivedRequestsScreenTags.acceptButton(request.id)), + ) + } + } + } + if (uiState.accepted.isNotEmpty()) { + SectionTitle(stringResource(R.string.received_requests_accepted)) + uiState.accepted.forEach { booking -> + RequestCard( + booking = booking, + renterName = uiState.renterNames[booking.renterUid], + tag = ReceivedRequestsScreenTags.accepted(booking.id), + ) + } + } + } + // Looked up again on every change: the request may have been answered meanwhile. + val confirming = uiState.requests.find { it.id == confirmingId } + if (confirming != null) { + AcceptDialog( + renterName = uiState.renterNames[confirming.renterUid], + days = formatRuns(groupIntoRuns(confirming.days)), + conflicts = uiState.conflictsOf(confirming).size, + onConfirm = { + confirmingId = null + actions.onAccept(confirming) + }, + onDismiss = { confirmingId = null }, + ) + } +} + +@Composable +private fun SectionTitle(text: String) { + Text( + text = text, + color = AuthColors.TextPrimary, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + ) +} + +/** + * One booking: who asked, for which days and how many. [actions] adds what the lender can do with + * it below. + */ +@Composable +private fun RequestCard( + booking: Booking, + renterName: String?, + tag: String, + actions: @Composable () -> Unit = {}, +) { + val shape = RoundedCornerShape(14.dp) + Column( + modifier = + Modifier.fillMaxWidth() + .background(AuthColors.CardBackground, shape) + .border(1.dp, AuthColors.Outline, shape) + .padding(12.dp) + .testTag(tag), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + text = renterName ?: stringResource(R.string.received_requests_unknown_renter), + color = AuthColors.TextPrimary, + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + ) + Text( + text = formatRuns(groupIntoRuns(booking.days)), + color = AuthColors.TextPrimary, + fontSize = 13.sp, + ) + Text( + text = + pluralStringResource( + R.plurals.received_requests_day_count, + booking.days.size, + booking.days.size, + ), + color = AuthColors.TextSecondary, + fontSize = 12.sp, + lineHeight = 17.sp, + ) + actions() + } +} + +/** + * Asks the lender to confirm the accept, which cannot be undone and cancels the [conflicts] other + * requests for the same days. + */ +@Composable +private fun AcceptDialog( + renterName: String?, + days: String, + conflicts: Int, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + val renter = renterName ?: stringResource(R.string.received_requests_unknown_renter) + val text = buildString { + append(stringResource(R.string.received_requests_confirm_text, renter, days)) + if (conflicts > 0) { + append(" ") + append( + pluralStringResource(R.plurals.received_requests_confirm_cancels, conflicts, conflicts) + ) + } + } + AlertDialog( + onDismissRequest = onDismiss, + containerColor = AuthColors.CardBackground, + shape = RoundedCornerShape(20.dp), + modifier = Modifier.testTag(ReceivedRequestsScreenTags.ACCEPT_DIALOG), + title = { + Text( + text = stringResource(R.string.received_requests_confirm_title), + color = AuthColors.TextPrimary, + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + ) + }, + text = { + Text( + text = text, + color = AuthColors.TextSecondary, + fontSize = 13.sp, + lineHeight = 18.sp, + modifier = Modifier.testTag(ReceivedRequestsScreenTags.ACCEPT_DIALOG_TEXT), + ) + }, + confirmButton = { + TextButton( + onClick = onConfirm, + modifier = Modifier.testTag(ReceivedRequestsScreenTags.ACCEPT_CONFIRM), + ) { + Text( + text = stringResource(R.string.received_requests_accept), + color = AuthColors.Accent, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + ) + } + }, + dismissButton = { + TextButton( + onClick = onDismiss, + modifier = Modifier.testTag(ReceivedRequestsScreenTags.ACCEPT_CANCEL), + ) { + Text( + text = stringResource(R.string.received_requests_cancel), + color = AuthColors.TextSecondary, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + ) + } + }, + ) +} + +@Composable +private fun LoadingIndicator() { + Box( + modifier = Modifier.fillMaxWidth().padding(vertical = 24.dp), + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator( + color = AuthColors.Accent, + modifier = Modifier.size(32.dp).testTag(ReceivedRequestsScreenTags.LOADING_INDICATOR), + ) + } +} + +/** Why the requests could not be read, with Retry. */ +@Composable +private fun LoadError(text: String, onRetry: () -> Unit) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = PageMargin, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = text, + color = AuthColors.Danger, + fontSize = 14.sp, + modifier = Modifier.weight(1f).testTag(ReceivedRequestsScreenTags.ERROR_MESSAGE), + ) + TextButton( + onClick = onRetry, + modifier = Modifier.testTag(ReceivedRequestsScreenTags.RETRY_BUTTON), + ) { + Text( + text = stringResource(R.string.booking_request_retry), + color = AuthColors.Accent, + fontWeight = FontWeight.Bold, + ) + } + } +} + +/** Two requests sharing a day and one accepted booking, for the IDE preview. */ +@Preview(showBackground = true, widthDp = 412, heightDp = 917) +@Composable +private fun ReceivedRequestsContentPreview() { + val first = LocalDate.of(2026, 11, 23) + fun booking(id: String, renter: String, days: IntRange, status: BookingStatus) = + Booking( + listingId = "preview", + renterUid = renter, + lenderUid = "lender", + days = days.mapTo(mutableSetOf()) { first.plusDays(it.toLong()) }, + status = status, + id = id, + ) + ReceivedRequestsContent( + uiState = + ReceivedRequestsUiState( + requests = + listOf( + booking("b1", "alice", 0..2, BookingStatus.REQUESTED), + booking("b2", "bob", 2..3, BookingStatus.REQUESTED), + ), + accepted = listOf(booking("b3", "carol", 7..8, BookingStatus.CONFIRMED)), + renterNames = mapOf("alice" to "alice_m", "bob" to "bob.k", "carol" to "carol"), + hasLoaded = true, + ), + actions = ReceivedRequestsActions(), + ) +} 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/main/java/com/android/polybazaar/listing/ui/ListingDetailOwnerParts.kt b/app/src/main/java/com/android/polybazaar/listing/ui/ListingDetailOwnerParts.kt index 0112109a..95ca4fad 100644 --- a/app/src/main/java/com/android/polybazaar/listing/ui/ListingDetailOwnerParts.kt +++ b/app/src/main/java/com/android/polybazaar/listing/ui/ListingDetailOwnerParts.kt @@ -13,9 +13,11 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -183,6 +185,38 @@ internal fun DeleteListingDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { ) } +/** + * Opens the requests renters made on the listing, where the owner accepts the ones they want. + * Styled like the renter's "Message lender". + */ +@Composable +internal fun BookingRequestsButton(onClick: () -> Unit) { + OutlinedButton( + onClick = onClick, + modifier = Modifier.fillMaxWidth().testTag(ListingDetailScreenTags.BOOKING_REQUESTS_BUTTON), + shape = RoundedCornerShape(10.dp), + border = BorderStroke(1.dp, AuthColors.Outline), + colors = + ButtonDefaults.outlinedButtonColors( + containerColor = AuthColors.CardBackground, + contentColor = AuthColors.Accent, + ), + ) { + // Decorative: the text says what the button does. + Icon( + painter = painterResource(R.drawable.ic_calendar), + contentDescription = null, + modifier = Modifier.size(17.dp), + ) + Text( + text = stringResource(R.string.listing_detail_booking_requests), + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.padding(start = 8.dp), + ) + } +} + /** * The "Paused" pill, next to the condition badge and with its size. The Toolbox shows it on paused * rows too. diff --git a/app/src/main/java/com/android/polybazaar/listing/ui/ListingDetailScreen.kt b/app/src/main/java/com/android/polybazaar/listing/ui/ListingDetailScreen.kt index 4e5e11b5..38c7f378 100644 --- a/app/src/main/java/com/android/polybazaar/listing/ui/ListingDetailScreen.kt +++ b/app/src/main/java/com/android/polybazaar/listing/ui/ListingDetailScreen.kt @@ -92,6 +92,7 @@ object ListingDetailScreenTags { const val CHOOSE_DATES_BUTTON = "listing_detail_choose_dates_button" const val BOOKING_NOTE = "listing_detail_booking_note" const val EDIT_BUTTON = "listing_detail_edit_button" + const val BOOKING_REQUESTS_BUTTON = "listing_detail_booking_requests_button" const val OWNER_MENU_BUTTON = "listing_detail_owner_menu_button" const val PAUSE_ITEM = "listing_detail_pause_item" const val RESUME_ITEM = "listing_detail_resume_item" @@ -114,6 +115,7 @@ object ListingDetailScreenTags { * not here: they stay inside the screen, so [ListingDetailScreen] wires them to the ViewModel. * * @property onEdit opens the "Edit listing" screen for the listing with this id (owner only). + * @property onOpenRequests opens the booking requests on the listing with this id (owner only). * @property onDeleted leaves the screen once the owner deleted the listing. */ class ListingDetailActions( @@ -122,6 +124,7 @@ class ListingDetailActions( val onMessageLender: () -> Unit = {}, val onChooseDates: () -> Unit = {}, val onEdit: (String) -> Unit = {}, + val onOpenRequests: (String) -> Unit = {}, val onDeleted: () -> Unit = {}, ) @@ -255,6 +258,12 @@ private fun ColumnScope.ListingDetail( ) { Overview(listing, uiState.pendingDetails) if (listing.isPaused) PausedNotice(text = pausedNoticeText(uiState.isOwner)) + // Saved listings always have an id. Still shown while paused: requests made before the + // pause can still be accepted. + val listingId = listing.listingId + if (uiState.isOwner && listingId != null) { + BookingRequestsButton(onClick = { actions.onOpenRequests(listingId) }) + } DescriptionSection(listing, uiState.pendingDetails) TermsSection(listing, uiState.pendingDetails) LenderSection(listing, uiState, actions, onRetry) diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index a9b25926..019a6b6b 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -58,8 +58,10 @@ import com.android.polybazaar.auth.viewmodel.ForgotPasswordViewModel import com.android.polybazaar.auth.viewmodel.VerifyEmailViewModel import com.android.polybazaar.booking.model.BookingRepository import com.android.polybazaar.booking.ui.BookingRequestScreen +import com.android.polybazaar.booking.ui.ReceivedRequestsScreen import com.android.polybazaar.booking.viewmodel.BookingRequestViewModel import com.android.polybazaar.booking.viewmodel.BookingViewModel +import com.android.polybazaar.booking.viewmodel.ReceivedRequestsViewModel import com.android.polybazaar.browse.ui.BrowseScreen import com.android.polybazaar.browse.viewmodel.BrowseViewModel import com.android.polybazaar.chat.model.ChatRepository @@ -109,7 +111,8 @@ object AppNavHostTags { * Pass the repository [authViewModel] uses, so every auth screen talks to the same backend. * @param listingRepository gives the Browse screen the listings to show, and saves new ones. * @param chatRepository gives the Conversations screen the signed-in user's conversations. - * @param bookingRepository sends the booking requests made from a listing's "Choose dates". + * @param bookingRepository sends the booking requests made from a listing's "Choose dates", and + * gives a listing's owner the requests on it to accept. * @param photoStorage keeps the photos of the listing being created. * @param editPhotoStorage keeps the photos added to the listing being edited. It must use another * folder than [photoStorage]: opening a form deletes the photos its folder holds for other forms. @@ -366,6 +369,11 @@ fun AppNavHost( navController.navigate(Routes.editListing(it)) { launchSingleTop = true } }, onDeleted = { navController.popBackStack() }, + onOpenRequests = { + navController.navigate(Routes.receivedRequests(it)) { + launchSingleTop = true + } + }, // The viewer messages the owner as the renter. Single top, so a double tap // does not stack two conversation screens. onMessageLender = { @@ -415,6 +423,30 @@ fun AppNavHost( onBack = dropUnlessResumed { navController.popBackStack() }, ) } + composable( + route = Routes.RECEIVED_REQUESTS, + arguments = listOf(navArgument(Routes.LISTING_ID) { type = NavType.StringType }), + ) { entry -> + val listingId = entry.arguments?.getString(Routes.LISTING_ID) ?: return@composable + val requestsViewModel: ReceivedRequestsViewModel = + viewModel( + factory = + viewModelFactory { + initializer { + ReceivedRequestsViewModel( + listingId = listingId, + bookingRepository = bookingRepository, + profileRepository = profileRepository, + ) + } + } + ) + ReceivedRequestsScreen( + viewModel = requestsViewModel, + // As on the booking request: a second tap while leaving would also pop the listing. + onBack = dropUnlessResumed { navController.popBackStack() }, + ) + } composable( route = Routes.LENDER_PROFILE, arguments = listOf(navArgument(Routes.LENDER_UID) { type = NavType.StringType }), @@ -617,6 +649,7 @@ private val signedInRoutes = Routes.INBOX, Routes.CONVERSATION, Routes.BOOKING_REQUEST, + Routes.RECEIVED_REQUESTS, Routes.PROFILE, Routes.EDIT_PROFILE, Routes.SETTINGS, diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/Routes.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/Routes.kt index 6fad198e..a39e3674 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/Routes.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/Routes.kt @@ -26,6 +26,7 @@ object Routes { const val RENTER_UID = "renterUid" const val CONVERSATION = "conversation/{$LISTING_ID}/{$RENTER_UID}" const val BOOKING_REQUEST = "booking_request/{$LISTING_ID}" + const val RECEIVED_REQUESTS = "received_requests/{$LISTING_ID}" /** The route of the "Edit listing" screen for the listing [listingId]. */ fun editListing(listingId: String) = "edit_listing/${Uri.encode(listingId)}" @@ -45,4 +46,7 @@ object Routes { /** The route of the screen where a renter requests the listing [listingId] for some days. */ fun bookingRequest(listingId: String) = "booking_request/${Uri.encode(listingId)}" + + /** The route of the booking requests renters made on the listing [listingId], for its owner. */ + fun receivedRequests(listingId: String) = "received_requests/${Uri.encode(listingId)}" } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ac2de988..dfa6e9fc 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -235,4 +235,24 @@ You asked for %1$s. The lender still has to accept it. Done Retry + + + Booking requests + Booking requests + No one has requested this listing yet. + Waiting for your answer + Accepted + A renter + + %1$d day + %1$d days + + Accept + Cancel + Accept this request? + %1$s gets %2$s. No one else can request these days. + + %1$d other request for these days will be cancelled. + %1$d other requests for these days will be cancelled. + 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..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 @@ -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 @@ -10,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 @@ -29,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 @@ -39,7 +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 } + } + + 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/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/app/src/test/java/com/android/polybazaar/booking/ui/ReceivedRequestsScreenTest.kt b/app/src/test/java/com/android/polybazaar/booking/ui/ReceivedRequestsScreenTest.kt new file mode 100644 index 00000000..039a35e7 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/booking/ui/ReceivedRequestsScreenTest.kt @@ -0,0 +1,188 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.booking.ui + +import android.content.Context +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.hasTestTag +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.polybazaar.R +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.booking.viewmodel.ReceivedRequestsUiState +import com.android.polybazaar.booking.viewmodel.ReceivedRequestsViewModel +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.profile.model.FakeProfileRepository +import java.time.LocalDate +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class ReceivedRequestsScreenTest { + + @get:Rule val composeTestRule = createComposeRule() + + private val context: Context = ApplicationProvider.getApplicationContext() + + 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, + ) = Booking("drill", renter, "lender", days, status, id) + + // Bob's request shares the 21st with Ann's. + 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(28..28), BookingStatus.CONFIRMED) + + private val loaded = + ReceivedRequestsUiState( + requests = listOf(ann, bob), + accepted = listOf(cy), + renterNames = mapOf("uid-ann" to "ann_m", "uid-cy" to "cy"), + hasLoaded = true, + ) + + private fun setContent( + uiState: ReceivedRequestsUiState, + actions: ReceivedRequestsActions = ReceivedRequestsActions(), + ) { + composeTestRule.setContent { ReceivedRequestsContent(uiState = uiState, actions = actions) } + } + + private fun node(tag: String) = composeTestRule.onNodeWithTag(tag) + + /** The text [text] inside the card tagged [tag]. */ + private fun card(tag: String, text: String) = + composeTestRule.onNode( + hasText(text) and hasAnyAncestor(hasTestTag(tag)), + useUnmergedTree = true, + ) + + @Test + fun beforeTheFirstLoad_showsTheIndicator() { + setContent(ReceivedRequestsUiState(isLoading = true)) + + node(ReceivedRequestsScreenTags.LOADING_INDICATOR).assertIsDisplayed() + } + + @Test + fun aLoadError_isShown_withRetry() { + var retries = 0 + setContent( + ReceivedRequestsUiState(error = AppError.NETWORK), + ReceivedRequestsActions(onRetry = { retries++ }), + ) + + node(ReceivedRequestsScreenTags.ERROR_MESSAGE) + .assertTextEquals(context.getString(R.string.error_network)) + node(ReceivedRequestsScreenTags.RETRY_BUTTON).performClick() + assertEquals(1, retries) + } + + @Test + fun noBookings_saysSo() { + setContent(ReceivedRequestsUiState(hasLoaded = true)) + + node(ReceivedRequestsScreenTags.EMPTY_MESSAGE).assertIsDisplayed() + } + + @Test + fun showsEachRequest_withItsRenterAndDays() { + setContent(loaded) + + val annCard = ReceivedRequestsScreenTags.request("ann") + card(annCard, "ann_m").assertIsDisplayed() + card(annCard, "20–21 Nov").assertIsDisplayed() + card(annCard, "2 days").assertIsDisplayed() + // Bob has no name read: shown as a renter. + card(ReceivedRequestsScreenTags.request("bob"), "A renter").assertIsDisplayed() + val cyCard = ReceivedRequestsScreenTags.accepted("cy") + card(cyCard, "cy").assertIsDisplayed() + card(cyCard, "28 Nov").assertIsDisplayed() + node(ReceivedRequestsScreenTags.acceptButton("cy")).assertDoesNotExist() + node(ReceivedRequestsScreenTags.EMPTY_MESSAGE).assertDoesNotExist() + } + + @Test + fun accept_asksFirst_sayingWhatItCancels() { + val accepted = mutableListOf() + setContent(loaded, ReceivedRequestsActions(onAccept = { accepted += it })) + + node(ReceivedRequestsScreenTags.acceptButton("ann")).performClick() + + node(ReceivedRequestsScreenTags.ACCEPT_DIALOG_TEXT) + .assertTextEquals( + "ann_m gets 20–21 Nov. No one else can request these days. " + + "1 other request for these days will be cancelled." + ) + assertEquals(emptyList(), accepted) + node(ReceivedRequestsScreenTags.ACCEPT_CONFIRM).performClick() + + node(ReceivedRequestsScreenTags.ACCEPT_DIALOG).assertDoesNotExist() + assertEquals(listOf(ann), accepted) + } + + @Test + fun cancellingTheDialog_acceptsNothing() { + val accepted = mutableListOf() + setContent( + loaded.copy(requests = listOf(ann)), + ReceivedRequestsActions(onAccept = { accepted += it }), + ) + + node(ReceivedRequestsScreenTags.acceptButton("ann")).performClick() + node(ReceivedRequestsScreenTags.ACCEPT_DIALOG_TEXT) + .assertTextEquals("ann_m gets 20–21 Nov. No one else can request these days.") + node(ReceivedRequestsScreenTags.ACCEPT_CANCEL).performClick() + + node(ReceivedRequestsScreenTags.ACCEPT_DIALOG).assertDoesNotExist() + assertEquals(emptyList(), accepted) + } + + @Test + fun whileAnAcceptRuns_theButtonsAreDisabled_andAFailureIsShown() { + setContent(loaded.copy(acceptingId = "ann", acceptError = AppError.NETWORK)) + + node(ReceivedRequestsScreenTags.acceptButton("ann")).assertIsNotEnabled() + node(ReceivedRequestsScreenTags.acceptButton("bob")).assertIsNotEnabled() + node(ReceivedRequestsScreenTags.ACCEPT_ERROR) + .assertTextEquals(context.getString(R.string.error_network)) + } + + @Test + fun withTheViewModel_acceptingMovesTheRequest_andRemovesTheOverlappingOne() { + val bookings = FakeBookingRepository(listOf(ann, bob)) + val profiles = + FakeProfileRepository( + mapOf("uid-ann" to User(uid = "uid-ann", email = "", username = "ann_m")) + ) + val viewModel = + ReceivedRequestsViewModel("drill", bookings, profiles, LocalDate.of(2026, 11, 18)) + composeTestRule.setContent { ReceivedRequestsScreen(viewModel = viewModel, onBack = {}) } + + node(ReceivedRequestsScreenTags.acceptButton("ann")).assertIsEnabled().performClick() + node(ReceivedRequestsScreenTags.ACCEPT_CONFIRM).performClick() + + node(ReceivedRequestsScreenTags.accepted("ann")).assertIsDisplayed() + node(ReceivedRequestsScreenTags.request("ann")).assertDoesNotExist() + node(ReceivedRequestsScreenTags.request("bob")).assertDoesNotExist() + assertEquals(BookingStatus.CANCELLED, bookings.bookings.single { it.id == "bob" }.status) + } +} 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) + } +} diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/ListingDetailScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/ListingDetailScreenTest.kt index a5cceeb6..4635a1b3 100644 --- a/app/src/test/java/com/android/polybazaar/listing/ui/ListingDetailScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/listing/ui/ListingDetailScreenTest.kt @@ -430,12 +430,26 @@ class ListingDetailScreenTest { assertEquals(listOf("drill"), edited) } + @Test + fun owner_opensTheBookingRequests_evenWhilePaused() { + val opened = mutableListOf() + setContent( + ownerState(drill.copy(isPaused = true)), + ListingDetailActions(onOpenRequests = { opened += it }), + ) + + node(ListingDetailScreenTags.BOOKING_REQUESTS_BUTTON).performScrollTo().performClick() + + assertEquals(listOf("drill"), opened) + } + @Test fun renter_seesNoOwnerMenuOrEdit() { setContent(ListingDetailUiState(listing = drill, lender = lender, canContactLender = true)) node(ListingDetailScreenTags.OWNER_MENU_BUTTON).assertDoesNotExist() node(ListingDetailScreenTags.EDIT_BUTTON).assertDoesNotExist() + node(ListingDetailScreenTags.BOOKING_REQUESTS_BUTTON).assertDoesNotExist() node(ListingDetailScreenTags.BOOKING_NOTE) .assertTextEquals(context.getString(R.string.listing_detail_reassurance)) } diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt index dd10552b..2afd24b8 100644 --- a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt +++ b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt @@ -65,6 +65,7 @@ import com.android.polybazaar.booking.model.FakeBookingRepository import com.android.polybazaar.booking.ui.AvailabilityCalendarSheetTags import com.android.polybazaar.booking.ui.AvailabilityCalendarTags import com.android.polybazaar.booking.ui.BookingRequestScreenTags +import com.android.polybazaar.booking.ui.ReceivedRequestsScreenTags import com.android.polybazaar.browse.ui.BrowseScreenTags import com.android.polybazaar.chat.model.ChatMessage import com.android.polybazaar.chat.model.Conversation @@ -889,6 +890,35 @@ class AppNavHostTest { assertEquals(listOf("drill" to true, "drill" to false), listingRepository.pauseCalls) } + @Test + fun listingDetail_ownerOpensTheBookingRequests_andComesBack() { + listingRepository.myListings = listOf(gracesDrill.copy(ownerUid = user.uid)) + bookingRepository.bookings = + listOf( + Booking( + listingId = "drill", + renterUid = "uid-grace", + lenderUid = user.uid, + days = setOf(LocalDate.now().plusDays(10)), + id = "b1", + ) + ) + setContent(FakeAuthRepository(currentUser = user)) + openProfile() + composeTestRule.onNodeWithTag(ToolboxCardTags.LISTING_ROW).performClick() + assertOnListingDetail("Bosch drill set") + + composeTestRule + .onNodeWithTag(ListingDetailScreenTags.BOOKING_REQUESTS_BUTTON) + .performScrollTo() + .performClick() + + assertCurrentRoute(Routes.RECEIVED_REQUESTS, Routes.LISTING_ID, "drill") + composeTestRule.onNodeWithTag(ReceivedRequestsScreenTags.request("b1")).assertIsDisplayed() + composeTestRule.onNodeWithTag(ReceivedRequestsScreenTags.BACK_BUTTON).performClick() + assertOnListingDetail("Bosch drill set") + } + @Test fun signOut_fromTheListingDetail_returnsToSignIn() { listingRepository.allListings = listOf(gracesDrill) 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 () => {