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
Expand Up @@ -17,6 +17,9 @@ interface BookingRepository {
/** Returns bookings for this listing owned by the signed-in lender. */
suspend fun getBookingsForListing(listingId: String): List<Booking>

/** Returns the bookings of all the listings of the signed-in lender, in any status. */
suspend fun getBookingsForLender(): List<Booking>

/** Returns bookings made by the signed-in renter. */
suspend fun getBookingsForRenter(): List<Booking>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
}

override suspend fun getBookingsForListing(listingId: String): List<Booking> {
val uid = signedInUid("Sign in to read bookings")

Check failure on line 54 in app/src/main/java/com/android/polybazaar/booking/model/FirebaseBookingRepository.kt

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of duplicating this literal "Sign in to read bookings" 3 times.

See more on https://sonarcloud.io/project/issues?id=polybazaar-project_polybazaar&issues=AaH0exFq18xjlWZMWeCX&open=AaH0exFq18xjlWZMWeCX&pullRequest=387
return firestore
.collection(BOOKINGS)
.whereEqualTo("listingId", listingId)
Expand All @@ -62,6 +62,18 @@
.map { it.toBooking() }
}

override suspend fun getBookingsForLender(): List<Booking> {
val uid = signedInUid("Sign in to read bookings")
// The rules let a lender read the bookings that name them, so the query passes as a whole.
return firestore
.collection(BOOKINGS)
.whereEqualTo("lenderUid", uid)
.get()
.await()
.documents
.map { it.toBooking() }
}

override suspend fun getBookingsForRenter(): List<Booking> {
val uid = signedInUid("Sign in to read bookings")
return firestore
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.android.polybazaar.toolbox.model

import com.android.polybazaar.booking.model.Booking
import com.android.polybazaar.booking.model.BookingStatus
import com.android.polybazaar.listing.model.Listing
import java.time.LocalDate

/**
* What the owner's Toolbox says about one of their listings (#196), derived from the listing and
* its bookings rather than stored.
*
* Lenders cannot approve or reject a request yet, so any booking that is not cancelled and covers
* today makes the listing [BookedToday]. Once requests can be approved, it should only count
* approved bookings. Bookings on later days do not show: the listing is still [Available] today.
*/
sealed interface ToolboxListingStatus {
/** Hidden from everyone else by its owner; shown whatever its bookings. */
data object Paused : ToolboxListingStatus

/** A booking that is not cancelled covers today. */
data object BookedToday : ToolboxListingStatus

/** Not paused, and no booking that is not cancelled covers today. */
data object Available : ToolboxListingStatus
}

/**
* The status of [listing] on [today], from [bookings], which may include those of other listings.
*/
fun toolboxListingStatus(
listing: Listing,
bookings: List<Booking>,
today: LocalDate,
): ToolboxListingStatus {
if (listing.isPaused) return ToolboxListingStatus.Paused
val bookedToday = bookings.any {
it.listingId == listing.listingId && it.status != BookingStatus.CANCELLED && today in it.days
}
return if (bookedToday) ToolboxListingStatus.BookedToday else ToolboxListingStatus.Available
}
81 changes: 72 additions & 9 deletions app/src/main/java/com/android/polybazaar/toolbox/ui/ToolboxCard.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
Expand All @@ -26,6 +27,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
Expand All @@ -46,8 +48,10 @@ import com.android.polybazaar.listing.model.ListingType
import com.android.polybazaar.listing.model.ServiceListing
import com.android.polybazaar.listing.model.formatChf
import com.android.polybazaar.listing.ui.PausedBadge
import com.android.polybazaar.toolbox.model.ToolboxListingStatus
import com.android.polybazaar.toolbox.viewmodel.ToolboxUiState
import com.android.polybazaar.toolbox.viewmodel.ToolboxViewModel
import java.time.LocalDate

object ToolboxCardTags {
const val LISTINGS = "toolbox_listings"
Expand All @@ -61,8 +65,14 @@ object ToolboxCardTags {
const val FILTER_SERVICES = "toolbox_filter_services"
const val FILTER_EMPTY = "toolbox_filter_empty"
const val PAUSED_BADGE = "toolbox_paused_badge"
/** The status of an unpaused listing: available or booked today. */
const val STATUS_BADGE = "toolbox_status_badge"
}

/** Green for a listing anyone can book, so it reads apart from the busy ones. */
private val AvailableText = Color(0xFF2E6B3A)
private val AvailableBackground = Color(0xFFE3F1E1)

/** @param onOpenListing called with a listing's id when the user taps its row. */
@Composable
fun ToolboxCard(viewModel: ToolboxViewModel, onOpenListing: (String) -> Unit = {}) {
Expand All @@ -83,6 +93,9 @@ fun ToolboxCard(viewModel: ToolboxViewModel, onOpenListing: (String) -> Unit = {
* Fills the height it is given: the title stays in place and the rows scroll inside the card, so it
* needs a bounded height.
*
* Each row shows its listing's status on [today]: paused, booked today or available. A row whose
* status needs bookings that could not be loaded shows none.
*
* @param onOpenListing called with a listing's id when the user taps its row.
*/
@Composable
Expand All @@ -92,6 +105,7 @@ fun ToolboxContent(
onTypeSelected: (ListingType?) -> Unit,
modifier: Modifier = Modifier,
onOpenListing: (String) -> Unit = {},
today: LocalDate = LocalDate.now(),
) {
val shape = RoundedCornerShape(20.dp)
Column(
Expand Down Expand Up @@ -182,7 +196,11 @@ fun ToolboxContent(
items(filteredListings) { listing ->
// A listing loaded from the repository always has its id.
val id = listing.listingId
ToolboxListingRow(listing = listing, onClick = id?.let { { onOpenListing(it) } })
ToolboxListingRow(
listing = listing,
status = uiState.statusOf(listing, today),
onClick = id?.let { { onOpenListing(it) } },
)
}
}
} else if (uiState.listings.isNotEmpty()) {
Expand Down Expand Up @@ -233,9 +251,16 @@ private fun TypeFilterButton(
)
}

/** @param onClick called when the user taps the row, or null for a row that cannot be tapped. */
/**
* @param status what the badge after the title says, or null for no badge.
* @param onClick called when the user taps the row, or null for a row that cannot be tapped.
*/
@Composable
private fun ToolboxListingRow(listing: Listing, onClick: (() -> Unit)?) {
private fun ToolboxListingRow(
listing: Listing,
status: ToolboxListingStatus?,
onClick: (() -> Unit)?,
) {
val shape = RoundedCornerShape(18.dp)
val openLabel = stringResource(R.string.open_listing)
// Clipped first, so the ripple follows the row's rounded corners.
Expand Down Expand Up @@ -269,11 +294,7 @@ private fun ToolboxListingRow(listing: Listing, onClick: (() -> Unit)?) {
// Not filling: the badge follows a short title, and a long one is cut before the badge.
modifier = Modifier.weight(1f, fill = false),
)
// Paused listings are hidden from everyone else, so the owner needs to see which ones are.
if (listing.isPaused) {
// No vertical padding, so a paused row is as tall as an active one.
PausedBadge(Modifier.testTag(ToolboxCardTags.PAUSED_BADGE), verticalPadding = 0.dp)
}
status?.let { StatusBadge(it) }
}
Row {
Text(
Expand All @@ -297,6 +318,47 @@ private fun ToolboxListingRow(listing: Listing, onClick: (() -> Unit)?) {
}
}

/**
* The badge after a row's title. Paused uses the listing detail's badge: paused listings are hidden
* from everyone else, so the owner needs to spot them. No vertical padding, so every row is as tall
* as one without a badge.
*/
@Composable
private fun StatusBadge(status: ToolboxListingStatus) {
when (status) {
ToolboxListingStatus.Paused ->
PausedBadge(Modifier.testTag(ToolboxCardTags.PAUSED_BADGE), verticalPadding = 0.dp)
ToolboxListingStatus.Available ->
StatusPill(
text = stringResource(R.string.toolbox_status_available),
textColor = AvailableText,
background = AvailableBackground,
)
ToolboxListingStatus.BookedToday ->
StatusPill(
text = stringResource(R.string.toolbox_status_booked_today),
textColor = AuthColors.CardBackground,
background = AuthColors.Accent,
)
}
}

/** A pill shaped like [PausedBadge], in the colours of its status. */
@Composable
private fun StatusPill(text: String, textColor: Color, background: Color) {
Text(
text = text.uppercase(),
color = textColor,
fontSize = 11.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
modifier =
Modifier.testTag(ToolboxCardTags.STATUS_BADGE)
.background(background, CircleShape)
.padding(horizontal = 10.dp),
)
}

@Preview(showBackground = true, widthDp = 412, heightDp = 320)
@Composable
internal fun ToolboxContentPreview() {
Expand All @@ -320,7 +382,8 @@ internal fun ToolboxContentPreview() {
"",
listingId = "math",
),
)
),
bookings = emptyList(),
),
onRetry = {},
onTypeSelected = {},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
// Co-authored-by: Claude Code (Claude Opus 5.5)
package com.android.polybazaar.toolbox.viewmodel

import android.util.Log
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.error.model.AppError
import com.android.polybazaar.error.model.toAppError
import com.android.polybazaar.listing.model.Listing
import com.android.polybazaar.listing.model.ListingRepository
import com.android.polybazaar.listing.model.ListingType
import com.android.polybazaar.toolbox.model.ToolboxListingStatus
import com.android.polybazaar.toolbox.model.toolboxListingStatus
import java.time.LocalDate
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -24,20 +31,40 @@ import kotlinx.coroutines.launch
* @property isLoading true while the listings are being loaded.
* @property error why the last load failed, or null.
* @property selectedType the type the listings are filtered by, or null to show them all.
* @property bookings the bookings of all the user's listings, or null until they are first loaded
* and after the last load of them failed: the listings then show only whether they are paused,
* since bookings from an earlier load may be out of date.
*/
data class ToolboxUiState(
val listings: List<Listing> = emptyList(),
val isLoading: Boolean = false,
val error: AppError? = null,
val selectedType: ListingType? = null,
val bookings: List<Booking>? = null,
) {
/**
* The status of [listing] on [today], or null when it depends on [bookings] that are not loaded:
* a paused listing is known to be paused without them.
*/
fun statusOf(listing: Listing, today: LocalDate): ToolboxListingStatus? =
when {
listing.isPaused -> ToolboxListingStatus.Paused
bookings == null -> null
else -> toolboxListingStatus(listing, bookings, today)
}

/** The [listings] of the [selectedType], or all of them when no type is selected. */
val filteredListings: List<Listing>
get() = if (selectedType == null) listings else listings.filter { it.type == selectedType }
}

/** Loads the signed-in user's listings for the Toolbox. */
class ToolboxViewModel(private val listingRepository: ListingRepository) : ViewModel() {
/**
* Loads the signed-in user's listings for the Toolbox, with the bookings that give their status.
*/
class ToolboxViewModel(
private val listingRepository: ListingRepository,
private val bookingRepository: BookingRepository,
) : ViewModel() {

private val _uiState = MutableStateFlow(ToolboxUiState())
val uiState: StateFlow<ToolboxUiState> = _uiState.asStateFlow()
Expand All @@ -52,15 +79,19 @@ class ToolboxViewModel(private val listingRepository: ListingRepository) : ViewM
}

/**
* Loads the user's listings, for example again after a failure (Retry) or after creating one.
* Ignored while a load is already running. On failure the listings already shown are kept, so a
* reload while offline does not empty the Toolbox.
* Loads the user's listings and their bookings, for example again after a failure (Retry) or
* after creating one. Ignored while a load is already running. On failure the listings already
* shown are kept, so a reload while offline does not empty the Toolbox, and the error says they
* may be out of date. A failure of the bookings shows no error, as the listings are still worth
* showing, so the bookings are dropped instead: a status from an earlier load would look current.
*/
fun loadListings() {
// Two loads at once could finish in any order, and the older answer would overwrite the newer.
if (_uiState.value.isLoading) return
_uiState.update { it.copy(isLoading = true, error = null) }
viewModelScope.launch {
// At the same time as the listings, so the statuses do not arrive a round trip later.
val bookings = async { loadBookings() }
try {
listingRepository
.getMyListings()
Expand All @@ -70,10 +101,29 @@ class ToolboxViewModel(private val listingRepository: ListingRepository) : ViewM
if (exception is CancellationException) throw exception
_uiState.update { it.copy(error = exception.toAppError()) }
}
val loaded = bookings.await()
_uiState.update { it.copy(bookings = loaded) }
} finally {
// Also on cancellation, otherwise the guard above would block every later load.
_uiState.update { it.copy(isLoading = false) }
}
}
}

/**
* The user's bookings as a lender, or null when they cannot be read. The failure is logged, as
* nothing on screen reports it: a malformed booking would otherwise hide every status silently.
*/
private suspend fun loadBookings(): List<Booking>? =
try {
bookingRepository.getBookingsForLender()
} catch (exception: Exception) {
Comment thread
adrimikh marked this conversation as resolved.
Resolved
if (exception is CancellationException) throw exception
Log.w(TAG, "Could not load the bookings, so the listings show no status", exception)
null
}

private companion object {
const val TAG = "ToolboxViewModel"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,9 @@ fun AppNavHost(
viewModel(
key = "toolbox_$uid",
factory =
viewModelFactory { initializer { ToolboxViewModel(listingRepository) } },
viewModelFactory {
initializer { ToolboxViewModel(listingRepository, bookingRepository) }
},
)
// Switching tabs keeps this ViewModel, so a listing published since it loaded needs a
// reload to show up when the user comes back.
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@
<string name="toolbox_filter_services">Services</string>
<string name="toolbox_empty_items">You have no item listings.</string>
<string name="toolbox_empty_services">You have no service listings.</string>
<string name="toolbox_status_available">Available</string>
<string name="toolbox_status_booked_today">Booked today</string>

<!-- Forgot password screen -->
<string name="forgot_password_title">Forgot password</string>
Expand Down
Loading
Loading