Modern Apps git

← Modern-Apps.git

travel: in-app card payment for the Nuitee backend + booking flow fixes

Commit
e52539d63bde22fba43a44b64c2194a75ac6c650
Author
Vayun Mathur <[email protected]>
When
2026-11-01 05:50 UTC (1 month ago)
Parents
e714678
Payment: replace the hosted-checkout Custom Tab with the Stripe payment
sheet (platform/StripeCheckout.kt). Checkout returns a client secret and
publishable key; after the sheet completes the app calls
POST /trips/:id/confirm and polls. Applies to flights, stays and
"Complete payment".

Booking flow:
- Review re-verifies the offer every time, so it shows the guaranteed price
  and blocks Continue when the fare can't be booked.
- Round trips: one "Choose flights" step where each outbound card expands
  into the returns it pairs with (fixed pairs), then the fare step.
- Seat map: pick a seat per passenger (passenger picker, P1/P2 badges).
- Extras are re-saved whenever they change, including back to none.
- Online changes hidden (canChange=false); Explore removed.

Home:
- Flights/Stays as a bottom navigation bar.
- From/To suggestions in the shared exposed dropdown menu.
- Search forms are hoisted and saved, so they stay filled in after
  results, tab switches and process death.
- Round-trip and stay dates use one range calendar; date fields no longer
  look disabled.

Adds the Stripe Android SDK; drops androidx.browser and :library:map.

Diff

SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex f8d87f25d9..9f221a31a5 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -16,3 +16,4 @@ Apps that fetch from external servers (excluding vayunmathur.com, maproj.org, ma 7. **email** — only after adding an account: `imap.gmail.com` / `smtp.gmail.com`, `outlook.office365.com` / `smtp-mail.outlook.com`, `imap.mail.yahoo.com` / `smtp.mail.yahoo.com`, `imap.aol.com` / `smtp.aol.com`, `imap.mail.me.com` / `smtp.mail.me.com`, `imap.fastmail.com` / `smtp.fastmail.com`, `login.microsoftonline.com` + `outlook.office.com` (OAuth) 8. **games/chess** — `lichess.org` (OAuth + Board API), only after sign-in 9. **web** — whichever search engine the user picks (WebView loads it; DuckDuckGo default), only on user navigation/search+10. **travel** — `api.stripe.com` (+ Stripe SDK hosts), only when the user pays for a booking in the in-app card sheet
travel/AGENTS.md
diff --git a/travel/AGENTS.md b/travel/AGENTS.mdindex c9be243cae..4782c08947 100644--- a/travel/AGENTS.md+++ b/travel/AGENTS.md@@ -7,7 +7,7 @@ _Install: ./install travel (dev by default)._ - Gradle: :travel / dir: travel/ - Package roots present: ui, data, network - Entry files: MainActivity.kt (no Route.kt — search/results/booking/manage flow with pages)-- Deps: :library:room, :library:network, :library:image+- Deps: :library:room, :library:network, :library:image, Stripe Android SDK (payment sheet) - Metadata: metadata_data/travel.md (present) - Rust: no / screenshotTest: yes @@ -15,10 +15,10 @@ _Install: ./install travel (dev by default)._ `travel` does not use the relay directly, but `NetworkClient.init(FIRST_PARTY)` covers `api.maproj.org`. Server checkout: `../location_share_server` (sibling of this repo root, `C:\Users\Vayun\Documents\code\location_share_server`). Full details: root `AGENTS.md` → "Backend server (outside this repo)".  ## Overview-**Purpose:** Flight + hotel booking — search/comparison, seat maps, ancillaries/offers, trip management with hosted checkout; trips persist on-device so plans stay readable offline.+**Purpose:** Flight + hotel booking — search/comparison, seat maps, ancillaries/offers, trip management with in-app card payment; trips persist on-device so plans stay readable offline. **Key features:**-- Flight search form (one-way / round-trip) → results → offer review → passengers → trip → ancillaries → hosted checkout → confirmation; Explore map (find-destination price pins → live re-search) ; change/cancel/manage on booked trips-- Round-trip step-by-step (grouped on-device); stays search → detail → guests → hosted checkout → confirmation; seat-map picker+- Flight search form (one-way / round-trip) → results → offer review → passengers → trip → ancillaries → payment sheet → confirm → confirmation; cancel/manage on booked trips (online changes are not offered — server sends `canChange=false`)+- Round-trip step-by-step (grouped on-device); stays search → detail → guests → payment sheet → confirm → confirmation; seat-map picker - `data/` Room (trips, local booking profiles, frequent-flyer, recent searches) + `domain/` on-device grouping/status + `network/` trip/stays DTOs + APIs **Architecture / data-flow:** `ui/` search/results/booking pages → `util/TravelViewModel` (+ `TravelUiContract`/`TravelUiState`, per-area `Travel*Ops`) → `domain/` grouping + `data/TravelRepository` over Room + `network/TravelApi`/`StaysApi`; booked trips stay readable from Room when offline. **Entry points + reading order:** `MainActivity.kt` → `ui/HomePage.kt` → `ui/FlightSearchForm.kt` → `util/TravelViewModel.kt` → `util/TravelSearchOps.kt` → `network/TravelApi.kt`.@@ -26,6 +26,7 @@ _Install: ./install travel (dev by default)._ - `util/` is NOT a closed package root — pending migration; don't add more files there - Booking is money-moving — price/availability must be re-confirmed server-side before payment, never trusted from cached offers - Offline readability is a feature (stored trips), offline booking is not — gate write paths on connectivity+- Payment: `POST /trips/:id/checkout` returns a payment-intent `clientSecret` + `publishableKey` (the provider's processor account, per environment); present it with `platform/StripeCheckout.kt`, then `POST /trips/:id/confirm` books it. Never book before the sheet reports Completed  ## Key files ### Root — entry (no Route.kt)@@ -40,8 +41,8 @@ _Install: ./install travel (dev by default)._ ### domain/ — on-device offer + trip logic - com/vayunmathur/travel/domain/OfferGrouping.kt - com/vayunmathur/travel/domain/TripStatus.kt-### intents/ — hosted-checkout Custom Tab-- com/vayunmathur/travel/intents/CheckoutTabs.kt+### platform/ — in-app card payment (Stripe payment sheet)+- com/vayunmathur/travel/platform/StripeCheckout.kt ### network/ — airline + stays APIs - com/vayunmathur/travel/network/TravelApi.kt - com/vayunmathur/travel/network/OfferDto.kt
travel/build.gradle.kts
diff --git a/travel/build.gradle.kts b/travel/build.gradle.ktsindex 373d5bcdf3..053481e3c0 100644--- a/travel/build.gradle.kts+++ b/travel/build.gradle.kts@@ -22,6 +22,7 @@ dependencies {     implementation(project(":library:network"))      implementation(project(":library:image"))-    implementation(project(":library:map"))-    implementation(libs.androidx.browser)+    implementation(libs.stripe.android)+    // stripe-android doesn't publish kotlin-parcelize-runtime in its POM (see fooddelivery).+    implementation(libs.kotlin.parcelize.runtime) }
travel/src/main/java/com/vayunmathur/travel/MainActivity.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/MainActivity.kt b/travel/src/main/java/com/vayunmathur/travel/MainActivity.ktindex 0767f6144b..6b34379b2d 100644--- a/travel/src/main/java/com/vayunmathur/travel/MainActivity.kt+++ b/travel/src/main/java/com/vayunmathur/travel/MainActivity.kt@@ -22,7 +22,6 @@ import com.vayunmathur.travel.ui.AncillariesPage import com.vayunmathur.travel.ui.CancellationPage import com.vayunmathur.travel.ui.ChangePage import com.vayunmathur.travel.ui.ConfirmationPage-import com.vayunmathur.travel.ui.ExploreMapPage import com.vayunmathur.travel.ui.FlightResultsPage import com.vayunmathur.travel.ui.FareSelectPage import com.vayunmathur.travel.ui.HomePage@@ -31,7 +30,6 @@ import com.vayunmathur.travel.ui.OrderDetailPage import com.vayunmathur.travel.ui.OutboundSelectPage import com.vayunmathur.travel.ui.PassengersPage import com.vayunmathur.travel.ui.PaymentPage-import com.vayunmathur.travel.ui.ReturnSelectPage import com.vayunmathur.travel.ui.SeatMapPage import com.vayunmathur.travel.ui.SettingsPage import com.vayunmathur.travel.ui.StayConfirmationPage@@ -79,8 +77,7 @@ class MainActivity : MaActivity() {      override fun onResume() {         super.onResume()-        // Back from the hosted-checkout Custom Tab: resume polling any trip-        // that is still awaiting payment / processing.+        // Resume polling any trip that is still awaiting payment / processing.         if (!::repository.isInitialized) return         lifecycleScope.launch {             viewModel.pendingTripIds().forEach { viewModel.pollTrip(it) }@@ -108,23 +105,6 @@ sealed interface Route : NavKey {         val maxConnections: Int,     ) : Route -    /**-     * Explore map: search params only (never the destination list — the page-     * fetches via the ViewModel). [tripType] is `oneway` or `roundtrip`.-     */-    @Serializable-    data class Explore(-        val origin: String,-        val tripType: String,-        val depart: String,-        val returnDate: String? = null,-        val cabin: String = "economy",-        val adults: Int = 1,-        val children: String = "",-        val infants: Int = 0,-        val maxConnections: Int = -1,-    ) : Route-     @Serializable     data class OfferReview(val offerId: String) : Route @@ -138,8 +118,6 @@ sealed interface Route : NavKey {         val maxConnections: Int,     ) : Route -    @Serializable-    data class ReturnSelect(val outboundSignature: String) : Route      @Serializable     data class FareSelect(val outboundSignature: String, val inboundSignature: String) : Route@@ -204,9 +182,7 @@ fun MainGraph(viewModel: TravelViewModel) {         MainNavigation(backStack) {             entry<Route.Home> { HomePage(backStack, viewModel) }             entry<Route.FlightResults>(metadata = ListPage()) { FlightResultsPage(backStack, viewModel, it) }-            entry<Route.Explore> { ExploreMapPage(backStack, viewModel, it) }             entry<Route.OutboundSelect> { OutboundSelectPage(backStack, viewModel, it) }-            entry<Route.ReturnSelect> { ReturnSelectPage(backStack, viewModel, it) }             entry<Route.FareSelect> { FareSelectPage(backStack, viewModel, it) }             entry<Route.OfferReview>(metadata = ListDetailPage() + MorphPage()) {                 OfferReviewPage(backStack, viewModel, it)
travel/src/main/java/com/vayunmathur/travel/data/BookedTrip.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/BookedTrip.kt b/travel/src/main/java/com/vayunmathur/travel/data/BookedTrip.ktindex 2391431a07..9384cde9f5 100644--- a/travel/src/main/java/com/vayunmathur/travel/data/BookedTrip.kt+++ b/travel/src/main/java/com/vayunmathur/travel/data/BookedTrip.kt@@ -16,7 +16,7 @@ const val TRIP_STATUS_FAILED = "failed" const val TRIP_STATUS_CANCELLED = "cancelled"  /**- * A booked trip, persisted after hosted checkout starts so it shows up under+ * A booked trip, persisted when checkout starts so it shows up under  * "My trips" and survives restarts. Keyed by [orderId]: the trip id until a  * booking reference exists, then kept stable (the reference is stored in  * [bookingReference] separately). [tripId] is the server trip id used for
travel/src/main/java/com/vayunmathur/travel/domain/AncillarySelection.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/domain/AncillarySelection.kt b/travel/src/main/java/com/vayunmathur/travel/domain/AncillarySelection.ktnew file mode 100644index 0000000000..69e7ba32c2--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/domain/AncillarySelection.kt@@ -0,0 +1,11 @@+package com.vayunmathur.travel.domain++import com.vayunmathur.travel.network.ServiceSelectionDto++/**+ * Whether [selections] must be sent to the trip. The server replaces the whole+ * set on every save, so an unchanged set is skipped, but going from some+ * extras back to none must still be saved to detach them.+ */+fun ancillariesNeedSaving(selections: List<ServiceSelectionDto>, saved: List<ServiceSelectionDto>): Boolean =+    selections.toSet() != saved.toSet()
travel/src/main/java/com/vayunmathur/travel/domain/ExploreSlices.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/domain/ExploreSlices.kt b/travel/src/main/java/com/vayunmathur/travel/domain/ExploreSlices.ktdeleted file mode 100644index 265661689e..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/domain/ExploreSlices.kt+++ /dev/null@@ -1,20 +0,0 @@-package com.vayunmathur.travel.domain--/**- * Live-search slices for an Explore pin: the tapped destination re-searched- * through the normal flight flow (explore fares are cached estimates, never- * booked directly). One-way is a single slice; round-trips reverse it.- * Pure: covered by unit tests.- */-fun exploreLiveSlices(-    origin: String,-    destinationCode: String,-    departDate: String,-    returnDate: String,-    isRoundTrip: Boolean,-): String =-    if (isRoundTrip && returnDate.isNotBlank()) {-        "$origin:$destinationCode:$departDate,$destinationCode:$origin:$returnDate"-    } else {-        "$origin:$destinationCode:$departDate"-    }
travel/src/main/java/com/vayunmathur/travel/domain/OfferGrouping.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/domain/OfferGrouping.kt b/travel/src/main/java/com/vayunmathur/travel/domain/OfferGrouping.ktindex 211f06c908..daefbccca9 100644--- a/travel/src/main/java/com/vayunmathur/travel/domain/OfferGrouping.kt+++ b/travel/src/main/java/com/vayunmathur/travel/domain/OfferGrouping.kt@@ -87,3 +87,4 @@ fun faresForItineraryPair(                 sliceSignature(it.slices[1]) == inboundSignature         }         .sortedBy { it.totalAmount.toDoubleOrNull() ?: Double.MAX_VALUE }+
travel/src/main/java/com/vayunmathur/travel/domain/SeatAssignment.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/domain/SeatAssignment.kt b/travel/src/main/java/com/vayunmathur/travel/domain/SeatAssignment.ktnew file mode 100644index 0000000000..3285f8fb70--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/domain/SeatAssignment.kt@@ -0,0 +1,62 @@+package com.vayunmathur.travel.domain++import com.vayunmathur.travel.network.OfferPassengerDto+import com.vayunmathur.travel.network.SeatElementDto+import com.vayunmathur.travel.network.ServiceSelectionDto++/**+ * Per-passenger seat selection. The selected-seats map is keyed+ * `"<segmentId>|<passengerId>"`: at most one seat per passenger per segment,+ * and a seat belongs to at most one passenger. Pure: covered by unit tests.+ */++fun seatKey(segmentId: String, passengerId: String): String = "$segmentId|$passengerId"++/** Passengers who occupy a seat (infants on a lap don't). */+fun seatedPassengers(passengers: List<OfferPassengerDto>): List<OfferPassengerDto> =+    passengers.filter { it.type != "infant_without_seat" }++/** The passenger holding [designator] on [segmentId], if any. */+fun seatHolder(selected: Map<String, SeatElementDto>, segmentId: String, designator: String): String? =+    selected.entries+        .firstOrNull { (key, seat) -> key.startsWith("$segmentId|") && seat.designator == designator }+        ?.key+        ?.substringAfter('|')++/**+ * Tap [seat] for [passengerId] on [segmentId]: tapping the passenger's own seat+ * clears it; otherwise the seat replaces their previous one. Seats held by+ * someone else, unavailable seats and seats without a service are ignored.+ */+fun assignSeat(+    selected: Map<String, SeatElementDto>,+    segmentId: String,+    passengerId: String,+    seat: SeatElementDto,+): Map<String, SeatElementDto> {+    if (!seat.available || seat.serviceId == null) return selected+    val key = seatKey(segmentId, passengerId)+    val holder = seatHolder(selected, segmentId, seat.designator)+    return when (holder) {+        passengerId -> selected - key+        null -> selected + (key to seat)+        else -> selected+    }+}++/** The passenger to pick for next: the first seated passenger without a seat on [segmentId]. */+fun nextPassengerToSeat(+    selected: Map<String, SeatElementDto>,+    segmentId: String,+    passengers: List<OfferPassengerDto>,+): String? {+    val seated = seatedPassengers(passengers)+    return seated.firstOrNull { seatKey(segmentId, it.id) !in selected }?.id ?: seated.firstOrNull()?.id+}++/** Seat selections for the server, each tagged with its passenger. */+fun seatSelections(selected: Map<String, SeatElementDto>): List<ServiceSelectionDto> =+    selected.mapNotNull { (key, seat) ->+        val passengerId = key.substringAfter('|', "").ifBlank { null }+        seat.serviceId?.let { ServiceSelectionDto(id = it, quantity = 1, passengerId = passengerId) }+    }
travel/src/main/java/com/vayunmathur/travel/intents/CheckoutTabs.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/intents/CheckoutTabs.kt b/travel/src/main/java/com/vayunmathur/travel/intents/CheckoutTabs.ktdeleted file mode 100644index aaf8e43b15..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/intents/CheckoutTabs.kt+++ /dev/null@@ -1,38 +0,0 @@-package com.vayunmathur.travel.intents--import android.content.Context-import android.net.Uri-import androidx.browser.customtabs.CustomTabColorSchemeParams-import androidx.browser.customtabs.CustomTabsIntent-import com.vayunmathur.library.util.AppMessages--/**- * Open a hosted-checkout URL in a Custom Tab (in-app secure payment page).- * Falls back to a plain view intent when Custom Tabs is unavailable, and- * reports (rather than throwing) when nothing handles the URL.- */-fun openCheckout(context: Context, url: String) {-    if (url.isBlank()) {-        AppMessages.show("Payment link is missing. Please try again.")-        return-    }-    runCatching {-        val params = CustomTabColorSchemeParams.Builder().build()-        val intent = CustomTabsIntent.Builder()-            .setDefaultColorSchemeParams(params)-            .setShowTitle(true)-            .setShareState(CustomTabsIntent.SHARE_STATE_OFF)-            .build()-        intent.launchUrl(context, Uri.parse(url))-    }.onFailure {-        runCatching {-            val view = android.content.Intent(-                android.content.Intent.ACTION_VIEW,-                Uri.parse(url)-            ).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)-            context.startActivity(view)-        }.onFailure {-            AppMessages.show("No app can open the payment page.")-        }-    }-}
travel/src/main/java/com/vayunmathur/travel/network/ExploreDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/ExploreDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/ExploreDto.ktdeleted file mode 100644index c2a234455b..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/network/ExploreDto.kt+++ /dev/null@@ -1,32 +0,0 @@-package com.vayunmathur.travel.network--import kotlinx.serialization.Serializable--/**- * A destination suggestion from `GET /api/travel/explore` (proxied- * `find_destination`): cached lowest fare + coordinates for the map pins.- * Fares are exploration-only — the app re-searches live via [TravelApi.flights]- * before booking.- */-@Serializable-data class ExploreDestinationDto(-    val cityName: String = "",-    val iataCode: String = "",-    val imageUrl: String = "",-    val latitude: Double? = null,-    val longitude: Double? = null,-    val lowestAmount: String = "",-    val lowestCurrency: String = "",-    /** Airport code of the lowest-fare flight's destination (for live re-search). */-    val destinationCode: String = "",-    /** Departure date of the lowest-fare flight (`YYYY-MM-DD`). */-    val departDate: String = "",-    /** Return date of the lowest-fare flight (`YYYY-MM-DD`, "" when one-way). */-    val returnDate: String = "",-)--/** The result of an explore search: one entry per suggested destination. */-@Serializable-data class ExploreSearchDto(-    val destinations: List<ExploreDestinationDto> = emptyList(),-)
travel/src/main/java/com/vayunmathur/travel/network/OrderDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/OrderDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/OrderDto.ktindex 684ba455b8..5601beaaae 100644--- a/travel/src/main/java/com/vayunmathur/travel/network/OrderDto.kt+++ b/travel/src/main/java/com/vayunmathur/travel/network/OrderDto.kt@@ -117,13 +117,15 @@ data class AncillariesSelectionResultDto( )  /**- * Hosted-checkout details from `POST /api/travel/trips/:id/checkout`. Open- * [checkoutUrl] in a Custom Tab. When [priceChanged], show [originalAmount] vs- * [totalAmount] and require an explicit accept before allowing pay.+ * Payment details from `POST /api/travel/trips/:id/checkout`: confirm+ * [clientSecret] with the native payment sheet (initialized with+ * [publishableKey]), then call `POST /trips/:id/confirm`. When [priceChanged],+ * show [originalAmount] vs [totalAmount] and require an explicit accept first.  */ @Serializable data class CheckoutDto(-    val checkoutUrl: String = "",+    val clientSecret: String = "",+    val publishableKey: String = "",     val quoteId: String = "",     val totalAmount: String = "0",     val currency: String = "USD",
travel/src/main/java/com/vayunmathur/travel/network/StaysApi.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/StaysApi.kt b/travel/src/main/java/com/vayunmathur/travel/network/StaysApi.ktindex 6ce011f0f9..7654ef8b64 100644--- a/travel/src/main/java/com/vayunmathur/travel/network/StaysApi.kt+++ b/travel/src/main/java/com/vayunmathur/travel/network/StaysApi.kt@@ -7,8 +7,9 @@ import kotlinx.serialization.json.Json /**  * Thin wrapper over the shared [NetworkClient] for the `/api/stays` endpoints on  * the proxy. Mirrors [TravelApi]: URL/body construction + delegation, with the- * booking token held server-side. Booking completes via hosted checkout; the- * trip is then polled/serviced through the shared trip + bookings endpoints.+ * booking token held server-side. Booking returns a payment intent paid in-app;+ * the trip is then confirmed/polled/serviced through the shared trip + bookings+ * endpoints.  * Callers wrap in try/catch and surface errors.  */ object StaysApi {@@ -59,7 +60,7 @@ object StaysApi {     suspend fun quote(rateId: String): StayQuoteDto =         postJson("$BASE/quote", StayQuoteRequest(rateId), "Quote failed") -    /** Book a quoted rate: upserts travelers, starts hosted checkout. */+    /** Book a quoted rate: records guests, returns the payment intent. */     suspend fun book(request: StayBookingRequestDto): StayBookingResultDto =         postJson("$BASE/bookings", request, "Booking failed") 
travel/src/main/java/com/vayunmathur/travel/network/StaysDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/StaysDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/StaysDto.ktindex 2d7a77bc4a..0bb30d7252 100644--- a/travel/src/main/java/com/vayunmathur/travel/network/StaysDto.kt+++ b/travel/src/main/java/com/vayunmathur/travel/network/StaysDto.kt@@ -96,8 +96,8 @@ data class StayBookingRequestDto( )  /**- * A stay booking after hosted checkout starts. Polling and servicing then use- * the shared trip (`GET /travel/trips/:id`) and bookings endpoints.+ * A quoted stay ready to pay: confirm [clientSecret] in-app, then confirm and+ * poll through the shared trip endpoints (`/travel/trips/:id`).  */ @Serializable data class StayBookingResultDto(@@ -109,6 +109,7 @@ data class StayBookingResultDto(     val checkOutDate: String = "",     val totalAmount: String = "0",     val totalCurrency: String = "USD",-    val checkoutUrl: String = "",+    val clientSecret: String = "",+    val publishableKey: String = "",     val expiresAt: String = "", )
travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt b/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.ktindex a7352d4640..2b9d3b4ccd 100644--- a/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt+++ b/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt@@ -59,40 +59,6 @@ object TravelApi {         )     ) -    /**-     * Explore destination suggestions with cached lowest fares for the map-     * pins: one entry per suggested destination. Fares are exploration-only;-     * the app re-searches live via [flights] before booking.-     */-    suspend fun explore(-        origins: String,-        tripType: String,-        depart: String,-        returnDate: String? = null,-        cabin: String = "economy",-        adults: Int = 1,-        children: String = "",-        infants: Int = 0,-        maxConnections: Int = -1,-        maxTotal: Double? = null,-        currency: String = "",-    ): ExploreSearchDto = NetworkClient.getJson(-        buildString {-            append(BASE).append("/explore")-            append("?origins=").append(enc(origins))-            append("&trip_type=").append(enc(tripType))-            append("&depart=").append(enc(depart))-            if (!returnDate.isNullOrBlank()) append("&return_date=").append(enc(returnDate))-            append("&cabin=").append(enc(cabin))-            append("&adults=").append(adults)-            if (children.isNotBlank()) append("&children=").append(enc(children))-            if (infants > 0) append("&infants=").append(infants)-            if (maxConnections >= 0) append("&max_connections=").append(maxConnections)-            if (maxTotal != null) append("&max_total=").append(maxTotal)-            if (currency.isNotBlank()) append("&currency=").append(enc(currency))-        }-    )-     private fun flightsUrl(         path: String,         origin: String,@@ -170,10 +136,13 @@ object TravelApi {         )      /**-     * Start hosted checkout for a trip. Raises [MissingDetailsException] (422)-     * when traveler details are missing and [StillPricingException] (503)-     * while the server is still pricing.+     * Get the payment intent for a trip. Raises [MissingDetailsException] (422)+     * when traveler details are missing.      */     suspend fun checkout(id: String): CheckoutDto =         travelPostJson("$BASE/trips/${enc(id)}/checkout", "", "Could not start payment")++    /** Book the trip after the payment sheet confirmed its intent. */+    suspend fun confirmPayment(id: String): TripDto =+        travelPostJson("$BASE/trips/${enc(id)}/confirm", "", "Could not confirm booking") }
travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.kt b/travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.ktnew file mode 100644index 0000000000..021c0b6778--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.kt@@ -0,0 +1,61 @@+package com.vayunmathur.travel.platform++import android.content.Context+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.platform.LocalContext+import com.stripe.android.PaymentConfiguration+import com.stripe.android.paymentsheet.PaymentSheet+import com.stripe.android.paymentsheet.PaymentSheetResult+import com.stripe.android.paymentsheet.rememberPaymentSheet++/** Outcome of the in-app card payment sheet. */+sealed interface CardPaymentResult {+    data object Completed : CardPaymentResult+    data object Canceled : CardPaymentResult+    data class Failed(val message: String) : CardPaymentResult+}++/**+ * Presents the native payment sheet for a server-issued payment intent. The+ * publishable key comes with each checkout because it must match the account+ * and environment the intent was created on.+ */+class CardPayment internal constructor(+    private val context: Context,+    private val sheet: PaymentSheet,+) {+    /** Returns false (without presenting) when the checkout lacks payment details. */+    fun present(clientSecret: String, publishableKey: String): Boolean {+        if (clientSecret.isBlank() || publishableKey.isBlank()) return false+        PaymentConfiguration.init(context, publishableKey)+        sheet.presentWithPaymentIntent(+            clientSecret,+            PaymentSheet.Configuration(merchantDisplayName = MERCHANT_DISPLAY_NAME),+        )+        return true+    }++    private companion object {+        const val MERCHANT_DISPLAY_NAME = "Travel"+    }+}++@Composable+fun rememberCardPayment(onResult: (CardPaymentResult) -> Unit): CardPayment {+    val context = LocalContext.current.applicationContext+    val callback by rememberUpdatedState(onResult)+    val sheet = rememberPaymentSheet { result ->+        callback(+            when (result) {+                is PaymentSheetResult.Completed -> CardPaymentResult.Completed+                is PaymentSheetResult.Canceled -> CardPaymentResult.Canceled+                is PaymentSheetResult.Failed ->+                    CardPaymentResult.Failed(result.error.localizedMessage ?: "Payment failed. Please try again.")+            }+        )+    }+    return remember(sheet) { CardPayment(context, sheet) }+}
travel/src/main/java/com/vayunmathur/travel/ui/AncillariesPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesPage.ktindex ed31ca46f0..c49d976540 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesPage.kt@@ -43,7 +43,7 @@ import androidx.compose.ui.res.stringResource  /**  * Extras step: bag services + seat maps off the created trip. Saving posts- * the selections, then the flow moves to hosted checkout.+ * the selections, then the flow moves to checkout.  */ @OptIn(ExperimentalMaterial3Api::class) @Composable
travel/src/main/java/com/vayunmathur/travel/ui/ChangePage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/ChangePage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/ChangePage.ktindex 9925cabb36..645ea34534 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/ChangePage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/ChangePage.kt@@ -35,7 +35,6 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route-import com.vayunmathur.travel.intents.openCheckout import com.vayunmathur.travel.network.ChangeOfferDto import com.vayunmathur.travel.network.SliceDto import com.vayunmathur.travel.util.TravelViewModel@@ -63,7 +62,6 @@ fun ChangePage(      var selectedSliceIndex by remember { mutableStateOf(0) }     var newDate by remember { mutableStateOf("") }-    val context = androidx.compose.ui.platform.LocalContext.current      AppScaffold(         title = stringResource(R.string.change_flights),@@ -127,8 +125,7 @@ fun ChangePage(                     Text(stringResource(R.string.no_change_options_available), color = MaterialTheme.colorScheme.onSurfaceVariant)                 } else {                     Text(stringResource(R.string.change_options), style = MaterialTheme.typography.titleMedium, modifier = Modifier.fillMaxWidth())-                    change.checkoutUrl?.let { url ->-                        LaunchedEffect(url) { openCheckout(context, url) }+                    change.checkoutUrl?.let {                         Text(                             stringResource(R.string.change_payment_needed),                             style = MaterialTheme.typography.bodyMedium,
travel/src/main/java/com/vayunmathur/travel/ui/Common.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/Common.kt b/travel/src/main/java/com/vayunmathur/travel/ui/Common.ktindex 6c4e143828..c1a5a05c15 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/Common.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/Common.kt@@ -7,7 +7,6 @@ import com.vayunmathur.library.ui.DateString import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import androidx.compose.foundation.background-import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -16,7 +15,6 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size-import com.vayunmathur.library.ui.IconCompass import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue@@ -27,23 +25,13 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight-import androidx.compose.foundation.text.KeyboardOptions-import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.repeatOnLifecycle import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.ElevatedCard-import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text-import com.vayunmathur.travel.network.PlaceDto-import com.vayunmathur.travel.util.TravelViewModel-import com.vayunmathur.travel.util.autocomplete-import androidx.compose.ui.res.stringResource-import com.vayunmathur.travel.R  @Composable fun SectionHeader(text: String, modifier: Modifier = Modifier) {@@ -56,86 +44,6 @@ fun SectionHeader(text: String, modifier: Modifier = Modifier) {     ) } -/**- * Airport/city autocomplete field. Owns its own text; reports the chosen code- * back via [onCodeChange] — either an IATA/city code when a suggestion is- * tapped, or the raw typed text as a fallback so power users can type "LON".- *- * When [showExploreRow] is true (the flights To field), a pinned "Explore"- * row is always shown in the dropdown; tapping it calls [onExploreSelected]- * instead of reporting a code.- */-@Composable-fun PlaceAutocompleteField(-    label: String,-    viewModel: TravelViewModel,-    onCodeChange: (String) -> Unit,-    modifier: Modifier = Modifier,-    initialText: String = "",-    showExploreRow: Boolean = false,-    onExploreSelected: () -> Unit = {},-) {-    var text by remember { mutableStateOf(initialText) }-    var suggestions by remember { mutableStateOf<List<PlaceDto>>(emptyList()) }-    var justSelected by remember { mutableStateOf(false) }--    LaunchedEffect(text) {-        if (justSelected) {-            justSelected = false-            return@LaunchedEffect-        }-        if (text.length < 2) {-            suggestions = emptyList()-            return@LaunchedEffect-        }-        kotlinx.coroutines.delay(100)-        suggestions = viewModel.autocomplete(text)-    }--    Column(modifier) {-        OutlinedTextField(-            value = text,-            onValueChange = {-                text = it-                onCodeChange(it.trim())-            },-            label = { Text(label) },-            singleLine = true,-            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii),-            modifier = Modifier.fillMaxWidth(),-        )-        if (suggestions.isNotEmpty() || showExploreRow) {-            val exploreLabel = stringResource(R.string.explore)-            ElevatedCard(Modifier.fillMaxWidth().padding(top = 4.dp)) {-                Column {-                    if (showExploreRow) {-                        ListItem(-                            modifier = Modifier.clickable {-                                onCodeChange("")-                                text = exploreLabel-                                justSelected = true-                                suggestions = emptyList()-                                onExploreSelected()-                            },-                            leadingContent = { IconCompass() },-                        ) { Text(stringResource(R.string.explore_anywhere)) }-                    }-                    suggestions.take(6).forEach { place ->-                        ListItem(-                            modifier = Modifier.clickable {-                                onCodeChange(place.code)-                                text = "${place.code} · ${place.city.ifBlank { place.name }}"-                                justSelected = true-                                suggestions = emptyList()-                            },-                        ) { Text(place.label) }-                    }-                }-            }-        }-    }-}- /** Centered loading/error/empty state used by results pages. */ @Composable fun StatusBox(
travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationPage.ktindex e872bf33fc..858e72c8db 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationPage.kt@@ -10,9 +10,11 @@ import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle@@ -27,6 +29,7 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route import com.vayunmathur.travel.data.TRIP_STATUS_FAILED@@ -37,10 +40,12 @@ import com.vayunmathur.travel.domain.isCheckoutUnexpired import com.vayunmathur.travel.domain.isTripAwaitingPayment import com.vayunmathur.travel.domain.isTripPollingStatus import com.vayunmathur.travel.domain.tripStatusLabel-import com.vayunmathur.travel.intents.openCheckout+import com.vayunmathur.travel.platform.CardPaymentResult+import com.vayunmathur.travel.platform.rememberCardPayment import com.vayunmathur.travel.util.CheckoutState import com.vayunmathur.travel.util.TravelViewModel import com.vayunmathur.travel.util.TripPollState+import com.vayunmathur.travel.util.confirmPaidTrip import com.vayunmathur.travel.util.pollTrip import com.vayunmathur.travel.util.recheckoutForStoredTrip import androidx.compose.ui.res.stringResource@@ -49,7 +54,7 @@ import androidx.compose.ui.res.stringResource  * Post-payment confirmation: polls the trip while pending/processing and  * shows the final status (confirmed / processing / failed / partial) with the  * booking reference. While pending_payment (and the checkout has not expired)- * offers "Complete payment" (fresh link in a Custom Tab) + "Refresh status".+ * offers "Complete payment" (in-app card sheet) + "Refresh status".  */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -62,11 +67,28 @@ fun ConfirmationPage(     val trip = trips.find { it.orderId == route.orderId }     val poll by viewModel.tripPoll.collectAsStateWithLifecycle()     val checkout by viewModel.checkout.collectAsStateWithLifecycle()-    val context = LocalContext.current+    val tripId = trip?.tripId?.ifBlank { route.orderId } ?: route.orderId+    var paying by remember { mutableStateOf(false) }+    var presentWhenReady by remember { mutableStateOf(false) }+    val cardPayment = rememberCardPayment { result ->+        paying = false+        when (result) {+            CardPaymentResult.Completed -> viewModel.confirmPaidTrip(tripId)+            CardPaymentResult.Canceled -> Unit+            is CardPaymentResult.Failed -> AppMessages.show(result.message)+        }+    }      LaunchedEffect(route.orderId) {-        val id = trip?.tripId?.ifBlank { route.orderId } ?: route.orderId-        viewModel.pollTrip(id)+        viewModel.pollTrip(tripId)+    }++    // "Complete payment" fetched a fresh intent: present it once it arrives.+    LaunchedEffect(checkout, presentWhenReady) {+        val ready = (checkout as? CheckoutState.Ready)?.checkout ?: return@LaunchedEffect+        if (!presentWhenReady) return@LaunchedEffect+        presentWhenReady = false+        paying = cardPayment.present(ready.clientSecret, ready.publishableKey)     }      DetailScaffold(@@ -129,20 +151,25 @@ fun ConfirmationPage(             }              if (isTripAwaitingPayment(trip.status)) {+                (poll as? TripPollState.Error)?.let {+                    Text(it.message, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)+                }                 (checkout as? CheckoutState.Error)?.let {                     Text(it.message, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)                 }-                val fresh = (checkout as? CheckoutState.Ready)?.checkout-                if (fresh != null && isCheckoutUnexpired(trip.checkoutExpiresAt)) {-                    Button(-                        onClick = { openCheckout(context, fresh.checkoutUrl) },-                        modifier = Modifier.fillMaxWidth(),-                    ) { Text(stringResource(R.string.complete_payment)) }-                } else if (isCheckoutUnexpired(trip.checkoutExpiresAt)) {+                if (isCheckoutUnexpired(trip.checkoutExpiresAt)) {                     val loading = checkout is CheckoutState.Loading                     Button(-                        onClick = { viewModel.recheckoutForStoredTrip(trip.orderId) },-                        enabled = !loading,+                        onClick = {+                            val fresh = (checkout as? CheckoutState.Ready)?.checkout+                            if (fresh != null && viewModel.currentTrip?.tripId == trip.tripId.ifBlank { trip.orderId }) {+                                paying = cardPayment.present(fresh.clientSecret, fresh.publishableKey)+                            } else {+                                presentWhenReady = true+                                viewModel.recheckoutForStoredTrip(trip.orderId)+                            }+                        },+                        enabled = !loading && !paying,                         modifier = Modifier.fillMaxWidth(),                     ) { Text(stringResource(R.string.complete_payment)) }                 } else {
travel/src/main/java/com/vayunmathur/travel/ui/DateField.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/DateField.kt b/travel/src/main/java/com/vayunmathur/travel/ui/DateField.ktindex e547413e58..92824e14eb 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/DateField.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/DateField.kt@@ -49,22 +49,7 @@ fun DateField(         dateFormat(LocalDate.parse(value))     }.getOrDefault(value) -    Box(modifier) {-        OutlinedTextField(-            value = display,-            onValueChange = {},-            readOnly = true,-            enabled = false,-            label = { Text(label) },-            leadingIcon = { IconCalendar() },-            modifier = Modifier.fillMaxWidth(),-        )-        Box(-            Modifier-                .matchParentSize()-                .clickable { show = true }-        )-    }+    DateFieldBox(label, display, onClick = { show = true }, modifier = modifier)      if (show) {         val minMillis = minDate?.atStartOfDayIn(TimeZone.UTC)?.toEpochMilliseconds()@@ -97,5 +82,38 @@ fun DateField(     } } +/**+ * The tappable date field itself: a normal (not disabled-looking) read-only+ * text field with a calendar icon; the overlay takes the tap so the field+ * never focuses or raises the keyboard.+ */+@Composable+internal fun DateFieldBox(label: String, display: String, onClick: () -> Unit, modifier: Modifier = Modifier) {+    Box(modifier) {+        OutlinedTextField(+            value = display,+            onValueChange = {},+            readOnly = true,+            label = { Text(label) },+            leadingIcon = { IconCalendar() },+            singleLine = true,+            modifier = Modifier.fillMaxWidth(),+        )+        Box(+            Modifier+                .matchParentSize()+                .clickable(onClick = onClick)+        )+    }+}++/** ISO `YYYY-MM-DD` → UTC midnight millis (null when blank/invalid). */+internal fun isoToUtcMillis(iso: String): Long? =+    runCatching { LocalDate.parse(iso) }.getOrNull()?.atStartOfDayIn(TimeZone.UTC)?.toEpochMilliseconds()++/** UTC midnight millis → ISO `YYYY-MM-DD`. */+internal fun utcMillisToIso(ms: Long): String =+    Instant.fromEpochMilliseconds(ms).toLocalDateTime(TimeZone.UTC).date.toString()+ /** Today in UTC as a [LocalDate], for clamping pickers to no-past-dates. */ fun todayUtc(): LocalDate = Clock.System.now().toLocalDateTime(TimeZone.UTC).date
travel/src/main/java/com/vayunmathur/travel/ui/DateRangeFields.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/DateRangeFields.kt b/travel/src/main/java/com/vayunmathur/travel/ui/DateRangeFields.ktnew file mode 100644index 0000000000..6f185ace03--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/DateRangeFields.kt@@ -0,0 +1,85 @@+package com.vayunmathur.travel.ui++import com.vayunmathur.library.ui.R as UiR+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.DateRangePicker+import com.vayunmathur.library.ui.DatePickerDialog+import com.vayunmathur.library.ui.DateString+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.SelectableDates+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.rememberDateRangePickerState+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn++/**+ * Two side-by-side date fields (e.g. Depart / Return, Check-in / Check-out)+ * that open one range calendar: tap either to pick both dates at once. Values+ * are ISO `YYYY-MM-DD` ("" when unset); dates before [minDate] are disabled.+ * [allowSameDay] = false requires the end to be after the start (hotel nights).+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DateRangeFields(+    startLabel: String,+    endLabel: String,+    start: String,+    end: String,+    onRange: (start: String, end: String) -> Unit,+    modifier: Modifier = Modifier,+    minDate: LocalDate? = null,+    allowSameDay: Boolean = true,+) {+    var show by remember { mutableStateOf(false) }+    val display = { iso: String ->+        runCatching { DateString.dateWeekdayNoYear(LocalDate.parse(iso)) }.getOrDefault(iso)+    }+    Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+        DateFieldBox(startLabel, display(start), onClick = { show = true }, modifier = Modifier.weight(1f))+        DateFieldBox(endLabel, display(end), onClick = { show = true }, modifier = Modifier.weight(1f))+    }+    if (!show) return++    val minMillis = minDate?.atStartOfDayIn(TimeZone.UTC)?.toEpochMilliseconds()+    val selectable = remember(minMillis) {+        object : SelectableDates {+            override fun isSelectableDate(utcTimeMillis: Long): Boolean =+                minMillis == null || utcTimeMillis >= minMillis+        }+    }+    val state = rememberDateRangePickerState(+        initialSelectedStartDateMillis = isoToUtcMillis(start),+        initialSelectedEndDateMillis = isoToUtcMillis(end),+        selectableDates = selectable,+    )+    val startMs = state.selectedStartDateMillis+    val endMs = state.selectedEndDateMillis+    val complete = startMs != null && endMs != null && (allowSameDay || endMs > startMs)+    DatePickerDialog(+        onDismissRequest = { show = false },+        confirmButton = {+            TextButton(+                onClick = {+                    if (startMs != null && endMs != null) onRange(utcMillisToIso(startMs), utcMillisToIso(endMs))+                    show = false+                },+                enabled = complete,+            ) { Text(stringResource(UiR.string.ok)) }+        },+        dismissButton = { TextButton(onClick = { show = false }) { Text(stringResource(UiR.string.cancel)) } },+    ) {+        DateRangePicker(state, modifier = Modifier.weight(1f))+    }+}
travel/src/main/java/com/vayunmathur/travel/ui/ExploreBottomSheet.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/ExploreBottomSheet.kt b/travel/src/main/java/com/vayunmathur/travel/ui/ExploreBottomSheet.ktdeleted file mode 100644index b53a4bed0b..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/ExploreBottomSheet.kt+++ /dev/null@@ -1,124 +0,0 @@-package com.vayunmathur.travel.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.layout.ContentScale-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.image.compose.AsyncImage-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.ModalBottomSheet-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.rememberModalBottomSheetState-import com.vayunmathur.travel.R-import com.vayunmathur.travel.domain.exploreLiveSlices-import com.vayunmathur.travel.network.ExploreDestinationDto-import com.vayunmathur.travel.util.FlightQuery-import com.vayunmathur.travel.util.TravelViewModel-import com.vayunmathur.travel.util.searchFlights--/**- * Bottom sheet for an Explore map pin: destination header (photo, city,- * cached "from" fare with a disclaimer) then LIVE flights to that place.- * The cached explore fare is never booked; tapping a live offer reports it- * via [onOffer] (the caller runs `selectOffer` + navigates to review).- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun ExploreBottomSheet(-    destination: ExploreDestinationDto,-    request: ExploreRequest,-    viewModel: TravelViewModel,-    onDismiss: () -> Unit,-    onOffer: (com.vayunmathur.travel.network.OfferDto) -> Unit,-) {-    val flights by viewModel.flights.collectAsStateWithLifecycle()--    LaunchedEffect(destination) {-        val destCode = destination.destinationCode.ifBlank { destination.iataCode }-        val depart = destination.departDate.ifBlank { request.depart }-        val slices = exploreLiveSlices(-            origin = request.origin,-            destinationCode = destCode,-            departDate = depart,-            returnDate = destination.returnDate,-            isRoundTrip = request.tripType == "roundtrip",-        )-        viewModel.searchFlights(-            FlightQuery(-                slices = slices,-                adults = request.adults,-                children = request.children,-                infants = request.infants,-                cabin = request.cabin,-                maxConnections = request.maxConnections,-                isRoundTrip = request.tripType == "roundtrip",-            )-        )-    }--    ModalBottomSheet(-        onDismissRequest = onDismiss,-        sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),-    ) {-        LazyColumn(Modifier.fillMaxWidth().padding(bottom = 24.dp)) {-            item {-                Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {-                    Row(-                        Modifier.fillMaxWidth(),-                        verticalAlignment = Alignment.CenterVertically,-                        horizontalArrangement = Arrangement.spacedBy(12.dp),-                    ) {-                        if (destination.imageUrl.isNotBlank()) {-                            AsyncImage(-                                model = destination.imageUrl,-                                contentDescription = destination.cityName,-                                contentScale = ContentScale.Crop,-                                modifier = Modifier.size(64.dp),-                            )-                        }-                        Column(Modifier.weight(1f)) {-                            Text(destination.cityName, style = MaterialTheme.typography.titleLarge)-                            Text(-                                "${stringResource(R.string.from)} ${formatMoney(destination.lowestAmount, destination.lowestCurrency)}",-                                style = MaterialTheme.typography.titleMedium,-                                color = MaterialTheme.colorScheme.primary,-                            )-                        }-                    }-                    Text(-                        stringResource(R.string.explore_fare_note),-                        style = MaterialTheme.typography.bodySmall,-                        color = MaterialTheme.colorScheme.onSurfaceVariant,-                    )-                    Text(stringResource(R.string.explore_live_fares), style = MaterialTheme.typography.titleSmall)-                }-            }-            items(flights.visibleOffers) { offer ->-                OfferCard(offer) { onOffer(offer) }-            }-            if (flights.loading || flights.error != null || (flights.hasSearched && flights.visibleOffers.isEmpty())) {-                item {-                    StatusBox(-                        loading = flights.loading,-                        error = flights.error,-                        isEmpty = flights.hasSearched && flights.visibleOffers.isEmpty(),-                    )-                }-            }-        }-    }-}
travel/src/main/java/com/vayunmathur/travel/ui/ExploreMapPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/ExploreMapPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/ExploreMapPage.ktdeleted file mode 100644index b77f254db7..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/ExploreMapPage.kt+++ /dev/null@@ -1,136 +0,0 @@-package com.vayunmathur.travel.ui--import androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.stringResource-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.map.CameraPosition-import com.vayunmathur.library.map.GeoPoint-import com.vayunmathur.library.map.VectorMap-import com.vayunmathur.library.map.rememberCameraState-import com.vayunmathur.library.util.ConnectivityMonitor-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.travel.R-import com.vayunmathur.travel.Route-import com.vayunmathur.travel.network.ExploreDestinationDto-import com.vayunmathur.travel.util.TravelViewModel-import com.vayunmathur.travel.util.searchExplore-import com.vayunmathur.travel.util.selectOffer--/**- * Explore map: destination suggestions from `find_destination` as price pins.- * Tapping a pin opens [ExploreBottomSheet] with live flights to that place;- * tapping a live offer reports it via the normal review flow.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun ExploreMapPage(-    backStack: NavBackStack<Route>,-    viewModel: TravelViewModel,-    route: Route.Explore,-) {-    val state by viewModel.explore.collectAsStateWithLifecycle()-    var selected by remember { mutableStateOf<ExploreDestinationDto?>(null) }--    LaunchedEffect(route) {-        viewModel.searchExplore(-            origin = route.origin,-            tripType = route.tripType,-            depart = route.depart,-            returnDate = route.returnDate,-            cabin = route.cabin,-            adults = route.adults,-            children = route.children,-            infants = route.infants,-            maxConnections = route.maxConnections,-        )-    }--    val camera = rememberCameraState(-        CameraPosition(target = GeoPoint(0.0, 20.0), zoom = 1.5)-    )-    // Fit the camera on the pins once loaded.-    LaunchedEffect(state.destinations) {-        val pins = state.destinations.mapNotNull { d ->-            val lat = d.latitude-            val lng = d.longitude-            if (lat == null || lng == null) null else GeoPoint(lng, lat)-        }-        if (pins.isNotEmpty()) {-            val avgLng = pins.map { it.longitude }.average()-            val avgLat = pins.map { it.latitude }.average()-            camera.animateTo(CameraPosition(target = GeoPoint(avgLng, avgLat), zoom = 2.5))-        }-    }--    val request = remember(route) {-        ExploreRequest(-            origin = route.origin,-            tripType = route.tripType,-            depart = route.depart,-            returnDate = route.returnDate,-            cabin = route.cabin,-            adults = route.adults,-            children = route.children,-            infants = route.infants,-            maxConnections = route.maxConnections,-        )-    }--    AppScaffold(-        title = stringResource(R.string.explore_title, route.origin),-        backStack = backStack,-        scrollBehavior = appBarScrollBehavior(),-    ) { padding ->-        Box(Modifier.fillMaxSize().padding(padding)) {-            if (state.loading || state.error != null || (state.hasSearched && state.destinations.isEmpty())) {-                StatusBox(-                    loading = state.loading,-                    error = state.error,-                    isEmpty = state.hasSearched && state.destinations.isEmpty(),-                    emptyMessage = stringResource(R.string.explore_empty),-                )-            } else {-                VectorMap(cameraState = camera, online = ConnectivityMonitor.isOnline) {-                    state.destinations.forEach { dest ->-                        val lat = dest.latitude ?: return@forEach-                        val lng = dest.longitude ?: return@forEach-                        MapMarker(position = GeoPoint(lng, lat)) {-                            ExplorePricePill(-                                amount = dest.lowestAmount,-                                currency = dest.lowestCurrency,-                                modifier = Modifier.clickable { selected = dest },-                            )-                        }-                    }-                }-            }-        }-    }--    selected?.let { dest ->-        ExploreBottomSheet(-            destination = dest,-            request = request,-            viewModel = viewModel,-            onDismiss = { selected = null },-            onOffer = { offer ->-                viewModel.selectOffer(offer)-                selected = null-                backStack.add(Route.OfferReview(offer.offerId))-            },-        )-    }-}
travel/src/main/java/com/vayunmathur/travel/ui/ExplorePricePill.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/ExplorePricePill.kt b/travel/src/main/java/com/vayunmathur/travel/ui/ExplorePricePill.ktdeleted file mode 100644index 8837584e44..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/ExplorePricePill.kt+++ /dev/null@@ -1,37 +0,0 @@-package com.vayunmathur.travel.ui--import androidx.compose.foundation.layout.padding-import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Surface-import com.vayunmathur.library.ui.Text--/**- * Price pill drawn on the Explore map at a destination: the cached lowest- * fare (e.g. "$412"). Taps are handled by the caller via [Modifier.clickable]- * on this pill.- */-@Composable-fun ExplorePricePill(-    amount: String,-    currency: String,-    modifier: Modifier = Modifier,-) {-    Surface(-        shape = MaterialTheme.shapes.small,-        color = MaterialTheme.colorScheme.inverseSurface,-        contentColor = MaterialTheme.colorScheme.inverseOnSurface,-        shadowElevation = 4.dp,-        modifier = modifier,-    ) {-        Text(-            formatMoney(amount, currency),-            style = MaterialTheme.typography.labelLarge,-            fontWeight = FontWeight.SemiBold,-            modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),-        )-    }-}
travel/src/main/java/com/vayunmathur/travel/ui/ExploreRequest.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/ExploreRequest.kt b/travel/src/main/java/com/vayunmathur/travel/ui/ExploreRequest.ktdeleted file mode 100644index ae0832e118..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/ExploreRequest.kt+++ /dev/null@@ -1,18 +0,0 @@-package com.vayunmathur.travel.ui--/**- * Explore search params carried by `Route.Explore`: origin, trip shape,- * dates, cabin and party. The Explore page fetches destinations via- * `TravelApi.explore`; nothing here is bookable (pin sheet re-searches live).- */-data class ExploreRequest(-    val origin: String,-    val tripType: String,-    val depart: String,-    val returnDate: String? = null,-    val cabin: String = "economy",-    val adults: Int = 1,-    val children: String = "",-    val infants: Int = 0,-    val maxConnections: Int = -1,-)
travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.ktindex f3e56037b9..a88b658ce8 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt@@ -236,7 +236,7 @@ private fun OfferExpiryBanner(expiresAt: String, onExpired: () -> Unit) {     } } -/** A single bookable offer row; shared with the Explore pin sheet. */+/** A single bookable offer row. */ @Composable internal fun OfferCard(offer: OfferDto, onClick: () -> Unit) {     ElevatedCard(
travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt b/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.ktindex ad4a84ceed..08f252a5ce 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt@@ -10,7 +10,6 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf-import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment@@ -52,34 +51,29 @@ enum class MaxStops(val apiValue: Int, @StringRes val label: Int) {  * Flight search form (Google-Flights style): a dropdown row (trip type,  * passengers, cabin, max stops) above side-by-side From/To fields with a swap  * button, then dates. Calls [onSearch] with a normalized [FlightQuery] when- * the user taps "Search flights", or [onExplore] with the explore params when- * the To field is in Explore mode.+ * the user taps "Search flights".+ *+ * Stateless: [state] is hoisted to the home screen so the form is still+ * filled in when the user comes back. Round trips pick both dates in one+ * range calendar.  *  * Date rules: no date before today; return not before depart.  */ @Composable fun FlightSearchForm(     viewModel: TravelViewModel,+    state: FlightFormState,+    onState: (FlightFormState) -> Unit,     modifier: Modifier = Modifier,     onSearch: (FlightQuery) -> Unit,-    onExplore: (ExploreRequest) -> Unit = {}, ) {-    var tripType by remember { mutableStateOf(TripType.ROUND_TRIP) }-    var origin by remember { mutableStateOf("") }-    var destination by remember { mutableStateOf("") }-    var depart by remember { mutableStateOf("") }-    var returnDate by remember { mutableStateOf("") }-    var mix by remember { mutableStateOf(PassengerMix()) }-    var cabin by remember { mutableStateOf(Cabin.ECONOMY) }-    var maxStops by remember { mutableStateOf(MaxStops.TWO_PLUS) }-    var exploreMode by remember { mutableStateOf(false) }-    // Bumped on swap so the autocomplete fields re-init from the swapped codes-    // (they own their display text internally).+    // Bumped on swap so the autocomplete fields re-init from the swapped text+    // (they own their editing text internally).     var swapNonce by remember { mutableIntStateOf(0) }      val today = remember { todayUtc() }-    val departDate = remember(depart) { runCatching { LocalDate.parse(depart) }.getOrNull() }-    val returnLocalDate = remember(returnDate) { runCatching { LocalDate.parse(returnDate) }.getOrNull() }+    val departDate = remember(state.depart) { runCatching { LocalDate.parse(state.depart) }.getOrNull() }+    val returnLocalDate = remember(state.returnDate) { runCatching { LocalDate.parse(state.returnDate) }.getOrNull() }      Column(modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {         Row(@@ -88,23 +82,23 @@ fun FlightSearchForm(             verticalAlignment = Alignment.CenterVertically,         ) {             SearchDropdown(-                display = stringResource(tripType.label),+                display = stringResource(state.tripType.label),                 options = TripType.entries.map { it.name to stringResource(it.label) },-                selectedValue = tripType.name,-                onSelect = { name -> tripType = TripType.valueOf(name) },+                selectedValue = state.tripType.name,+                onSelect = { name -> onState(state.copy(tripType = TripType.valueOf(name))) },             )-            PassengerField(mix = mix, onMix = { mix = it })+            PassengerField(mix = state.mix, onMix = { onState(state.copy(mix = it)) })             SearchDropdown(-                display = stringResource(cabin.label),+                display = stringResource(state.cabin.label),                 options = Cabin.entries.map { it.name to stringResource(it.label) },-                selectedValue = cabin.name,-                onSelect = { name -> cabin = Cabin.valueOf(name) },+                selectedValue = state.cabin.name,+                onSelect = { name -> onState(state.copy(cabin = Cabin.valueOf(name))) },             )             SearchDropdown(-                display = stringResource(maxStops.label),+                display = stringResource(state.maxStops.label),                 options = MaxStops.entries.map { it.name to stringResource(it.label) },-                selectedValue = maxStops.name,-                onSelect = { name -> maxStops = MaxStops.valueOf(name) },+                selectedValue = state.maxStops.name,+                onSelect = { name -> onState(state.copy(maxStops = MaxStops.valueOf(name))) },             )         } @@ -117,89 +111,60 @@ fun FlightSearchForm(                 PlaceAutocompleteField(                     "From",                     viewModel,-                    onCodeChange = { origin = it },+                    onChange = { code, text -> onState(state.copy(origin = code, originText = text)) },                     modifier = Modifier.weight(1f),-                    initialText = origin,+                    initialText = state.originText.ifBlank { state.origin },                 )             }             IconButton(onClick = {-                val o = origin-                origin = destination-                destination = o-                exploreMode = false+                onState(state.swapped())                 swapNonce++             }) { IconSwapLanguages() }             androidx.compose.runtime.key(swapNonce) {                 PlaceAutocompleteField(                     "To",                     viewModel,-                    onCodeChange = {-                        destination = it-                        // Typing a code exits Explore mode.-                        if (it.isNotBlank()) exploreMode = false-                    },+                    onChange = { code, text -> onState(state.copy(destination = code, destinationText = text)) },                     modifier = Modifier.weight(1f),-                    initialText = destination,-                    showExploreRow = true,-                    onExploreSelected = {-                        destination = ""-                        exploreMode = true-                    },+                    initialText = state.destinationText.ifBlank { state.destination },                 )             }         } -        Row(-            Modifier.fillMaxWidth(),-            horizontalArrangement = Arrangement.spacedBy(8.dp),-        ) {+        if (state.tripType == TripType.ROUND_TRIP) {+            DateRangeFields(+                startLabel = stringResource(R.string.depart),+                endLabel = stringResource(R.string.return_label),+                start = state.depart,+                end = state.returnDate,+                onRange = { start, end -> onState(state.copy(depart = start, returnDate = end)) },+                minDate = today,+            )+        } else {             DateField(                 stringResource(R.string.depart),-                depart,-                onDate = { depart = it },-                modifier = Modifier.weight(1f),+                state.depart,+                onDate = { onState(state.copy(depart = it)) },+                modifier = Modifier.fillMaxWidth(),                 minDate = today,             )-            if (tripType == TripType.ROUND_TRIP) {-                DateField(-                    stringResource(R.string.return_label),-                    returnDate,-                    onDate = { returnDate = it },-                    modifier = Modifier.weight(1f),-                    minDate = departDate ?: today,-                )-            }         }          val departValid = departDate != null && departDate >= today-        val returnValid = tripType == TripType.ONE_WAY ||+        val returnValid = state.tripType == TripType.ONE_WAY ||             (returnLocalDate != null && departDate != null && returnLocalDate >= departDate)-        val valid = origin.isNotBlank() && (destination.isNotBlank() || exploreMode) && departValid && returnValid+        val valid = state.origin.isNotBlank() && state.destination.isNotBlank() && departValid && returnValid          Button(             onClick = {+                val mix = state.mix                 // Infants in seats fly as children (age 1) so they hold a seat;                 // infants on lap use the infant bucket.                 val childAges = mix.childAges + List(mix.infantsInSeat) { 1 }-                if (exploreMode) {-                    onExplore(-                        ExploreRequest(-                            origin = origin,-                            tripType = if (tripType == TripType.ROUND_TRIP) "roundtrip" else "oneway",-                            depart = depart,-                            returnDate = returnDate.takeIf { tripType == TripType.ROUND_TRIP },-                            cabin = cabin.code,-                            adults = mix.adults,-                            children = childAges.joinToString(","),-                            infants = mix.infantsOnLap,-                            maxConnections = maxStops.apiValue,-                        )-                    )-                    return@Button-                }-                val slices = when (tripType) {-                    TripType.ROUND_TRIP -> "$origin:$destination:$depart,$destination:$origin:$returnDate"-                    TripType.ONE_WAY -> "$origin:$destination:$depart"+                val (origin, destination) = state.origin to state.destination+                val slices = when (state.tripType) {+                    TripType.ROUND_TRIP -> "$origin:$destination:${state.depart},$destination:$origin:${state.returnDate}"+                    TripType.ONE_WAY -> "$origin:$destination:${state.depart}"                 }                 onSearch(                     FlightQuery(@@ -207,14 +172,14 @@ fun FlightSearchForm(                         adults = mix.adults,                         children = childAges.joinToString(","),                         infants = mix.infantsOnLap,-                        cabin = cabin.code,-                        maxConnections = maxStops.apiValue,-                        isRoundTrip = tripType == TripType.ROUND_TRIP,+                        cabin = state.cabin.code,+                        maxConnections = state.maxStops.apiValue,+                        isRoundTrip = state.tripType == TripType.ROUND_TRIP,                     )                 )             },             enabled = valid,             modifier = Modifier.fillMaxWidth(),-        ) { Text(stringResource(if (exploreMode) R.string.explore_search else R.string.search_flights)) }+        ) { Text(stringResource(R.string.search_flights)) }     } }
travel/src/main/java/com/vayunmathur/travel/ui/HomePage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/HomePage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/HomePage.ktindex e2d250d264..966a34d684 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/HomePage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/HomePage.kt@@ -15,6 +15,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -24,15 +25,17 @@ import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.ElevatedCard import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconFlight+import com.vayunmathur.library.ui.IconHotel import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedCard import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.BottomNavBar+import com.vayunmathur.library.util.BottomNavBarItem import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route import com.vayunmathur.travel.data.BookedTrip@@ -43,14 +46,21 @@ import androidx.compose.ui.res.stringResource import androidx.annotation.StringRes import com.vayunmathur.travel.R -private enum class Product(@StringRes val label: Int) { FLIGHTS(R.string.flights), STAYS(R.string.stays) }+private enum class Product(@StringRes val label: Int, val icon: @Composable () -> Unit) {+    FLIGHTS(R.string.flights, { IconFlight() }),+    STAYS(R.string.stays, { IconHotel() }),+}  @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) {     val recents by viewModel.recentSearches.collectAsStateWithLifecycle()     val trips by viewModel.bookedTrips.collectAsStateWithLifecycle()-    var product by remember { mutableStateOf(Product.FLIGHTS) }+    var product by rememberSaveable { mutableStateOf(Product.FLIGHTS) }+    // Hoisted (and saved) so both forms are still filled in when the user+    // comes back from results or switches tabs.+    var flightForm by rememberSaveable(stateSaver = FlightFormSaver) { mutableStateOf(FlightFormState()) }+    var stayForm by rememberSaveable(stateSaver = StayFormSaver) { mutableStateOf(StayFormState()) }      AppScaffold(         title = stringResource(R.string.app_name),@@ -63,6 +73,18 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) {             }         },         scrollBehavior = appBarScrollBehavior(),+        bottomBar = {+            BottomNavBar {+                Product.entries.forEach { p ->+                    BottomNavBarItem(+                        selected = product == p,+                        onClick = { product = p },+                        icon = p.icon,+                        label = stringResource(p.label),+                    )+                }+            }+        },     ) { padding ->         Column(             Modifier@@ -70,18 +92,12 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) {                 .padding(padding)                 .verticalScroll(rememberScrollState()),         ) {-            Row(-                Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),-                horizontalArrangement = Arrangement.spacedBy(8.dp),-            ) {-                Product.entries.forEach { p ->-                    FilterChip(selected = product == p, onClick = { product = p }, label = { Text(stringResource(p.label)) })-                }-            }              when (product) {                 Product.FLIGHTS -> FlightSearchForm(                     viewModel,+                    state = flightForm,+                    onState = { flightForm = it },                     onSearch = { query ->                         if (query.isRoundTrip) {                             backStack.add(@@ -107,23 +123,8 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) {                             )                         }                     },-                    onExplore = { explore ->-                        backStack.add(-                            Route.Explore(-                                origin = explore.origin,-                                tripType = explore.tripType,-                                depart = explore.depart,-                                returnDate = explore.returnDate,-                                cabin = explore.cabin,-                                adults = explore.adults,-                                children = explore.children,-                                infants = explore.infants,-                                maxConnections = explore.maxConnections,-                            )-                        )-                    },                 )-                Product.STAYS -> StaySearchForm(viewModel) { place, checkIn, checkOut, rooms, adults, lat, lng ->+                Product.STAYS -> StaySearchForm(viewModel, stayForm, { stayForm = it }) { place, checkIn, checkOut, rooms, adults, lat, lng ->                     backStack.add(                         Route.StayResults(                             place = place,
travel/src/main/java/com/vayunmathur/travel/ui/OfferReviewPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/OfferReviewPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/OfferReviewPage.ktindex 3d42198df2..4a50aa0fa3 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/OfferReviewPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/OfferReviewPage.kt@@ -51,10 +51,9 @@ fun OfferReviewPage( ) {     val review by viewModel.review.collectAsStateWithLifecycle() -    // The offer is seeded by the results screen; only re-read it from the-    // server when there is nothing in memory (process-death restore).+    // Always re-verify: the review screen shows the guaranteed price, not the search price.     LaunchedEffect(route.offerId) {-        if (review.offer?.offerId != route.offerId) viewModel.refreshOffer(route.offerId)+        viewModel.refreshOffer(route.offerId)     }     LaunchedEffect(Unit) {         viewModel.loadAircraft()@@ -148,7 +147,8 @@ fun OfferReviewPage(                     viewModel.initPassengers(offer)                     backStack.add(Route.Passengers(offer.offerId))                 },-                enabled = !review.loading,+                // A fare that failed verification can't be prebooked either.+                enabled = !review.loading && review.error == null,                 modifier = Modifier.fillMaxWidth(),             ) { Text(stringResource(R.string.continue_action)) }         }
travel/src/main/java/com/vayunmathur/travel/ui/OrderDetailPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/OrderDetailPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/OrderDetailPage.ktindex 526134ccb1..60cdde0aa7 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/OrderDetailPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/OrderDetailPage.kt@@ -11,7 +11,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle@@ -28,7 +27,6 @@ import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route import com.vayunmathur.travel.domain.isCheckoutUnexpired-import com.vayunmathur.travel.intents.openCheckout import com.vayunmathur.travel.network.OrderDetailDto import com.vayunmathur.travel.network.SliceDto import com.vayunmathur.travel.util.CheckoutState@@ -37,8 +35,6 @@ import com.vayunmathur.travel.util.OrderDetailUiState import com.vayunmathur.travel.util.TravelViewModel import com.vayunmathur.travel.util.acceptNewPrice import com.vayunmathur.travel.util.loadBookingDetail-import com.vayunmathur.travel.util.pollTrip-import com.vayunmathur.travel.util.recheckoutForStoredTrip import com.vayunmathur.travel.util.refreshBookingDetail import androidx.compose.ui.res.stringResource @@ -52,7 +48,6 @@ fun OrderDetailPage(     val state by viewModel.orderDetail.collectAsStateWithLifecycle()     val trips by viewModel.bookedTrips.collectAsStateWithLifecycle()     val checkout by viewModel.checkout.collectAsStateWithLifecycle()-    val context = LocalContext.current     val stored = trips.find { it.orderId == route.orderId }      LaunchedEffect(route.orderId) {@@ -62,17 +57,9 @@ fun OrderDetailPage(     val actions = remember(viewModel, backStack, route) {         object : OrderDetailActions {             override fun refresh() = viewModel.refreshBookingDetail(route.orderId)+            // The confirmation screen owns the in-app payment sheet and polling.             override fun completePayment() {-                val fresh = (viewModel.checkout.value as? CheckoutState.Ready)?.checkout-                if (fresh != null) {-                    openCheckout(context, fresh.checkoutUrl)-                    // The payment result lands on the trip: show confirmation,-                    // which polls to the final status.-                    backStack.add(Route.Confirmation(route.orderId))-                    viewModel.pollTrip(stored?.tripId?.ifBlank { route.orderId } ?: route.orderId)-                } else {-                    viewModel.recheckoutForStoredTrip(route.orderId)-                }+                backStack.add(Route.Confirmation(route.orderId))             }             override fun acceptNewPrice() = viewModel.acceptNewPrice()             override fun openChange(orderId: String) = backStack.add(Route.Change(orderId))
travel/src/main/java/com/vayunmathur/travel/ui/OutboundFlightCard.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/OutboundFlightCard.kt b/travel/src/main/java/com/vayunmathur/travel/ui/OutboundFlightCard.ktnew file mode 100644index 0000000000..c7c2499037--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/OutboundFlightCard.kt@@ -0,0 +1,158 @@+package com.vayunmathur.travel.ui++import androidx.compose.ui.res.pluralStringResource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.rotate+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.ExpandVisibility+import com.vayunmathur.library.ui.IconKeyboardArrowDown+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.animatedColor+import com.vayunmathur.library.ui.animatedDp+import com.vayunmathur.library.ui.animatedFloat+import com.vayunmathur.library.ui.rememberIs24Hour+import com.vayunmathur.travel.R+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.SliceDto++/**+ * An outbound flight that expands, in place, into the return flights it can be+ * paired with (round trips are priced as fixed pairs). Same expanding-group+ * look as the contacts Groups page: the header recolors and its bottom corners+ * tighten as the attached list opens.+ *+ * @param outbound the cheapest round trip using this outbound flight.+ * @param returns the cheapest round trip per return flight for this outbound.+ */+@Composable+fun OutboundFlightCard(+    outbound: OfferDto,+    returns: List<OfferDto>,+    expanded: Boolean,+    onToggle: () -> Unit,+    onPickReturn: (OfferDto) -> Unit,+) {+    val open = expanded && returns.isNotEmpty()+    val headerColor = animatedColor(+        if (open) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceVariant+    )+    val bottomRadius = animatedDp(if (open) 4.dp else 16.dp)+    Column {+        Surface(+            onClick = onToggle,+            modifier = Modifier.fillMaxWidth(),+            shape = RoundedCornerShape(16.dp, 16.dp, bottomRadius, bottomRadius),+            color = headerColor,+        ) {+            ListItem(+                content = {+                    outbound.slices.firstOrNull()?.let { LegLines(it, outbound.owner) }+                },+                supportingContent = {+                    Text(pluralStringResource(R.plurals.return_flight_options, returns.size, returns.size))+                },+                leadingContent = { AirlineLogo(outbound.ownerLogoUrl, outbound.ownerIata) },+                trailingContent = {+                    Column(horizontalAlignment = Alignment.End) {+                        RoundTripPrice(outbound, from = true)+                        IconKeyboardArrowDown(Modifier.rotate(animatedFloat(if (open) 180f else 0f)))+                    }+                },+                colors = ListItemDefaults.colors(containerColor = Color.Transparent),+            )+        }+        // The 2dp gap belongs to the expanding block so it disappears with it.+        ExpandVisibility(visible = open) {+            Column {+                Spacer(Modifier.height(2.dp))+                Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+                returns.forEachIndexed { i, offer ->+                    Surface(+                        onClick = { onPickReturn(offer) },+                        modifier = Modifier.fillMaxWidth(),+                        shape = attachedShape(i, returns.size),+                        color = MaterialTheme.colorScheme.surfaceContainerHighest,+                    ) {+                        ListItem(+                            content = {+                                offer.slices.getOrNull(1)?.let { LegLines(it, offer.slices[1].segments.firstOrNull()?.carrier.orEmpty()) }+                            },+                            leadingContent = { AirlineLogo("", offer.slices.getOrNull(1)?.segments?.firstOrNull()?.carrierIata.orEmpty()) },+                            trailingContent = { RoundTripPrice(offer, from = false) },+                            colors = ListItemDefaults.colors(containerColor = Color.Transparent),+                        )+                    }+                }+                }+            }+        }+    }+}++/** Carrier, route + times, then stops · duration for one leg. */+@Composable+internal fun LegLines(slice: SliceDto, carrier: String) {+    val is24 = rememberIs24Hour()+    Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+        if (carrier.isNotBlank()) {+            Text(carrier, style = MaterialTheme.typography.titleSmall)+        }+        Text(+            "${slice.origin} → ${slice.destination}  ·  ${formatTime(slice.departureAt, is24)} – ${formatTime(slice.arrivalAt, is24)}",+            style = MaterialTheme.typography.bodyMedium,+        )+        Text(+            listOf(stopsLabel(slice.stops), formatDuration(slice.durationMinutes))+                .filter { it.isNotBlank() }.joinToString(" · "),+            style = MaterialTheme.typography.bodySmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+    }+}++/** Round-trip total, optionally as a "from" (cheapest) price. */+@Composable+internal fun RoundTripPrice(offer: OfferDto, from: Boolean) {+    Column(horizontalAlignment = Alignment.End) {+        if (from) {+            Text(+                stringResource(R.string.from),+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+        Text(+            formatMoney(offer.totalAmount, offer.currency),+            style = MaterialTheme.typography.titleMedium,+            color = MaterialTheme.colorScheme.primary,+            fontWeight = FontWeight.SemiBold,+        )+        Text(+            stringResource(R.string.round_trip),+            style = MaterialTheme.typography.labelSmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+    }+}++/** Rows attached under the header: flat top on the first, rounded bottom on the last. */+private fun attachedShape(index: Int, size: Int, outer: Dp = 16.dp, inner: Dp = 4.dp): RoundedCornerShape {+    val bottom = if (index == size - 1) outer else inner+    return RoundedCornerShape(inner, inner, bottom, bottom)+}
travel/src/main/java/com/vayunmathur/travel/ui/PartialOffersPages.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/PartialOffersPages.kt b/travel/src/main/java/com/vayunmathur/travel/ui/PartialOffersPages.ktindex eddb8d1e0d..1428325b16 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/PartialOffersPages.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/PartialOffersPages.kt@@ -7,18 +7,18 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.ui.AssistChip-import com.vayunmathur.library.ui.rememberIs24Hour import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.ElevatedCard import com.vayunmathur.library.ui.ExperimentalMaterial3Api@@ -30,21 +30,24 @@ import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route+import com.vayunmathur.travel.domain.groupInboundSlices+import com.vayunmathur.travel.domain.groupOutboundSlices import com.vayunmathur.travel.domain.sliceSignature import com.vayunmathur.travel.network.OfferDto import com.vayunmathur.travel.util.FlightQuery+import com.vayunmathur.travel.util.PartialFlowState import com.vayunmathur.travel.util.TravelViewModel import com.vayunmathur.travel.util.loadPartialFares-import com.vayunmathur.travel.util.loadPartialReturn import com.vayunmathur.travel.util.selectOffer-import com.vayunmathur.travel.util.selectOffers import com.vayunmathur.travel.util.startPartialSearch import androidx.compose.ui.res.stringResource  /**- * Round-trip step 1: pick the outbound flight. One synchronous search, grouped- * on-device by distinct outbound slice (cheapest price per row).+ * Round-trip step 1: pick the flights. One synchronous search; each outbound+ * flight is a card that expands into the return flights it pairs with (round+ * trips are priced as fixed pairs). Picking a return moves on to the fares.  */+@OptIn(ExperimentalMaterial3Api::class) @Composable fun OutboundSelectPage(     backStack: NavBackStack<Route>,@@ -64,37 +67,42 @@ fun OutboundSelectPage(             )         )     }-    PartialLegScaffold(-        title = stringResource(R.string.choose_outbound),-        subtitle = stringResource(R.string.step_1_of_3),-        backStack = backStack,-        viewModel = viewModel,-    ) { offer ->-        val signature = offer.slices.firstOrNull()?.let { sliceSignature(it) }.orEmpty()-        backStack.add(Route.ReturnSelect(signature))+    val state by viewModel.partialFlow.collectAsStateWithLifecycle()+    // Each outbound (cheapest round trip using it) with the returns it pairs with.+    val outbounds = remember(state.allOffers) {+        groupOutboundSlices(state.allOffers).map { out ->+            out to groupInboundSlices(state.allOffers, sliceSignature(out.slices[0]))+        }     }-}--/** Round-trip step 2: pick the return flight for the chosen outbound. */-@Composable-fun ReturnSelectPage(-    backStack: NavBackStack<Route>,-    viewModel: TravelViewModel,-    route: Route.ReturnSelect,-) {-    LaunchedEffect(route.outboundSignature) { viewModel.loadPartialReturn(route.outboundSignature) }-    PartialLegScaffold(-        title = stringResource(R.string.choose_return),-        subtitle = stringResource(R.string.step_2_of_3),+    val expanded = remember { mutableStateListOf<String>() }+    PartialScaffold(+        title = stringResource(R.string.choose_flights),+        subtitle = stringResource(R.string.step_1_of_2),         backStack = backStack,-        viewModel = viewModel,-    ) { offer ->-        val inbound = offer.slices.getOrNull(1)?.let { sliceSignature(it) }.orEmpty()-        backStack.add(Route.FareSelect(route.outboundSignature, inbound))+        state = state,+        isEmpty = outbounds.isEmpty(),+        horizontalPadding = 16.dp,+    ) {+        outbounds.forEach { (outbound, returns) ->+            val signature = sliceSignature(outbound.slices[0])+            item(key = signature) {+                OutboundFlightCard(+                    outbound = outbound,+                    returns = returns,+                    expanded = signature in expanded,+                    onToggle = { if (!expanded.remove(signature)) expanded.add(signature) },+                    onPickReturn = { offer ->+                        val inbound = offer.slices.getOrNull(1)?.let { sliceSignature(it) }.orEmpty()+                        backStack.add(Route.FareSelect(signature, inbound))+                    },+                )+            }+        }     } } -/** Round-trip step 3: pick the final fare, then continue to review. */+/** Round-trip step 2: pick the fare for the chosen outbound + return, then review. */+@OptIn(ExperimentalMaterial3Api::class) @Composable fun FareSelectPage(     backStack: NavBackStack<Route>,@@ -104,27 +112,34 @@ fun FareSelectPage(     LaunchedEffect(route.outboundSignature, route.inboundSignature) {         viewModel.loadPartialFares(route.outboundSignature, route.inboundSignature)     }-    PartialLegScaffold(+    val state by viewModel.partialFlow.collectAsStateWithLifecycle()+    PartialScaffold(         title = stringResource(R.string.choose_fare),-        subtitle = stringResource(R.string.step_3_of_3),+        subtitle = stringResource(R.string.step_2_of_2),         backStack = backStack,-        viewModel = viewModel,-    ) { offer ->-        viewModel.selectOffer(offer)-        backStack.add(Route.OfferReview(offer.offerId))+        state = state,+        isEmpty = state.offers.isEmpty(),+    ) {+        items(state.offers) { offer ->+            FareCard(offer) {+                viewModel.selectOffer(offer)+                backStack.add(Route.OfferReview(offer.offerId))+            }+        }     } }  @OptIn(ExperimentalMaterial3Api::class) @Composable-private fun PartialLegScaffold(+private fun PartialScaffold(     title: String,     subtitle: String,     backStack: NavBackStack<Route>,-    viewModel: TravelViewModel,-    onSelect: (OfferDto) -> Unit,+    state: PartialFlowState,+    isEmpty: Boolean,+    horizontalPadding: androidx.compose.ui.unit.Dp = 0.dp,+    content: LazyListScope.() -> Unit, ) {-    val state by viewModel.partialFlow.collectAsStateWithLifecycle()     LazyListScaffold(         topBar = {             TopAppBar(@@ -141,15 +156,17 @@ private fun PartialLegScaffold(                 navigationIcon = { IconNavigation(backStack) },             )         },+        horizontalPadding = horizontalPadding,+        verticalArrangement = Arrangement.spacedBy(8.dp),         scrollBehavior = appBarScrollBehavior(),     ) {-        items(state.offers) { offer -> PartialOfferCard(offer) { onSelect(offer) } }-        if (state.loading || state.error != null || state.offers.isEmpty()) {+        content()+        if (state.loading || state.error != null || isEmpty) {             item {                 StatusBox(                     loading = state.loading,                     error = state.error,-                    isEmpty = !state.loading && state.error == null && state.offers.isEmpty(),+                    isEmpty = !state.loading && state.error == null && isEmpty,                     emptyMessage = stringResource(R.string.no_flights_for_leg),                 )             }@@ -157,13 +174,13 @@ private fun PartialLegScaffold(     } } +/** One fare for a chosen outbound + return: both legs, fare brand, exact total. */ @Composable-private fun PartialOfferCard(offer: OfferDto, onClick: () -> Unit) {-    val is24 = rememberIs24Hour()+private fun FareCard(offer: OfferDto, onClick: () -> Unit) {     ElevatedCard(         modifier = Modifier             .fillMaxWidth()-            .padding(horizontal = 16.dp, vertical = 4.dp)+            .padding(horizontal = 16.dp)             .clickable { onClick() },     ) {         Row(@@ -172,33 +189,15 @@ private fun PartialOfferCard(offer: OfferDto, onClick: () -> Unit) {             horizontalArrangement = Arrangement.spacedBy(12.dp),         ) {             AirlineLogo(offer.ownerLogoUrl, offer.ownerIata)-            Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {-                Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {-                    Text(offer.owner.ifBlank { stringResource(R.string.flight) }, style = MaterialTheme.typography.titleMedium)-                    if (offer.fareBrand.isNotBlank()) {-                        AssistChip(onClick = {}, label = { Text(offer.fareBrand) })-                    }+            Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                if (offer.fareBrand.isNotBlank()) {+                    AssistChip(onClick = {}, label = { Text(offer.fareBrand) })                 }                 offer.slices.forEach { slice ->-                    val times = "${formatTime(slice.departureAt, is24)} – ${formatTime(slice.arrivalAt, is24)}"-                    Text(-                        "${slice.origin} → ${slice.destination}  ·  $times",-                        style = MaterialTheme.typography.bodyMedium,-                    )-                    Text(-                        listOf(stopsLabel(slice.stops), formatDuration(slice.durationMinutes))-                            .filter { it.isNotBlank() }.joinToString(" · "),-                        style = MaterialTheme.typography.bodySmall,-                        color = MaterialTheme.colorScheme.onSurfaceVariant,-                    )+                    LegLines(slice, slice.segments.firstOrNull()?.carrier.orEmpty())                 }             }-            Text(-                formatMoney(offer.totalAmount, offer.currency),-                style = MaterialTheme.typography.titleMedium,-                color = MaterialTheme.colorScheme.primary,-                fontWeight = FontWeight.SemiBold,-            )+            RoundTripPrice(offer, from = false)         }     } }
travel/src/main/java/com/vayunmathur/travel/ui/PaymentPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/PaymentPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/PaymentPage.ktindex 496aebdd16..4d1ab1647b 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/PaymentPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/PaymentPage.kt@@ -11,9 +11,11 @@ import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle@@ -28,21 +30,23 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route-import com.vayunmathur.travel.intents.openCheckout+import com.vayunmathur.travel.platform.CardPaymentResult+import com.vayunmathur.travel.platform.rememberCardPayment import com.vayunmathur.travel.util.CheckoutState import com.vayunmathur.travel.util.TravelViewModel import com.vayunmathur.travel.util.acceptNewPrice-import com.vayunmathur.travel.util.pollTrip+import com.vayunmathur.travel.util.confirmPaidTrip import com.vayunmathur.travel.util.startCheckout import androidx.compose.ui.res.stringResource  /**- * Hosted-checkout screen: shows the checkout total (and the original vs new- * price when it changed, requiring an explicit accept), then "Pay securely"- * opens the checkout URL in a Custom Tab. The trip is persisted as- * pending_payment before leaving; on return the app polls to confirmation.+ * Checkout screen: shows the total (and the original vs new price when it+ * changed, requiring an explicit accept), then "Pay securely" opens the+ * in-app card sheet. On success the trip is confirmed server-side and the app+ * moves to the confirmation screen, which polls to the final status.  */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -53,7 +57,19 @@ fun PaymentPage( ) {     val review by viewModel.review.collectAsStateWithLifecycle()     val checkout by viewModel.checkout.collectAsStateWithLifecycle()-    val context = LocalContext.current+    var paying by remember { mutableStateOf(false) }+    val cardPayment = rememberCardPayment { result ->+        paying = false+        val tripId = viewModel.currentTrip?.tripId.orEmpty()+        when (result) {+            CardPaymentResult.Completed -> if (tripId.isNotBlank()) {+                viewModel.confirmPaidTrip(tripId)+                backStack.add(Route.Confirmation(tripId))+            }+            CardPaymentResult.Canceled -> Unit+            is CardPaymentResult.Failed -> AppMessages.show(result.message)+        }+    }      LaunchedEffect(Unit) {         if (checkout is CheckoutState.Idle) viewModel.startCheckout()@@ -119,15 +135,13 @@ fun PaymentPage(                 ) { Text(stringResource(UiR.string.retry)) }             } -            val payEnabled = ready != null && !loading &&+            val payEnabled = ready != null && !loading && !paying &&                 (!ready.priceChanged || accepted)             Button(                 onClick = {-                    val url = ready?.checkoutUrl.orEmpty()-                    val tripId = viewModel.currentTrip?.tripId.orEmpty()-                    openCheckout(context, url)-                    if (tripId.isNotBlank()) viewModel.pollTrip(tripId)-                    if (tripId.isNotBlank()) backStack.add(Route.Confirmation(tripId))+                    val r = ready ?: return@Button+                    paying = cardPayment.present(r.clientSecret, r.publishableKey)+                    if (!paying) AppMessages.show("Payment is unavailable right now. Please try again.")                 },                 enabled = payEnabled,                 modifier = Modifier.fillMaxWidth(),
travel/src/main/java/com/vayunmathur/travel/ui/PlaceAutocompleteField.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/PlaceAutocompleteField.kt b/travel/src/main/java/com/vayunmathur/travel/ui/PlaceAutocompleteField.ktnew file mode 100644index 0000000000..612ada6d26--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/PlaceAutocompleteField.kt@@ -0,0 +1,135 @@+package com.vayunmathur.travel.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.style.TextOverflow+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.ExposedDropdownMenu+import com.vayunmathur.library.ui.ExposedDropdownMenuAnchorType+import com.vayunmathur.library.ui.ExposedDropdownMenuBox+import com.vayunmathur.library.ui.IconFlight+import com.vayunmathur.library.ui.IconApartment+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.travel.network.PlaceDto+import com.vayunmathur.travel.util.TravelViewModel+import com.vayunmathur.travel.util.autocomplete++private const val MAX_SUGGESTIONS = 6++/**+ * Airport/city autocomplete field using the shared exposed dropdown menu.+ * Owns its editing text (seeded from [initialText]). [onChange] reports the+ * code to search — the IATA / city code when a suggestion is picked, or the+ * raw typed text as a fallback so power users can type "LON" — together with+ * the visible text, so a hoisted form can restore the field as it was.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun PlaceAutocompleteField(+    label: String,+    viewModel: TravelViewModel,+    onChange: (code: String, text: String) -> Unit,+    modifier: Modifier = Modifier,+    initialText: String = "",+) {+    var text by remember { mutableStateOf(initialText) }+    var suggestions by remember { mutableStateOf<List<PlaceDto>>(emptyList()) }+    var expanded by remember { mutableStateOf(false) }+    // Restoring the saved text must not pop the suggestion menu open.+    var justSelected by remember { mutableStateOf(initialText.isNotBlank()) }++    LaunchedEffect(text) {+        if (justSelected) {+            justSelected = false+            return@LaunchedEffect+        }+        if (text.length < 2) {+            suggestions = emptyList()+            return@LaunchedEffect+        }+        kotlinx.coroutines.delay(100)+        suggestions = viewModel.autocomplete(text).take(MAX_SUGGESTIONS)+        expanded = suggestions.isNotEmpty()+    }++    ExposedDropdownMenuBox(+        expanded = expanded && suggestions.isNotEmpty(),+        onExpandedChange = { expanded = it && suggestions.isNotEmpty() },+        modifier = modifier,+    ) {+        OutlinedTextField(+            value = text,+            onValueChange = {+                text = it+                onChange(it.trim(), it)+            },+            label = { Text(label) },+            singleLine = true,+            keyboardOptions = KeyboardOptions(+                keyboardType = KeyboardType.Ascii,+                capitalization = KeyboardCapitalization.Characters,+            ),+            modifier = Modifier+                .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable)+                .fillMaxWidth(),+        )+        ExposedDropdownMenu(+            expanded = expanded && suggestions.isNotEmpty(),+            onDismissRequest = { expanded = false },+        ) {+            suggestions.forEach { place ->+                DropdownMenuItem(+                    text = { PlaceSuggestion(place) },+                    leadingIcon = { if (place.type == "city") IconApartment() else IconFlight() },+                    onClick = {+                        text = "${place.code} · ${place.city.ifBlank { place.name }}"+                        onChange(place.code, text)+                        justSelected = true+                        suggestions = emptyList()+                        expanded = false+                    },+                )+            }+        }+    }+}++/** Two-line row: code + city on top, airport name / country underneath. */+@Composable+private fun PlaceSuggestion(place: PlaceDto) {+    Column {+        Text(+            listOf(place.code, place.city.ifBlank { place.name }).filter { it.isNotBlank() }.joinToString(" · "),+            style = MaterialTheme.typography.bodyLarge,+            fontWeight = FontWeight.SemiBold,+            maxLines = 1,+            overflow = TextOverflow.Ellipsis,+        )+        val detail = listOf(place.name.takeIf { it != place.city && it != place.code }, place.country)+            .filterNot { it.isNullOrBlank() }+            .joinToString(", ")+        if (detail.isNotBlank()) {+            Text(+                detail,+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                maxLines = 2,+                overflow = TextOverflow.Ellipsis,+            )+        }+    }+}
travel/src/main/java/com/vayunmathur/travel/ui/SearchFormState.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/SearchFormState.kt b/travel/src/main/java/com/vayunmathur/travel/ui/SearchFormState.ktnew file mode 100644index 0000000000..993ae2cfbc--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/SearchFormState.kt@@ -0,0 +1,93 @@+package com.vayunmathur.travel.ui++import androidx.compose.runtime.saveable.Saver+import androidx.compose.runtime.saveable.listSaver++/**+ * Everything the flight search form shows, hoisted to the home screen so it is+ * still filled in after coming back from results (and across tab switches).+ * [originText]/[destinationText] are the visible field text (e.g.+ * "JFK · New York"); [origin]/[destination] are the codes searched.+ */+data class FlightFormState(+    val tripType: TripType = TripType.ROUND_TRIP,+    val origin: String = "",+    val originText: String = "",+    val destination: String = "",+    val destinationText: String = "",+    val depart: String = "",+    val returnDate: String = "",+    val mix: PassengerMix = PassengerMix(),+    val cabin: Cabin = Cabin.ECONOMY,+    val maxStops: MaxStops = MaxStops.TWO_PLUS,+) {+    fun swapped() = copy(+        origin = destination,+        originText = destinationText,+        destination = origin,+        destinationText = originText,+    )+}++/** Stay search form state, hoisted like [FlightFormState]. */+data class StayFormState(+    val place: String = "",+    val placeText: String = "",+    val latitude: Double? = null,+    val longitude: Double? = null,+    val checkIn: String = "",+    val checkOut: String = "",+    val rooms: Int = 1,+    val guests: Int = 2,+)++val FlightFormSaver: Saver<FlightFormState, Any> = listSaver(+    save = {+        listOf(+            it.tripType.name, it.origin, it.originText, it.destination, it.destinationText,+            it.depart, it.returnDate, it.mix.adults, ArrayList(it.mix.childAges),+            it.mix.infantsInSeat, it.mix.infantsOnLap, it.cabin.name, it.maxStops.name,+        )+    },+    restore = {+        @Suppress("UNCHECKED_CAST")+        FlightFormState(+            tripType = TripType.valueOf(it[0] as String),+            origin = it[1] as String,+            originText = it[2] as String,+            destination = it[3] as String,+            destinationText = it[4] as String,+            depart = it[5] as String,+            returnDate = it[6] as String,+            mix = PassengerMix(+                adults = it[7] as Int,+                childAges = it[8] as List<Int>,+                infantsInSeat = it[9] as Int,+                infantsOnLap = it[10] as Int,+            ),+            cabin = Cabin.valueOf(it[11] as String),+            maxStops = MaxStops.valueOf(it[12] as String),+        )+    },+)++val StayFormSaver: Saver<StayFormState, Any> = listSaver(+    save = {+        listOf(+            it.place, it.placeText, it.latitude ?: Double.NaN, it.longitude ?: Double.NaN,+            it.checkIn, it.checkOut, it.rooms, it.guests,+        )+    },+    restore = {+        StayFormState(+            place = it[0] as String,+            placeText = it[1] as String,+            latitude = (it[2] as Double).takeUnless(Double::isNaN),+            longitude = (it[3] as Double).takeUnless(Double::isNaN),+            checkIn = it[4] as String,+            checkOut = it[5] as String,+            rooms = it[6] as Int,+            guests = it[7] as Int,+        )+    },+)
travel/src/main/java/com/vayunmathur/travel/ui/SeatMapControls.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/SeatMapControls.kt b/travel/src/main/java/com/vayunmathur/travel/ui/SeatMapControls.ktnew file mode 100644index 0000000000..6fb50b81fe--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/SeatMapControls.kt@@ -0,0 +1,70 @@+package com.vayunmathur.travel.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+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.unit.dp+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.travel.domain.seatKey+import com.vayunmathur.travel.network.SeatElementDto++/** A passenger who needs a seat, with the label shown in the picker. */+data class SeatPassenger(val id: String, val label: String)++@Composable+internal fun SeatPassengerPicker(+    passengers: List<SeatPassenger>,+    segmentId: String,+    selectedSeats: Map<String, SeatElementDto>,+    active: String,+    onSelect: (String) -> Unit,+) {+    Row(+        Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp),+        horizontalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        passengers.forEach { p ->+            val seat = selectedSeats[seatKey(segmentId, p.id)]?.designator+            FilterChip(+                selected = p.id == active,+                onClick = { onSelect(p.id) },+                label = { Text(if (seat != null) "${p.label} · $seat" else p.label) },+            )+        }+    }+}++@Composable+internal fun SeatLegend() {+    Row(+        Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),+        horizontalArrangement = Arrangement.spacedBy(16.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        LegendSwatch(MaterialTheme.colorScheme.secondaryContainer, "Available")+        LegendSwatch(MaterialTheme.colorScheme.primary, "Selected")+        LegendSwatch(MaterialTheme.colorScheme.surfaceVariant, "Taken")+    }+}++@Composable+private fun LegendSwatch(color: Color, label: String) {+    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {+        Box(Modifier.size(16.dp).clip(RoundedCornerShape(4.dp)).background(color))+        Text(label, style = MaterialTheme.typography.bodySmall)+    }+}
travel/src/main/java/com/vayunmathur/travel/ui/SeatMapPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/SeatMapPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/SeatMapPage.ktindex e95d00b09e..653bddc416 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/SeatMapPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/SeatMapPage.kt@@ -22,7 +22,9 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip@@ -41,6 +43,10 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route+import com.vayunmathur.travel.domain.assignSeat+import com.vayunmathur.travel.domain.seatHolder+import com.vayunmathur.travel.domain.seatKey+import com.vayunmathur.travel.domain.seatedPassengers import com.vayunmathur.travel.network.SeatCabinDto import com.vayunmathur.travel.network.SeatElementDto import com.vayunmathur.travel.network.SeatRowDto@@ -101,14 +107,22 @@ fun SeatMapPage( ) {     val state by viewModel.seatMap.collectAsStateWithLifecycle()     val selectedSeats by viewModel.selectedSeats.collectAsStateWithLifecycle()+    val review by viewModel.review.collectAsStateWithLifecycle()+    val inputs by viewModel.passengers.collectAsStateWithLifecycle()+    val passengers = seatedPassengers(review.offer?.passengers.orEmpty()).mapIndexed { i, p ->+        val input = inputs.firstOrNull { it.id == p.id }+        val name = listOfNotNull(input?.givenName?.ifBlank { null }, input?.familyName?.ifBlank { null })+            .joinToString(" ")+        SeatPassenger(p.id, name.ifBlank { "Passenger ${i + 1}" })+    }      // Seat maps ride on the trip ancillaries (loaded before this screen).     LaunchedEffect(route.offerId) { viewModel.loadSeatMaps() }      val actions = remember(viewModel, backStack) {         object : SeatMapActions {-            override fun toggleSeat(segmentId: String, seat: SeatElementDto) =-                viewModel.toggleSeat(segmentId, seat)+            override fun toggleSeat(segmentId: String, passengerId: String, seat: SeatElementDto) =+                viewModel.toggleSeat(segmentId, passengerId, seat)              override fun done() = backStack.pop()             override fun back() = backStack.pop()@@ -120,9 +134,11 @@ fun SeatMapPage(         state = state,         selectedSeats = selectedSeats,         actions = actions,+        passengers = passengers,     ) } + /**  * The seat picker for one segment, with no dependency on the ViewModel or the back stack so  * it can be rendered from a `@Preview` — see `src/screenshotTest`, which is where the store@@ -135,7 +151,14 @@ fun SeatMapScreen(     state: SeatMapState,     selectedSeats: Map<String, SeatElementDto>,     actions: SeatMapActions,+    passengers: List<SeatPassenger> = emptyList(), ) {+    var activePassenger by remember(segmentId, passengers) {+        mutableStateOf(+            passengers.firstOrNull { seatKey(segmentId, it.id) !in selectedSeats }?.id+                ?: passengers.firstOrNull()?.id.orEmpty()+        )+    }     AppScaffold(         title = stringResource(R.string.choose_seats),         onNavigateBack = { actions.back() },@@ -156,8 +179,20 @@ fun SeatMapScreen(             Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()),         ) {             SeatLegend()+            if (passengers.size > 1) {+                SeatPassengerPicker(passengers, segmentId, selectedSeats, activePassenger) { activePassenger = it }+            }+            val passengerNumbers = passengers.mapIndexed { i, p -> p.id to i + 1 }.toMap()             cabins.forEach { cabin ->-                CabinView(cabin, segmentId, selectedSeats) { actions.toggleSeat(segmentId, it) }+                CabinView(cabin, segmentId, selectedSeats, passengerNumbers.takeIf { passengers.size > 1 }) { seat ->+                    actions.toggleSeat(segmentId, activePassenger, seat)+                    // Move on to the next passenger still without a seat.+                    val holder = seatHolder(selectedSeats, segmentId, seat.designator)+                    if (holder == null && passengers.size > 1) {+                        val after = assignSeat(selectedSeats, segmentId, activePassenger, seat)+                        passengers.firstOrNull { seatKey(segmentId, it.id) !in after }?.let { activePassenger = it.id }+                    }+                }             }             Button(                 onClick = { actions.done() },@@ -167,32 +202,12 @@ fun SeatMapScreen(     } } -@Composable-private fun SeatLegend() {-    Row(-        Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),-        horizontalArrangement = Arrangement.spacedBy(16.dp),-        verticalAlignment = Alignment.CenterVertically,-    ) {-        LegendSwatch(MaterialTheme.colorScheme.secondaryContainer, "Available")-        LegendSwatch(MaterialTheme.colorScheme.primary, "Selected")-        LegendSwatch(MaterialTheme.colorScheme.surfaceVariant, "Taken")-    }-}--@Composable-private fun LegendSwatch(color: Color, label: String) {-    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {-        Box(Modifier.size(16.dp).clip(RoundedCornerShape(4.dp)).background(color))-        Text(label, style = MaterialTheme.typography.bodySmall)-    }-}- @Composable private fun CabinView(     cabin: SeatCabinDto,     segmentId: String,     selectedSeats: Map<String, SeatElementDto>,+    passengerNumbers: Map<String, Int>?,     onToggle: (SeatElementDto) -> Unit, ) {     if (cabin.cabinClass.isNotBlank()) {@@ -209,7 +224,7 @@ private fun CabinView(         Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp),         verticalArrangement = Arrangement.spacedBy(GAP),     ) {-        cabin.rows.forEach { row -> SeatRowView(row, layout, segmentId, selectedSeats, onToggle) }+        cabin.rows.forEach { row -> SeatRowView(row, layout, segmentId, selectedSeats, passengerNumbers, onToggle) }     } } @@ -219,6 +234,7 @@ private fun SeatRowView(     layout: CabinLayout,     segmentId: String,     selectedSeats: Map<String, SeatElementDto>,+    passengerNumbers: Map<String, Int>?,     onToggle: (SeatElementDto) -> Unit, ) {     Row(verticalAlignment = Alignment.CenterVertically) {@@ -231,8 +247,9 @@ private fun SeatRowView(                     letters.forEach { letter ->                         val seat = elements.firstOrNull { it.isSeat && seatLetter(it.designator) == letter }                         if (seat != null) {-                            val selected = selectedSeats.containsKey("$segmentId|${seat.designator}")-                            SeatChip(seat, selected) { onToggle(seat) }+                            val holder = seatHolder(selectedSeats, segmentId, seat.designator)+                            val badge = holder?.let { passengerNumbers?.get(it) }?.let { "P$it" }+                            SeatChip(seat, holder != null, badge) { onToggle(seat) }                         } else {                             Spacer(Modifier.size(CELL))                         }@@ -247,7 +264,7 @@ private fun SeatRowView( }  @Composable-private fun SeatChip(seat: SeatElementDto, selected: Boolean, onClick: () -> Unit) {+private fun SeatChip(seat: SeatElementDto, selected: Boolean, badge: String?, onClick: () -> Unit) {     val bg = when {         selected -> MaterialTheme.colorScheme.primary         seat.available -> MaterialTheme.colorScheme.secondaryContainer@@ -277,7 +294,9 @@ private fun SeatChip(seat: SeatElementDto, selected: Boolean, onClick: () -> Uni                 textAlign = TextAlign.Center,                 fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,             )-            if (seat.available && price != null) {+            if (badge != null) {+                Text(badge, fontSize = 8.sp, color = fg, textAlign = TextAlign.Center, fontWeight = FontWeight.Bold)+            } else if (seat.available && price != null) {                 Text(price, fontSize = 8.sp, color = fg, textAlign = TextAlign.Center)             }         }
travel/src/main/java/com/vayunmathur/travel/ui/StayConfirmationPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/StayConfirmationPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/StayConfirmationPage.ktindex b4a1efc211..168bd818a7 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/StayConfirmationPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/StayConfirmationPage.kt@@ -10,9 +10,11 @@ import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle@@ -27,16 +29,21 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route import com.vayunmathur.travel.domain.isCheckoutUnexpired import com.vayunmathur.travel.domain.isTripAwaitingPayment import com.vayunmathur.travel.domain.isTripPollingStatus import com.vayunmathur.travel.domain.tripStatusLabel-import com.vayunmathur.travel.intents.openCheckout+import com.vayunmathur.travel.platform.CardPaymentResult+import com.vayunmathur.travel.platform.rememberCardPayment+import com.vayunmathur.travel.util.CheckoutState import com.vayunmathur.travel.util.TravelViewModel import com.vayunmathur.travel.util.TripPollState+import com.vayunmathur.travel.util.confirmPaidTrip import com.vayunmathur.travel.util.pollTrip+import com.vayunmathur.travel.util.recheckoutForStoredTrip import com.vayunmathur.travel.util.refreshStoredTrip import androidx.compose.ui.res.stringResource @@ -55,12 +62,28 @@ fun StayConfirmationPage(     val trips by viewModel.bookedTrips.collectAsStateWithLifecycle()     val trip = trips.find { it.orderId == route.bookingId }     val poll by viewModel.tripPoll.collectAsStateWithLifecycle()-    val stayCheckout = viewModel.stayCheckout-    val context = LocalContext.current+    val checkout by viewModel.checkout.collectAsStateWithLifecycle()+    val tripId = trip?.tripId?.ifBlank { route.bookingId } ?: route.bookingId+    var paying by remember { mutableStateOf(false) }+    var presentWhenReady by remember { mutableStateOf(false) }+    val cardPayment = rememberCardPayment { result ->+        paying = false+        when (result) {+            CardPaymentResult.Completed -> viewModel.confirmPaidTrip(tripId)+            CardPaymentResult.Canceled -> Unit+            is CardPaymentResult.Failed -> AppMessages.show(result.message)+        }+    }      LaunchedEffect(route.bookingId) {-        val id = trip?.tripId?.ifBlank { route.bookingId } ?: route.bookingId-        viewModel.pollTrip(id)+        viewModel.pollTrip(tripId)+    }++    LaunchedEffect(checkout, presentWhenReady) {+        val ready = (checkout as? CheckoutState.Ready)?.checkout ?: return@LaunchedEffect+        if (!presentWhenReady) return@LaunchedEffect+        presentWhenReady = false+        paying = cardPayment.present(ready.clientSecret, ready.publishableKey)     }      DetailScaffold(@@ -92,13 +115,25 @@ fun StayConfirmationPage(                     }                 }    

Diff truncated.