travel: update
- Commit
f596f1161857219b1e9734667563d12eb6e1ce94- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-20 22:05 UTC (4 months ago)
- Parents
14ae816
Diff
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 f34c40a4f3..18fc444c14 100644--- a/travel/src/main/java/com/vayunmathur/travel/MainActivity.kt+++ b/travel/src/main/java/com/vayunmathur/travel/MainActivity.kt@@ -17,14 +17,17 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.travel.data.BookedTripDao import com.vayunmathur.travel.data.DB_NAME-import com.vayunmathur.travel.data.FavoriteDao import com.vayunmathur.travel.data.RecentSearchDao import com.vayunmathur.travel.data.TravelDatabase-import com.vayunmathur.travel.ui.CarResultsPage+import com.vayunmathur.travel.ui.ConfirmationPage import com.vayunmathur.travel.ui.FlightResultsPage import com.vayunmathur.travel.ui.HomePage-import com.vayunmathur.travel.ui.HotelResultsPage+import com.vayunmathur.travel.ui.OfferReviewPage+import com.vayunmathur.travel.ui.PassengersPage+import com.vayunmathur.travel.ui.PaymentPage+import com.vayunmathur.travel.ui.TripsPage import com.vayunmathur.travel.util.TravelViewModel import com.vayunmathur.travel.util.TravelViewModelFactory import kotlinx.coroutines.Dispatchers@@ -34,10 +37,10 @@ import kotlinx.serialization.Serializable class MainActivity : ComponentActivity() { private lateinit var recentSearchDao: RecentSearchDao- private lateinit var favoriteDao: FavoriteDao+ private lateinit var bookedTripDao: BookedTripDao private val viewModel: TravelViewModel by viewModels {- TravelViewModelFactory(application, recentSearchDao, favoriteDao)+ TravelViewModelFactory(application, recentSearchDao, bookedTripDao) } override fun onCreate(savedInstanceState: Bundle?) {@@ -48,7 +51,7 @@ class MainActivity : ComponentActivity() { lifecycleScope.launch(Dispatchers.IO) { val db = buildDatabase<TravelDatabase>(dbName = DB_NAME) recentSearchDao = db.recentSearchDao()- favoriteDao = db.favoriteDao()+ bookedTripDao = db.bookedTripDao() withContext(Dispatchers.Main) { ready.value = true } } @@ -72,22 +75,23 @@ sealed interface Route : NavKey { val depart: String, val returnDate: String?, val adults: Int,+ val cabin: String, ) : Route @Serializable- data class HotelResults(- val location: String,- val checkin: String,- val checkout: String,- val adults: Int,- ) : Route+ data class OfferReview(val offerId: String) : Route @Serializable- data class CarResults(- val location: String,- val pickup: String,- val dropoff: String,- ) : Route+ data class Passengers(val offerId: String) : Route++ @Serializable+ data class Payment(val offerId: String) : Route++ @Serializable+ data class Confirmation(val orderId: String) : Route++ @Serializable+ data object Trips : Route } @Composable@@ -97,8 +101,11 @@ fun MainGraph(viewModel: TravelViewModel) { MainNavigation(backStack) { entry<Route.Home> { HomePage(backStack, viewModel) } entry<Route.FlightResults> { FlightResultsPage(backStack, viewModel, it) }- entry<Route.HotelResults> { HotelResultsPage(backStack, viewModel, it) }- entry<Route.CarResults> { CarResultsPage(backStack, viewModel, it) }+ entry<Route.OfferReview> { OfferReviewPage(backStack, viewModel, it) }+ entry<Route.Passengers> { PassengersPage(backStack, viewModel, it) }+ entry<Route.Payment> { PaymentPage(backStack, viewModel, it) }+ entry<Route.Confirmation> { ConfirmationPage(backStack, viewModel, it) }+ entry<Route.Trips> { TripsPage(backStack, viewModel) } } } }
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.ktnew file mode 100644index 0000000000..f20299aa29--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/data/BookedTrip.kt@@ -0,0 +1,23 @@+package com.vayunmathur.travel.data++import androidx.room.Entity+import androidx.room.PrimaryKey++/**+ * A booked flight, persisted after a successful order so it shows up under+ * "My trips" and survives restarts. Keyed by [orderId] (Duffel `ord_…`).+ * [bookingReference] is the airline PNR; [route] is a pre-rendered summary like+ * "LHR → JFK"; [passengersJson] is the JSON-encoded passenger list for detail.+ */+@Entity+data class BookedTrip(+ @PrimaryKey val orderId: String,+ val bookingReference: String,+ val route: String,+ val departDate: String,+ val amount: String,+ val currency: String,+ val passengersJson: String = "",+ val status: String = "confirmed",+ val createdAt: Long = System.currentTimeMillis(),+)
travel/src/main/java/com/vayunmathur/travel/data/Favorite.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/Favorite.kt b/travel/src/main/java/com/vayunmathur/travel/data/Favorite.ktdeleted file mode 100644index a00a34da30..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/data/Favorite.kt+++ /dev/null@@ -1,20 +0,0 @@-package com.vayunmathur.travel.data--import androidx.room.Entity-import androidx.room.PrimaryKey--/**- * An offer the user has saved. Keyed by [bookingUrl] because that uniquely- * identifies a specific offer across all verticals and makes toggling a- * favorite a simple upsert/delete-by-key.- */-@Entity-data class Favorite(- @PrimaryKey val bookingUrl: String,- val vertical: String,- val title: String,- val subtitle: String = "",- val price: Double = 0.0,- val currency: String = "usd",- val createdAt: Long = System.currentTimeMillis(),-)
travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.kt b/travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.ktindex c1af8fc88a..1644755aa1 100644--- a/travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.kt+++ b/travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.kt@@ -3,13 +3,13 @@ package com.vayunmathur.travel.data import androidx.room.Entity import androidx.room.PrimaryKey -/** The three built vertical searches persisted as recent history. */-enum class Vertical { FLIGHTS, HOTELS, CARS }+/** Recent searches are flights-only now, but the column is kept for history. */+enum class Vertical { FLIGHTS } /** * A search the user has run, kept so the Home screen can offer one-tap- * re-runs. All fields needed to rebuild the query are stored as columns- * ([origin]…[dropoff]); [label] is a pre-rendered human summary for the chip.+ * re-runs. All fields needed to rebuild the query are stored as columns;+ * [label] is a pre-rendered human summary for the chip. */ @Entity data class RecentSearch(@@ -20,11 +20,7 @@ data class RecentSearch( val destination: String? = null, val depart: String? = null, val returnDate: String? = null,- val location: String? = null,- val checkin: String? = null,- val checkout: String? = null,- val pickup: String? = null,- val dropoff: String? = null, val adults: Int = 1,+ val cabin: String = "economy", val createdAt: Long = System.currentTimeMillis(), )
travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt b/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.ktindex 2b290c1523..0dac1e846f 100644--- a/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt+++ b/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt@@ -38,25 +38,28 @@ interface RecentSearchDao { } @Dao-interface FavoriteDao {- @Query("SELECT * FROM Favorite ORDER BY createdAt DESC")- fun observeAll(): Flow<List<Favorite>>+interface BookedTripDao {+ @Query("SELECT * FROM BookedTrip ORDER BY createdAt DESC")+ fun observeAll(): Flow<List<BookedTrip>>++ @Query("SELECT * FROM BookedTrip WHERE orderId = :orderId")+ suspend fun byId(orderId: String): BookedTrip? @Upsert- suspend fun upsert(value: Favorite)+ suspend fun upsert(value: BookedTrip) - @Query("DELETE FROM Favorite WHERE bookingUrl = :bookingUrl")- suspend fun deleteByUrl(bookingUrl: String)+ @Query("DELETE FROM BookedTrip WHERE orderId = :orderId")+ suspend fun deleteById(orderId: String) } @Database(- entities = [RecentSearch::class, Favorite::class],+ entities = [RecentSearch::class, BookedTrip::class], version = 1, exportSchema = false, ) abstract class TravelDatabase : RoomDatabase() { abstract fun recentSearchDao(): RecentSearchDao- abstract fun favoriteDao(): FavoriteDao+ abstract fun bookedTripDao(): BookedTripDao companion object : DatabaseMigrations { override val migrations = emptyList<androidx.room.migration.Migration>()
travel/src/main/java/com/vayunmathur/travel/network/CarDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/CarDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/CarDto.ktdeleted file mode 100644index 31ba24ff13..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/network/CarDto.kt+++ /dev/null@@ -1,17 +0,0 @@-package com.vayunmathur.travel.network--import kotlinx.serialization.Serializable--/**- * A car-rental offer from `/api/travel/cars`. Coverage is limited upstream, so- * this is deep-link-first: [price] is often 0 (unknown) and the UI shows a- * "See prices" affordance that opens [bookingUrl].- */-@Serializable-data class CarDto(- val name: String = "",- val price: Double = 0.0,- val currency: String = "usd",- val provider: String = "",- val bookingUrl: String = "",-)
travel/src/main/java/com/vayunmathur/travel/network/FlightDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/FlightDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/FlightDto.ktdeleted file mode 100644index f7d29cd4bd..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/network/FlightDto.kt+++ /dev/null@@ -1,24 +0,0 @@-package com.vayunmathur.travel.network--import kotlinx.serialization.Serializable--/**- * A single cheapest-fare flight offer from `/api/travel/flights`.- *- * Note: Aviasales data is *cached aggregated prices* (cheapest fare seen per- * route/date), not live availability, so [price] is indicative. [bookingUrl] is- * the affiliate deep-link that opens the provider to complete the booking.- */-@Serializable-data class FlightDto(- val price: Double = 0.0,- val currency: String = "usd",- val origin: String = "",- val destination: String = "",- val departureAt: String = "",- val returnAt: String? = null,- val airline: String = "",- val flightNumber: String = "",- val transfers: Int = 0,- val bookingUrl: String = "",-)
travel/src/main/java/com/vayunmathur/travel/network/HotelDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/HotelDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/HotelDto.ktdeleted file mode 100644index 4fa93781c5..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/network/HotelDto.kt+++ /dev/null@@ -1,14 +0,0 @@-package com.vayunmathur.travel.network--import kotlinx.serialization.Serializable--/** A single hotel offer from `/api/travel/hotels`. */-@Serializable-data class HotelDto(- val name: String = "",- val stars: Int = 0,- val price: Double = 0.0,- val currency: String = "usd",- val location: String = "",- val bookingUrl: String = "",-)
travel/src/main/java/com/vayunmathur/travel/network/OfferDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/OfferDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/OfferDto.ktnew file mode 100644index 0000000000..090816293f--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/network/OfferDto.kt@@ -0,0 +1,57 @@+package com.vayunmathur.travel.network++import kotlinx.serialization.Serializable++/**+ * A single operated leg of a [SliceDto], from `/api/travel/flights`.+ */+@Serializable+data class SegmentDto(+ val carrier: String = "",+ val flightNumber: String = "",+ val origin: String = "",+ val destination: String = "",+ val departureAt: String = "",+ val arrivalAt: String = "",+)++/**+ * One slice of an itinerary (outbound or return). [stops] is the number of+ * connections (`segments.size - 1`); [durationMinutes] is the whole-slice+ * travel time.+ */+@Serializable+data class SliceDto(+ val origin: String = "",+ val destination: String = "",+ val departureAt: String = "",+ val arrivalAt: String = "",+ val durationMinutes: Long = 0,+ val stops: Long = 0,+ val segments: List<SegmentDto> = emptyList(),+)++/**+ * A bookable flight offer from `/api/travel/flights` (or refreshed via+ * `/api/travel/offer`). [totalAmount] is a decimal string (Duffel returns money+ * as strings). [offerId] is the id passed back when booking, and [expiresAt] is+ * when the offer can no longer be booked at this price.+ */+@Serializable+data class OfferDto(+ val offerId: String = "",+ val totalAmount: String = "0",+ val currency: String = "USD",+ val owner: String = "",+ val ownerIata: String = "",+ val expiresAt: String = "",+ val passengerIds: List<String> = emptyList(),+ val slices: List<SliceDto> = emptyList(),+)++/** A flight search response: the offer-request id plus the mapped offers. */+@Serializable+data class OfferSearchDto(+ val offerRequestId: String = "",+ val offers: List<OfferDto> = 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.ktnew file mode 100644index 0000000000..0b9c4be6cf--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/network/OrderDto.kt@@ -0,0 +1,46 @@+package com.vayunmathur.travel.network++import kotlinx.serialization.Serializable++/**+ * A passenger the app collects and sends when booking. [id] is the Duffel+ * passenger id carried on the offer's passenger list; [title] is `mr`/`ms`/…,+ * [gender] is `m`/`f`, [bornOn] is `YYYY-MM-DD`.+ */+@Serializable+data class PassengerInputDto(+ val id: String = "",+ val title: String = "",+ val givenName: String = "",+ val familyName: String = "",+ val bornOn: String = "",+ val gender: String = "",+ val email: String = "",+ val phoneNumber: String = "",+)++/**+ * Payment instruction. Sandbox books with `{"type":"balance"}`; live card+ * payments (deferred) would carry a card token here instead.+ */+@Serializable+data class PaymentInputDto(+ val type: String = "balance",+)++/** The order-creation body posted to `POST /api/travel/orders`. */+@Serializable+data class OrderRequestDto(+ val offerId: String = "",+ val passengers: List<PassengerInputDto> = emptyList(),+ val payment: PaymentInputDto = PaymentInputDto(),+)++/** A confirmed order returned by `POST /api/travel/orders`. */+@Serializable+data class OrderResultDto(+ val orderId: String = "",+ val bookingReference: String = "",+ val totalAmount: String = "0",+ val currency: String = "USD",+)
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 954209d4f3..26ccbc6a33 100644--- a/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt+++ b/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt@@ -5,13 +5,12 @@ import java.net.URLEncoder /** * Thin wrapper over the shared [NetworkClient] for the `/api/travel` endpoints- * on the self-hosted proxy (`api.vayunmathur.com`). The proxy holds the- * Travelpayouts token/affiliate marker server-side, so the app ships no secret;- * it just does URL construction + delegation to the Ktor client.+ * on the self-hosted proxy (`api.vayunmathur.com`). The proxy holds the Duffel+ * token server-side, so the app ships no secret; it just does URL/body+ * construction + delegation to the Ktor client. *- * Modeled after [com.vayunmathur.weather.network.WeatherApi]. Each call throws- * on network/parse failure; callers (the ViewModel) wrap in try/catch and- * surface an error state.+ * Each call throws on network/parse failure; callers (the ViewModel) wrap in+ * try/catch and surface an error state. */ object TravelApi { @@ -26,8 +25,9 @@ object TravelApi { } /**- * Cheapest fares for a route. [depart] / [ret] are `YYYY-MM-DD`; omit [ret]- * for one-way. [adults] is forwarded but ignored by the aggregated upstream.+ * Search bookable flight offers for a route. [depart] / [ret] are+ * `YYYY-MM-DD`; omit [ret] for one-way. [cabin] is one of+ * `economy`/`premium_economy`/`business`/`first`. */ suspend fun flights( origin: String,@@ -35,8 +35,8 @@ object TravelApi { depart: String, ret: String? = null, adults: Int = 1,- currency: String = "usd",- ): List<FlightDto> {+ cabin: String = "economy",+ ): OfferSearchDto { val url = buildString { append(BASE).append("/flights") append("?origin=").append(enc(origin))@@ -44,44 +44,21 @@ object TravelApi { append("&depart=").append(enc(depart)) if (!ret.isNullOrBlank()) append("&return=").append(enc(ret)) append("&adults=").append(adults)- append("¤cy=").append(enc(currency))+ append("&cabin=").append(enc(cabin)) } return NetworkClient.getJson(url) } - /** Hotel offers for a location and date range. */- suspend fun hotels(- location: String,- checkin: String,- checkout: String,- adults: Int = 2,- currency: String = "usd",- ): List<HotelDto> {- val url = buildString {- append(BASE).append("/hotels")- append("?location=").append(enc(location))- append("&checkin=").append(enc(checkin))- append("&checkout=").append(enc(checkout))- append("&adults=").append(adults)- append("¤cy=").append(enc(currency))- }- return NetworkClient.getJson(url)- }+ /** Re-price/confirm a single offer right before booking (offers expire). */+ suspend fun offer(id: String): OfferDto =+ NetworkClient.getJson("$BASE/offer?id=${enc(id)}") - /** Best-effort car-rental offers (deep-link-first; see [CarDto]). */- suspend fun cars(- location: String,- pickup: String,- dropoff: String,- currency: String = "usd",- ): List<CarDto> {- val url = buildString {- append(BASE).append("/cars")- append("?location=").append(enc(location))- append("&pickup=").append(enc(pickup))- append("&dropoff=").append(enc(dropoff))- append("¤cy=").append(enc(currency))- }- return NetworkClient.getJson(url)- }+ /** Book a selected offer. Returns the confirmed order (with a PNR). */+ suspend fun createOrder(request: OrderRequestDto): OrderResultDto =+ NetworkClient.callJson(+ url = "$BASE/orders",+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = request,+ ) }
travel/src/main/java/com/vayunmathur/travel/ui/CarResultsPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/CarResultsPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/CarResultsPage.ktdeleted file mode 100644index cb66ee5faa..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/CarResultsPage.kt+++ /dev/null@@ -1,108 +0,0 @@-package com.vayunmathur.travel.ui--import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.material.icons.Icons-import androidx.compose.material.icons.automirrored.filled.ArrowBack-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.unit.dp-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.OutlinedCard-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.travel.Route-import com.vayunmathur.travel.data.Favorite-import com.vayunmathur.travel.data.Vertical-import com.vayunmathur.travel.network.CarDto-import com.vayunmathur.travel.util.TravelViewModel-import com.vayunmathur.travel.util.openBooking--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun CarResultsPage(- backStack: NavBackStack<Route>,- viewModel: TravelViewModel,- route: Route.CarResults,-) {- val context = LocalContext.current- val state by viewModel.cars.collectAsStateWithLifecycle()- val favorites by viewModel.favorites.collectAsStateWithLifecycle()-- LaunchedEffect(route) {- viewModel.searchCars(route.location, route.pickup, route.dropoff)- }-- Scaffold(- topBar = {- TopAppBar(- title = { Text(route.location) },- navigationIcon = {- IconButton(onClick = { backStack.pop() }) {- Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")- }- },- )- },- ) { padding ->- LazyColumn(- modifier = Modifier.fillMaxSize().padding(padding),- contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp),- ) {- item {- OutlinedCard(- Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 4.dp),- ) {- Text(- "Car-rental price coverage is limited. Tap \"Book\" to see live prices " +- "and availability on the provider's site.",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(16.dp),- )- }- }- items(state.results) { car ->- val fav = favorites.any { it.bookingUrl == car.bookingUrl }- ResultCard(- title = car.name,- subtitle = car.provider,- price = car.price,- currency = car.currency,- isFavorite = fav,- onFavorite = { viewModel.toggleFavorite(car.toFavorite()) },- onBook = { openBooking(context, car.bookingUrl) },- )- }- if (state.loading || state.error != null || (state.hasSearched && state.results.isEmpty())) {- item {- StatusBox(- loading = state.loading,- error = state.error,- isEmpty = state.hasSearched && state.results.isEmpty(),- )- }- }- }- }-}--private fun CarDto.toFavorite() = Favorite(- bookingUrl = bookingUrl,- vertical = Vertical.CARS.name,- title = name,- subtitle = provider,- price = price,- currency = currency,-)
travel/src/main/java/com/vayunmathur/travel/ui/CarSearchForm.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/CarSearchForm.kt b/travel/src/main/java/com/vayunmathur/travel/ui/CarSearchForm.ktdeleted file mode 100644index 8b83dffffd..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/CarSearchForm.kt+++ /dev/null@@ -1,51 +0,0 @@-package com.vayunmathur.travel.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-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.unit.dp-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Text-import com.vayunmathur.travel.util.TravelViewModel--/**- * Car search form: pickup location + pickup/drop-off dates. Upstream car- * coverage is limited, so this is deep-link-first — the results page opens the- * affiliate provider to see live prices.- */-@Composable-fun CarSearchForm(- @Suppress("UNUSED_PARAMETER") viewModel: TravelViewModel,- modifier: Modifier = Modifier,- onSearch: (location: String, pickup: String, dropoff: String) -> Unit,-) {- var location by remember { mutableStateOf("") }- var pickup by remember { mutableStateOf("") }- var dropoff by remember { mutableStateOf("") }-- Column(modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {- OutlinedTextField(- value = location,- onValueChange = { location = it },- label = { Text("Pickup city or airport") },- singleLine = true,- modifier = Modifier.fillMaxWidth(),- )- DateField("Pickup", pickup, onDate = { pickup = it })- DateField("Drop-off", dropoff, onDate = { dropoff = it })-- Button(- onClick = { onSearch(location, pickup, dropoff) },- enabled = location.isNotBlank() && pickup.isNotBlank() && dropoff.isNotBlank(),- modifier = Modifier.fillMaxWidth(),- ) { Text("Search cars") }- }-}
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 30831f5ebd..16529a8008 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/Common.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/Common.kt@@ -8,19 +8,10 @@ import androidx.compose.foundation.layout.Row 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 androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.CalendarMonth-import androidx.compose.material.icons.filled.DirectionsCar-import androidx.compose.material.icons.filled.Favorite-import androidx.compose.material.icons.filled.FavoriteBorder-import androidx.compose.material.icons.filled.Flight-import androidx.compose.material.icons.filled.Hotel import androidx.compose.material.icons.filled.Remove-import androidx.compose.material.icons.filled.Star import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue@@ -29,10 +20,8 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DatePicker import com.vayunmathur.library.ui.DatePickerDialog@@ -50,6 +39,7 @@ import com.vayunmathur.travel.network.PlaceDto import com.vayunmathur.travel.util.TravelViewModel import java.time.Instant import java.time.LocalDate+import java.time.LocalDateTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter @@ -64,18 +54,6 @@ fun SectionHeader(text: String, modifier: Modifier = Modifier) { ) } -/** A row of up to [max] stars, [stars] of them filled (hotel rating). */-@Composable-fun StarRow(stars: Int, max: Int = 5, modifier: Modifier = Modifier) {- if (stars <= 0) return- val filled = MaterialTheme.colorScheme.tertiary- Row(modifier) {- repeat(stars.coerceIn(0, max)) {- Icon(Icons.Filled.Star, contentDescription = null, tint = filled, modifier = Modifier.size(16.dp))- }- }-}- /** * Airport/city autocomplete field. Owns its own text; reports the chosen code * back via [onCodeChange] — either an IATA/city code when a suggestion is@@ -194,7 +172,7 @@ fun DateField( } } -/** A +/- stepper for a small integer count (passengers, rooms). */+/** A +/- stepper for a small integer count (passengers). */ @Composable fun CountStepper( label: String,@@ -224,86 +202,14 @@ fun CountStepper( } } -/** A price like "$412" / "€220"; "See prices" when [price] is 0 (unknown). */-fun formatPrice(price: Double, currency: String): String {- if (price <= 0.0) return "See prices"- val symbol = when (currency.lowercase()) {- "usd" -> "$"- "eur" -> "€"- "gbp" -> "£"- else -> currency.uppercase() + " "- }- return symbol + (if (price % 1.0 == 0.0) price.toInt().toString() else "%.2f".format(price))-}--/**- * A reusable result card: title + subtitle on the left, a price and a "Book"- * button on the right, and a favorite toggle.- */-@Composable-fun ResultCard(- title: String,- subtitle: String,- price: Double,- currency: String,- isFavorite: Boolean,- onFavorite: () -> Unit,- onBook: () -> Unit,- modifier: Modifier = Modifier,- extra: (@Composable () -> Unit)? = null,-) {- ElevatedCard(- modifier = modifier- .fillMaxWidth()- .padding(horizontal = 16.dp, vertical = 4.dp),- ) {- Row(- Modifier- .fillMaxWidth()- .padding(16.dp),- verticalAlignment = Alignment.CenterVertically,- ) {- Column(Modifier.weight(1f)) {- Text(title, style = MaterialTheme.typography.titleMedium)- if (subtitle.isNotBlank()) {- Text(- subtitle,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- extra?.invoke()- }- Column(horizontalAlignment = Alignment.End) {- Text(- formatPrice(price, currency),- style = MaterialTheme.typography.titleMedium,- color = MaterialTheme.colorScheme.primary,- fontWeight = FontWeight.SemiBold,- )- Row(verticalAlignment = Alignment.CenterVertically) {- IconButton(onClick = onFavorite) {- if (isFavorite) {- Icon(Icons.Filled.Favorite, contentDescription = "Saved", tint = MaterialTheme.colorScheme.tertiary)- } else {- Icon(Icons.Filled.FavoriteBorder, contentDescription = "Save")- }- }- TextButton(onClick = onBook) { Text("Book") }- }- }- }- }-}--/** Centered loading/error/empty state used by every results page. */+/** Centered loading/error/empty state used by results pages. */ @Composable fun StatusBox( loading: Boolean, error: String?, isEmpty: Boolean, modifier: Modifier = Modifier,- emptyMessage: String = "No results found. Try different dates or destinations.",+ emptyMessage: String = "No flights found. Try different dates or airports.", ) { Box(modifier.fillMaxWidth().heightIn(min = 200.dp), contentAlignment = Alignment.Center) { when {@@ -322,8 +228,42 @@ fun StatusBox( } } -fun verticalIcon(vertical: com.vayunmathur.travel.data.Vertical): ImageVector = when (vertical) {- com.vayunmathur.travel.data.Vertical.FLIGHTS -> Icons.Filled.Flight- com.vayunmathur.travel.data.Vertical.HOTELS -> Icons.Filled.Hotel- com.vayunmathur.travel.data.Vertical.CARS -> Icons.Filled.DirectionsCar+// --- Formatting helpers ------------------------------------------------------++/** A money label like "$412" / "€220.50" from a Duffel decimal-string amount. */+fun formatMoney(amount: String, currency: String): String {+ val value = amount.toDoubleOrNull() ?: return "$currency $amount"+ val symbol = when (currency.uppercase()) {+ "USD" -> "$"+ "EUR" -> "€"+ "GBP" -> "£"+ else -> currency.uppercase() + " "+ }+ return symbol + (if (value % 1.0 == 0.0) value.toInt().toString() else "%.2f".format(value))+}++/** "510" minutes -> "8h 30m". */+fun formatDuration(minutes: Long): String {+ if (minutes <= 0) return ""+ val h = minutes / 60+ val m = minutes % 60+ return buildString {+ if (h > 0) append("${h}h")+ if (m > 0) {+ if (h > 0) append(" ")+ append("${m}m")+ }+ }+}++/** "2026-09-01T10:00:00" -> "10:00"; falls back to the raw time part. */+fun formatTime(iso: String): String = runCatching {+ LocalDateTime.parse(iso.take(19)).format(DateTimeFormatter.ofPattern("HH:mm"))+}.getOrDefault(iso.substringAfter('T').take(5))++/** Stops label: "Nonstop" / "1 stop" / "N stops". */+fun stopsLabel(stops: Long): String = when (stops) {+ 0L -> "Nonstop"+ 1L -> "1 stop"+ else -> "$stops stops" }
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.ktnew file mode 100644index 0000000000..11b2282083--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationPage.kt@@ -0,0 +1,109 @@+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.fillMaxSize+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.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.CheckCircle+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+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.Button+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.util.TravelViewModel++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ConfirmationPage(+ backStack: NavBackStack<Route>,+ viewModel: TravelViewModel,+ route: Route.Confirmation,+) {+ val trips by viewModel.bookedTrips.collectAsStateWithLifecycle()+ val trip = trips.find { it.orderId == route.orderId }++ Scaffold(+ topBar = { TopAppBar(title = { Text("Booking confirmed") }) },+ ) { padding ->+ Column(+ Modifier+ .fillMaxSize()+ .padding(padding)+ .verticalScroll(rememberScrollState())+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ if (trip == null) {+ Text("Trip not found.", color = MaterialTheme.colorScheme.onSurfaceVariant)+ Button(onClick = { backStack.reset(Route.Home) }, modifier = Modifier.fillMaxWidth()) {+ Text("Back to search")+ }+ return@Column+ }++ Icon(+ Icons.Filled.CheckCircle,+ contentDescription = null,+ tint = MaterialTheme.colorScheme.primary,+ modifier = Modifier.size(64.dp).padding(top = 8.dp),+ )+ Text("You're booked!", style = MaterialTheme.typography.headlineSmall)++ ElevatedCard(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {+ DetailRow("Booking reference", trip.bookingReference, emphasize = true)+ HorizontalDivider()+ DetailRow("Route", trip.route)+ DetailRow("Departs", TravelViewModel.prettyDate(trip.departDate))+ DetailRow("Amount paid", formatMoney(trip.amount, trip.currency))+ DetailRow("Status", trip.status.replaceFirstChar(Char::uppercase))+ }+ }++ Button(onClick = { backStack.reset(Route.Home) }, modifier = Modifier.fillMaxWidth()) {+ Text("Done")+ }+ OutlinedButton(+ onClick = { backStack.reset(Route.Home, Route.Trips) },+ modifier = Modifier.fillMaxWidth(),+ ) { Text("View my trips") }+ }+ }+}++@Composable+private fun DetailRow(label: String, value: String, emphasize: Boolean = false) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Text(label, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(+ value,+ style = if (emphasize) MaterialTheme.typography.titleMedium else MaterialTheme.typography.bodyLarge,+ color = if (emphasize) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,+ fontWeight = if (emphasize) FontWeight.SemiBold else FontWeight.Normal,+ )+ }+}
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 f70c935f6f..52815b8023 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt@@ -1,6 +1,11 @@ package com.vayunmathur.travel.ui +import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items@@ -9,23 +14,24 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack 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.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.ElevatedCard import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.Icon import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route-import com.vayunmathur.travel.data.Favorite-import com.vayunmathur.travel.data.Vertical-import com.vayunmathur.travel.network.FlightDto+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.SliceDto import com.vayunmathur.travel.util.TravelViewModel-import com.vayunmathur.travel.util.openBooking @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -34,12 +40,17 @@ fun FlightResultsPage( viewModel: TravelViewModel, route: Route.FlightResults, ) {- val context = LocalContext.current val state by viewModel.flights.collectAsStateWithLifecycle()- val favorites by viewModel.favorites.collectAsStateWithLifecycle() LaunchedEffect(route) {- viewModel.searchFlights(route.origin, route.destination, route.depart, route.returnDate, route.adults)+ viewModel.searchFlights(+ route.origin,+ route.destination,+ route.depart,+ route.returnDate,+ route.adults,+ route.cabin,+ ) } Scaffold(@@ -58,17 +69,11 @@ fun FlightResultsPage( modifier = Modifier.fillMaxSize().padding(padding), contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp), ) {- items(state.results) { flight ->- val fav = favorites.any { it.bookingUrl == flight.bookingUrl }- ResultCard(- title = flightTitle(flight),- subtitle = flightSubtitle(flight),- price = flight.price,- currency = flight.currency,- isFavorite = fav,- onFavorite = { viewModel.toggleFavorite(flight.toFavorite()) },- onBook = { openBooking(context, flight.bookingUrl) },- )+ items(state.results) { offer ->+ OfferCard(offer) {+ viewModel.selectOffer(offer)+ backStack.add(Route.OfferReview(offer.offerId))+ } } if (state.loading || state.error != null || (state.hasSearched && state.results.isEmpty())) { item {@@ -83,27 +88,50 @@ fun FlightResultsPage( } } -private fun flightTitle(f: FlightDto): String {- val airline = f.airline.ifBlank { "Flight" }- return if (f.flightNumber.isBlank()) airline else "$airline ${f.flightNumber}"+@Composable+private fun OfferCard(offer: OfferDto, onClick: () -> Unit) {+ ElevatedCard(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp, vertical = 4.dp)+ .clickable { onClick() },+ ) {+ Row(+ Modifier.fillMaxWidth().padding(16.dp),+ verticalAlignment = Alignment.Top,+ ) {+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Text(+ offer.owner.ifBlank { "Flight" },+ style = MaterialTheme.typography.titleMedium,+ )+ offer.slices.forEach { slice -> SliceRow(slice) }+ }+ Text(+ formatMoney(offer.totalAmount, offer.currency),+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.primary,+ fontWeight = FontWeight.SemiBold,+ )+ }+ } } -private fun flightSubtitle(f: FlightDto): String {- val date = TravelViewModel.prettyDate(f.departureAt.take(10))- val stops = when (f.transfers) {- 0 -> "Nonstop"- 1 -> "1 stop"- else -> "${f.transfers} stops"+@Composable+private fun SliceRow(slice: SliceDto) {+ val times = "${formatTime(slice.departureAt)} – ${formatTime(slice.arrivalAt)}"+ val meta = listOf(stopsLabel(slice.stops), formatDuration(slice.durationMinutes))+ .filter { it.isNotBlank() }+ .joinToString(" · ")+ Column {+ Text(+ "${slice.origin} → ${slice.destination} · $times",+ style = MaterialTheme.typography.bodyMedium,+ )+ Text(+ meta,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ ) }- val ret = f.returnAt?.takeIf { it.isNotBlank() }?.let { " · Return ${TravelViewModel.prettyDate(it.take(10))}" } ?: ""- return "$date · $stops$ret" }--private fun FlightDto.toFavorite() = Favorite(- bookingUrl = bookingUrl,- vertical = Vertical.FLIGHTS.name,- title = flightTitle(this),- subtitle = "$origin → $destination · ${flightSubtitle(this)}",- price = price,- currency = currency,-)
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 abe61a8cbf..3f948301a7 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt@@ -1,10 +1,12 @@ package com.vayunmathur.travel.ui +import androidx.compose.foundation.horizontalScroll 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.rememberScrollState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf@@ -15,20 +17,29 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.Switch import com.vayunmathur.library.ui.Text import com.vayunmathur.travel.util.TravelViewModel +/** The Duffel cabin classes, with a display label. */+enum class Cabin(val code: String, val label: String) {+ ECONOMY("economy", "Economy"),+ PREMIUM("premium_economy", "Premium"),+ BUSINESS("business", "Business"),+ FIRST("first", "First"),+}+ /** * Flight search form: origin/destination autocomplete, depart (+ optional- * return) dates, and a passenger count. Calls [onSearch] with the collected- * query when the user taps "Search flights".+ * return) dates, cabin class, and a passenger count. Calls [onSearch] with the+ * collected query when the user taps "Search flights". */ @Composable fun FlightSearchForm( viewModel: TravelViewModel, modifier: Modifier = Modifier,- onSearch: (origin: String, destination: String, depart: String, ret: String?, adults: Int) -> Unit,+ onSearch: (origin: String, destination: String, depart: String, ret: String?, adults: Int, cabin: String) -> Unit, ) { var origin by remember { mutableStateOf("") } var destination by remember { mutableStateOf("") }@@ -36,6 +47,7 @@ fun FlightSearchForm( var roundTrip by remember { mutableStateOf(false) } var returnDate by remember { mutableStateOf("") } var adults by remember { mutableIntStateOf(1) }+ var cabin by remember { mutableStateOf(Cabin.ECONOMY) } Column(modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { PlaceAutocompleteField("From", viewModel, onCodeChange = { origin = it })@@ -54,6 +66,19 @@ fun FlightSearchForm( DateField("Return", returnDate, onDate = { returnDate = it }) } + Row(+ Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Cabin.entries.forEach { c ->+ FilterChip(+ selected = cabin == c,+ onClick = { cabin = c },+ label = { Text(c.label) },+ )+ }+ }+ CountStepper("Passengers", adults, onCount = { adults = it }) Button(@@ -64,6 +89,7 @@ fun FlightSearchForm( depart, returnDate.takeIf { roundTrip && it.isNotBlank() }, adults,+ cabin.code, ) }, enabled = origin.isNotBlank() && destination.isNotBlank() && depart.isNotBlank() &&
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 bb0d78f239..d72159a2a5 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/HomePage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/HomePage.kt@@ -1,7 +1,7 @@ package com.vayunmathur.travel.ui -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize@@ -10,12 +10,9 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons-import androidx.compose.material.icons.filled.Favorite+import androidx.compose.material.icons.filled.Flight 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.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp@@ -23,38 +20,35 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.ui.ElevatedCard import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedCard import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.SegmentedButton-import com.vayunmathur.library.ui.SegmentedButtonDefaults-import com.vayunmathur.library.ui.SingleChoiceSegmentedButtonRow import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route-import com.vayunmathur.travel.data.Favorite+import com.vayunmathur.travel.data.BookedTrip import com.vayunmathur.travel.data.RecentSearch-import com.vayunmathur.travel.data.Vertical import com.vayunmathur.travel.util.TravelViewModel-import com.vayunmathur.travel.util.openBooking--private enum class Tab(val label: String) {- FLIGHTS("Flights"), HOTELS("Hotels"), CARS("Cars"), TRAINS("Trains")-} @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) {- val context = androidx.compose.ui.platform.LocalContext.current- var tab by remember { mutableStateOf(Tab.FLIGHTS) } val recents by viewModel.recentSearches.collectAsStateWithLifecycle()- val favorites by viewModel.favorites.collectAsStateWithLifecycle()+ val trips by viewModel.bookedTrips.collectAsStateWithLifecycle() Scaffold(- topBar = { TopAppBar(title = { Text("Travel") }) },+ topBar = {+ TopAppBar(+ title = { Text("Flights") },+ actions = {+ if (trips.isNotEmpty()) {+ TextButton(onClick = { backStack.add(Route.Trips) }) { Text("My trips") }+ }+ },+ )+ }, ) { padding -> Column( Modifier@@ -62,32 +56,8 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) { .padding(padding) .verticalScroll(rememberScrollState()), ) {- SingleChoiceSegmentedButtonRow(- Modifier- .fillMaxWidth()- .padding(horizontal = 16.dp, vertical = 12.dp),- ) {- Tab.entries.forEachIndexed { index, t ->- SegmentedButton(- selected = tab == t,- onClick = { tab = t },- shape = SegmentedButtonDefaults.itemShape(index, Tab.entries.size),- label = { Text(t.label) },- )- }- }-- when (tab) {- Tab.FLIGHTS -> FlightSearchForm(viewModel) { origin, destination, depart, ret, adults ->- backStack.add(Route.FlightResults(origin, destination, depart, ret, adults))- }- Tab.HOTELS -> HotelSearchForm(viewModel) { location, checkin, checkout, adults ->- backStack.add(Route.HotelResults(location, checkin, checkout, adults))- }- Tab.CARS -> CarSearchForm(viewModel) { location, pickup, dropoff ->- backStack.add(Route.CarResults(location, pickup, dropoff))- }- Tab.TRAINS -> TrainsComingSoon()+ FlightSearchForm(viewModel) { origin, destination, depart, ret, adults, cabin ->+ backStack.add(Route.FlightResults(origin, destination, depart, ret, adults, cabin)) } if (recents.isNotEmpty()) {@@ -104,14 +74,16 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) { } } - if (favorites.isNotEmpty()) {- SectionHeader("Saved")- favorites.forEach { favorite ->- FavoriteCard(- favorite = favorite,- onOpen = { openBooking(context, favorite.bookingUrl) },- onRemove = { viewModel.removeFavorite(favorite) },- )+ if (trips.isNotEmpty()) {+ SectionHeader("My trips")+ trips.take(3).forEach { trip ->+ TripSummaryCard(trip) { backStack.add(Route.Confirmation(trip.orderId)) }+ }+ if (trips.size > 3) {+ TextButton(+ onClick = { backStack.add(Route.Trips) },+ modifier = Modifier.padding(horizontal = 8.dp),+ ) { Text("See all ${trips.size} trips") } } } @@ -122,7 +94,6 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) { @Composable private fun RecentSearchCard(recent: RecentSearch, onClick: () -> Unit) {- val vertical = runCatching { Vertical.valueOf(recent.vertical) }.getOrNull() OutlinedCard( modifier = Modifier .fillMaxWidth()@@ -134,73 +105,51 @@ private fun RecentSearchCard(recent: RecentSearch, onClick: () -> Unit) { verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) {- if (vertical != null) Icon(verticalIcon(vertical), contentDescription = null)+ Icon(Icons.Filled.Flight, contentDescription = null) Text(recent.label, style = MaterialTheme.typography.bodyLarge) } } } @Composable-private fun FavoriteCard(favorite: Favorite, onOpen: () -> Unit, onRemove: () -> Unit) {+private fun TripSummaryCard(trip: BookedTrip, onClick: () -> Unit) { ElevatedCard( modifier = Modifier .fillMaxWidth()- .padding(horizontal = 16.dp, vertical = 4.dp),+ .padding(horizontal = 16.dp, vertical = 4.dp)+ .clickable { onClick() }, ) { Row( Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) {- Text(favorite.title, style = MaterialTheme.typography.titleMedium)- if (favorite.subtitle.isNotBlank()) {- Text(- favorite.subtitle,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }+ Text(trip.route, style = MaterialTheme.typography.titleMedium)+ Text(+ "${TravelViewModel.prettyDate(trip.departDate)} · ${trip.bookingReference}",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ ) } Text(- formatPrice(favorite.price, favorite.currency),+ formatMoney(trip.amount, trip.currency), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary, )- IconButton(onClick = onRemove) {- Icon(Icons.Filled.Favorite, contentDescription = "Remove", tint = MaterialTheme.colorScheme.tertiary)- }- TextButton(onClick = onOpen) { Text("Book") } } } } -/** Rebuild the results Route for a stored search and navigate to it. */+/** Rebuild the flight-results Route for a stored search and navigate to it. */ private fun openRecent(backStack: NavBackStack<Route>, recent: RecentSearch) {- when (runCatching { Vertical.valueOf(recent.vertical) }.getOrNull()) {- Vertical.FLIGHTS -> backStack.add(- Route.FlightResults(- origin = recent.origin.orEmpty(),- destination = recent.destination.orEmpty(),- depart = recent.depart.orEmpty(),- returnDate = recent.returnDate,- adults = recent.adults,- )+ backStack.add(+ Route.FlightResults(+ origin = recent.origin.orEmpty(),+ destination = recent.destination.orEmpty(),+ depart = recent.depart.orEmpty(),+ returnDate = recent.returnDate,+ adults = recent.adults,+ cabin = recent.cabin, )- Vertical.HOTELS -> backStack.add(- Route.HotelResults(- location = recent.location.orEmpty(),- checkin = recent.checkin.orEmpty(),- checkout = recent.checkout.orEmpty(),- adults = recent.adults,- )- )- Vertical.CARS -> backStack.add(- Route.CarResults(- location = recent.location.orEmpty(),- pickup = recent.pickup.orEmpty(),- dropoff = recent.dropoff.orEmpty(),- )- )- null -> {}- }+ ) }
travel/src/main/java/com/vayunmathur/travel/ui/HotelResultsPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/HotelResultsPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/HotelResultsPage.ktdeleted file mode 100644index a1d371563f..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/HotelResultsPage.kt+++ /dev/null@@ -1,94 +0,0 @@-package com.vayunmathur.travel.ui--import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.material.icons.Icons-import androidx.compose.material.icons.automirrored.filled.ArrowBack-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.unit.dp-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.travel.Route-import com.vayunmathur.travel.data.Favorite-import com.vayunmathur.travel.data.Vertical-import com.vayunmathur.travel.network.HotelDto-import com.vayunmathur.travel.util.TravelViewModel-import com.vayunmathur.travel.util.openBooking--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun HotelResultsPage(- backStack: NavBackStack<Route>,- viewModel: TravelViewModel,- route: Route.HotelResults,-) {- val context = LocalContext.current- val state by viewModel.hotels.collectAsStateWithLifecycle()- val favorites by viewModel.favorites.collectAsStateWithLifecycle()-- LaunchedEffect(route) {- viewModel.searchHotels(route.location, route.checkin, route.checkout, route.adults)- }-- Scaffold(- topBar = {- TopAppBar(- title = { Text(route.location) },- navigationIcon = {- IconButton(onClick = { backStack.pop() }) {- Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")- }- },- )- },- ) { padding ->- LazyColumn(- modifier = Modifier.fillMaxSize().padding(padding),- contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp),- ) {- items(state.results) { hotel ->- val fav = favorites.any { it.bookingUrl == hotel.bookingUrl }- ResultCard(- title = hotel.name,- subtitle = hotel.location,- price = hotel.price,- currency = hotel.currency,- isFavorite = fav,- onFavorite = { viewModel.toggleFavorite(hotel.toFavorite()) },- onBook = { openBooking(context, hotel.bookingUrl) },- extra = { StarRow(hotel.stars) },- )- }- if (state.loading || state.error != null || (state.hasSearched && state.results.isEmpty())) {- item {- StatusBox(- loading = state.loading,- error = state.error,- isEmpty = state.hasSearched && state.results.isEmpty(),- )- }- }- }- }-}--private fun HotelDto.toFavorite() = Favorite(- bookingUrl = bookingUrl,- vertical = Vertical.HOTELS.name,- title = name,- subtitle = location,- price = price,- currency = currency,-)
travel/src/main/java/com/vayunmathur/travel/ui/HotelSearchForm.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/HotelSearchForm.kt b/travel/src/main/java/com/vayunmathur/travel/ui/HotelSearchForm.ktdeleted file mode 100644index e13df95584..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/HotelSearchForm.kt+++ /dev/null@@ -1,53 +0,0 @@-package com.vayunmathur.travel.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-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.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Text-import com.vayunmathur.travel.util.TravelViewModel--/**- * Hotel search form: destination (free text — the proxy resolves the location),- * check-in/out dates, and a guest count.- */-@Composable-fun HotelSearchForm(- @Suppress("UNUSED_PARAMETER") viewModel: TravelViewModel,- modifier: Modifier = Modifier,- onSearch: (location: String, checkin: String, checkout: String, adults: Int) -> Unit,-) {- var location by remember { mutableStateOf("") }- var checkin by remember { mutableStateOf("") }- var checkout by remember { mutableStateOf("") }- var adults by remember { mutableIntStateOf(2) }-- Column(modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {- OutlinedTextField(- value = location,- onValueChange = { location = it },- label = { Text("City or destination") },- singleLine = true,- modifier = Modifier.fillMaxWidth(),- )- DateField("Check-in", checkin, onDate = { checkin = it })- DateField("Check-out", checkout, onDate = { checkout = it })- CountStepper("Guests", adults, onCount = { adults = it })-- Button(- onClick = { onSearch(location, checkin, checkout, adults) },- enabled = location.isNotBlank() && checkin.isNotBlank() && checkout.isNotBlank(),- modifier = Modifier.fillMaxWidth(),- ) { Text("Search hotels") }- }-}
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.ktnew file mode 100644index 0000000000..8818d3440f--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/OfferReviewPage.kt@@ -0,0 +1,177 @@+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.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+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.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.SliceDto+import com.vayunmathur.travel.util.TravelViewModel++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun OfferReviewPage(+ backStack: NavBackStack<Route>,+ viewModel: TravelViewModel,+ route: Route.OfferReview,+) {+ val review by viewModel.review.collectAsStateWithLifecycle()++ LaunchedEffect(route.offerId) { viewModel.refreshOffer(route.offerId) }++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text("Review flight") },+ navigationIcon = {+ IconButton(onClick = { backStack.pop() }) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")+ }+ },+ )+ },+ ) { padding ->+ val offer = review.offer+ Column(+ Modifier+ .fillMaxSize()+ .padding(padding)+ .verticalScroll(rememberScrollState())+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ if (offer == null) {+ StatusBox(loading = review.loading, error = review.error, isEmpty = !review.loading)+ return@Column+ }++ Text(offer.owner.ifBlank { "Flight" }, style = MaterialTheme.typography.titleLarge)++ offer.slices.forEachIndexed { index, slice ->+ SliceDetailCard(+ title = if (offer.slices.size > 1) {+ if (index == 0) "Outbound" else "Return"+ } else {+ "Itinerary"+ },+ slice = slice,+ )+ }++ PriceSummaryCard(offer, review.loading)++ if (review.error != null) {+ Text(+ review.error!!,+ color = MaterialTheme.colorScheme.error,+ style = MaterialTheme.typography.bodySmall,+ )+ }++ Button(+ onClick = {+ viewModel.initPassengers(offer)+ backStack.add(Route.Passengers(offer.offerId))+ },+ enabled = !review.loading,+ modifier = Modifier.fillMaxWidth(),+ ) { Text("Continue") }+ }+ }+}++@Composable+private fun SliceDetailCard(title: String, slice: SliceDto) {+ ElevatedCard(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)+ Text(+ listOf(stopsLabel(slice.stops), formatDuration(slice.durationMinutes))+ .filter { it.isNotBlank() }.joinToString(" · "),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ slice.segments.forEach { seg ->+ Column {+ Text(+ "${seg.origin} ${formatTime(seg.departureAt)} → ${seg.destination} ${formatTime(seg.arrivalAt)}",+ style = MaterialTheme.typography.bodyMedium,+ )+ val carrier = listOf(seg.carrier, seg.flightNumber).filter { it.isNotBlank() }.joinToString(" ")+ if (carrier.isNotBlank()) {+ Text(+ carrier,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+ }+ }+}++@Composable+private fun PriceSummaryCard(offer: OfferDto, loading: Boolean) {+ ElevatedCard(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text("Total", style = MaterialTheme.typography.titleMedium)+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if (loading) CircularProgressIndicator()+ Text(+ formatMoney(offer.totalAmount, offer.currency),+ style = MaterialTheme.typography.titleLarge,+ color = MaterialTheme.colorScheme.primary,+ fontWeight = FontWeight.SemiBold,+ )+ }+ }+ if (offer.expiresAt.isNotBlank()) {+ HorizontalDivider()+ Text(+ "Offer held until ${formatTime(offer.expiresAt)} · price may change",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+}
travel/src/main/java/com/vayunmathur/travel/ui/PassengersPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/PassengersPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/PassengersPage.ktnew file mode 100644index 0000000000..901fdfd428--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/PassengersPage.kt@@ -0,0 +1,171 @@+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.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.network.PassengerInputDto+import com.vayunmathur.travel.util.TravelViewModel++private val TITLES = listOf("mr", "ms", "mrs", "miss")+private val GENDERS = listOf("m" to "Male", "f" to "Female")++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun PassengersPage(+ backStack: NavBackStack<Route>,+ viewModel: TravelViewModel,+ route: Route.Passengers,+) {+ val passengers by viewModel.passengers.collectAsStateWithLifecycle()++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text("Passengers") },+ navigationIcon = {+ IconButton(onClick = { backStack.pop() }) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")+ }+ },+ )+ },+ ) { padding ->+ Column(+ Modifier+ .fillMaxSize()+ .padding(padding)+ .verticalScroll(rememberScrollState())+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ passengers.forEachIndexed { index, passenger ->+ PassengerForm(+ index = index,+ total = passengers.size,+ passenger = passenger,+ onChange = { viewModel.updatePassenger(index, it) },+ )+ }++ Button(+ onClick = { backStack.add(Route.Payment(route.offerId)) },+ enabled = passengers.isNotEmpty() && passengers.all { it.isValid() },+ modifier = Modifier.fillMaxWidth(),+ ) { Text("Continue to payment") }+ }+ }+}++@Composable+private fun PassengerForm(+ index: Int,+ total: Int,+ passenger: PassengerInputDto,+ onChange: (PassengerInputDto) -> Unit,+) {+ ElevatedCard(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(+ if (total > 1) "Passenger ${index + 1}" else "Passenger details",+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.primary,+ )++ ChipRow("Title", TITLES.map { it to it.replaceFirstChar(Char::uppercase) }, passenger.title) {+ onChange(passenger.copy(title = it))+ }++ OutlinedTextField(+ value = passenger.givenName,+ onValueChange = { onChange(passenger.copy(givenName = it)) },+ label = { Text("Given name") },+ singleLine = true,+ modifier = Modifier.fillMaxWidth(),+ )+ OutlinedTextField(+ value = passenger.familyName,+ onValueChange = { onChange(passenger.copy(familyName = it)) },+ label = { Text("Family name") },+ singleLine = true,+ modifier = Modifier.fillMaxWidth(),+ )++ DateField("Date of birth", passenger.bornOn, onDate = { onChange(passenger.copy(bornOn = it)) })++ ChipRow("Gender", GENDERS, passenger.gender) { onChange(passenger.copy(gender = it)) }++ OutlinedTextField(+ value = passenger.email,+ onValueChange = { onChange(passenger.copy(email = it)) },+ label = { Text("Email") },+ singleLine = true,+ keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = KeyboardType.Email),+ modifier = Modifier.fillMaxWidth(),+ )+ OutlinedTextField(+ value = passenger.phoneNumber,+ onValueChange = { onChange(passenger.copy(phoneNumber = it)) },+ label = { Text("Phone (e.g. +14155550123)") },+ singleLine = true,+ keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = KeyboardType.Phone),+ modifier = Modifier.fillMaxWidth(),+ )+ }+ }+}++@Composable+private fun ChipRow(+ label: String,+ options: List<Pair<String, String>>,+ selected: String,+ onSelect: (String) -> Unit,+) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ options.forEach { (value, text) ->+ FilterChip(+ selected = selected == value,+ onClick = { onSelect(value) },+ label = { Text(text) },+ )+ }+ }+ }+}++private fun PassengerInputDto.isValid(): Boolean =+ title.isNotBlank() &&+ givenName.isNotBlank() &&+ familyName.isNotBlank() &&+ bornOn.isNotBlank() &&+ gender.isNotBlank() &&+ email.contains("@") &&+ phoneNumber.isNotBlank()
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.ktnew file mode 100644index 0000000000..37803d0417--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/PaymentPage.kt@@ -0,0 +1,127 @@+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.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+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.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.util.BookingState+import com.vayunmathur.travel.util.TravelViewModel++/**+ * Payment screen.+ *+ * **Sandbox (shipped):** books the offer with Duffel's test `balance` payment —+ * no card entry, no PCI surface — via [TravelViewModel.createOrder].+ *+ * **Live cards (deferred):** this same screen is where a Duffel Payments hosted+ * card component would be rendered in a `WebView` (using a client key minted by+ * `/api/travel/payment-key`), then the resulting card token passed to+ * `createOrder`. The flow around it (review → passengers → confirmation) does+ * not change, so that layers in here without reworking navigation.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun PaymentPage(+ backStack: NavBackStack<Route>,+ viewModel: TravelViewModel,+ route: Route.Payment,+) {+ val review by viewModel.review.collectAsStateWithLifecycle()+ val booking by viewModel.booking.collectAsStateWithLifecycle()++ LaunchedEffect(booking) {+ val b = booking+ if (b is BookingState.Success) {+ viewModel.resetBooking()+ // Replace the whole booking flow with the confirmation so Back+ // returns to Home rather than the payment screen.+ backStack.reset(Route.Home, Route.Confirmation(b.result.orderId))+ }+ }++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text("Payment") },+ navigationIcon = {+ IconButton(onClick = { backStack.pop() }) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")+ }+ },+ )+ },+ ) { padding ->+ val offer = review.offer+ val loading = booking is BookingState.Loading+ Column(+ Modifier+ .fillMaxSize()+ .padding(padding)+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ ElevatedCard(Modifier.fillMaxWidth()) {+ Row(+ Modifier.fillMaxWidth().padding(16.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text("Total due", style = MaterialTheme.typography.titleMedium)+ Text(+ if (offer != null) formatMoney(offer.totalAmount, offer.currency) else "—",+ style = MaterialTheme.typography.titleLarge,+ color = MaterialTheme.colorScheme.primary,+ fontWeight = FontWeight.SemiBold,+ )+ }+ }++ Text(+ "Sandbox booking — paid with a Duffel test balance. No card is charged.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )++ (booking as? BookingState.Error)?.let {+ Text(it.message, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)+ }++ Button(+ onClick = { viewModel.createOrder() },+ enabled = offer != null && !loading,+ modifier = Modifier.fillMaxWidth(),+ ) {+ if (loading) {+ CircularProgressIndicator(modifier = Modifier.padding(end = 8.dp))+ Text("Booking…")+ } else {+ Text("Pay with test balance")+ }+ }+ }+ }+}
travel/src/main/java/com/vayunmathur/travel/ui/TrainsComingSoon.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/TrainsComingSoon.kt b/travel/src/main/java/com/vayunmathur/travel/ui/TrainsComingSoon.ktdeleted file mode 100644index 25089b846a..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/ui/TrainsComingSoon.kt+++ /dev/null@@ -1,47 +0,0 @@-package com.vayunmathur.travel.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size-import androidx.compose.material.icons.Icons-import androidx.compose.material.icons.filled.Train-import androidx.compose.runtime.Composable-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.text.style.TextAlign-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text--/**- * Placeholder for the Trains vertical. No free global rail-pricing API exists,- * so this is a scaffold-only "coming soon" panel (see the plan's out-of-scope- * note).- */-@Composable-fun TrainsComingSoon(modifier: Modifier = Modifier) {- Column(- modifier- .fillMaxWidth()- .padding(32.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(12.dp),- ) {- Icon(- Icons.Filled.Train,- contentDescription = null,- tint = MaterialTheme.colorScheme.primary,- modifier = Modifier.size(48.dp),- )- Text("Trains are coming soon", style = MaterialTheme.typography.titleMedium)- Text(- "We're working on rail search. For now, try Flights, Hotels, or Cars.",- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- textAlign = TextAlign.Center,- )- }-}
travel/src/main/java/com/vayunmathur/travel/ui/TripsPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/TripsPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/TripsPage.ktnew file mode 100644index 0000000000..9dd585424e--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/TripsPage.kt@@ -0,0 +1,92 @@+package com.vayunmathur.travel.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.util.TravelViewModel++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun TripsPage(backStack: NavBackStack<Route>, viewModel: TravelViewModel) {+ val trips by viewModel.bookedTrips.collectAsStateWithLifecycle()++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text("My trips") },+ navigationIcon = {+ IconButton(onClick = { backStack.pop() }) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")+ }+ },+ )+ },+ ) { padding ->+ if (trips.isEmpty()) {+ StatusBox(+ loading = false,+ error = null,+ isEmpty = true,+ modifier = Modifier.fillMaxSize().padding(padding),+ emptyMessage = "No booked trips yet.",+ )+ return@Scaffold+ }+ LazyColumn(+ modifier = Modifier.fillMaxSize().padding(padding),+ contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp),+ ) {+ items(trips) { trip ->+ ElevatedCard(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp, vertical = 4.dp)+ .clickable { backStack.add(Route.Confirmation(trip.orderId)) },+ ) {+ Row(+ Modifier.fillMaxWidth().padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(trip.route, style = MaterialTheme.typography.titleMedium)+ Text(+ "${TravelViewModel.prettyDate(trip.departDate)} · ${trip.bookingReference}",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ Text(+ formatMoney(trip.amount, trip.currency),+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.primary,+ )+ }+ }+ }+ }+ }+}
travel/src/main/java/com/vayunmathur/travel/util/Booking.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/Booking.kt b/travel/src/main/java/com/vayunmathur/travel/util/Booking.ktdeleted file mode 100644index b2bdc63729..0000000000--- a/travel/src/main/java/com/vayunmathur/travel/util/Booking.kt+++ /dev/null@@ -1,17 +0,0 @@-package com.vayunmathur.travel.util--import android.content.Context-import android.content.Intent-import androidx.core.net.toUri--/**- * Opens an affiliate [bookingUrl] in the user's browser / a Custom Tab via a- * plain `ACTION_VIEW` intent. v1 deep-links out to the provider to complete the- * booking — there are no in-app payments.- */-fun openBooking(context: Context, bookingUrl: String) {- if (bookingUrl.isBlank()) return- val intent = Intent(Intent.ACTION_VIEW, bookingUrl.toUri())- .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- runCatching { context.startActivity(intent) }-}
travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt b/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.ktindex 2326558ef9..a3ffcc86f2 100644--- a/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt+++ b/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt@@ -5,14 +5,16 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope-import com.vayunmathur.travel.data.Favorite-import com.vayunmathur.travel.data.FavoriteDao+import com.vayunmathur.travel.data.BookedTrip+import com.vayunmathur.travel.data.BookedTripDao import com.vayunmathur.travel.data.RecentSearch import com.vayunmathur.travel.data.RecentSearchDao import com.vayunmathur.travel.data.Vertical-import com.vayunmathur.travel.network.CarDto-import com.vayunmathur.travel.network.FlightDto-import com.vayunmathur.travel.network.HotelDto+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.OrderRequestDto+import com.vayunmathur.travel.network.OrderResultDto+import com.vayunmathur.travel.network.PassengerInputDto+import com.vayunmathur.travel.network.PaymentInputDto import com.vayunmathur.travel.network.PlaceDto import com.vayunmathur.travel.network.TravelApi import kotlinx.coroutines.flow.MutableStateFlow@@ -21,8 +23,9 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.serialization.json.Json -/** Generic search state for one vertical's results list. */+/** Search state for the flight results list. */ data class SearchUiState<T>( val loading: Boolean = false, val error: String? = null,@@ -30,33 +33,49 @@ data class SearchUiState<T>( val hasSearched: Boolean = false, ) +/** State for the single-offer review (re-price) screen. */+data class OfferReviewState(+ val loading: Boolean = false,+ val error: String? = null,+ val offer: OfferDto? = null,+)++/** Booking lifecycle for the payment/confirmation flow. */+sealed interface BookingState {+ data object Idle : BookingState+ data object Loading : BookingState+ data class Success(val result: OrderResultDto) : BookingState+ data class Error(val message: String) : BookingState+}+ /**- * The single hub for the Travel app: owns the per-vertical search state (calling- * [TravelApi] and exposing loading/error/results as [StateFlow]) and persists- * recent searches + favorites through the Room [RecentSearchDao] / [FavoriteDao].- *- * Modeled after [com.vayunmathur.weather.util.WeatherViewModel] and- * `EducationViewModel` (manual [ViewModelProvider.Factory]).+ * The single hub for the Travel app: owns flight search + the+ * offer→passengers→order booking flow (calling [TravelApi] and exposing+ * loading/error state as [StateFlow]), persists recent searches, and stores+ * booked trips through the Room [RecentSearchDao] / [BookedTripDao]. */ class TravelViewModel( application: Application, private val recentSearchDao: RecentSearchDao,- private val favoriteDao: FavoriteDao,+ private val bookedTripDao: BookedTripDao, ) : AndroidViewModel(application) { - private val _flights = MutableStateFlow(SearchUiState<FlightDto>())- val flights: StateFlow<SearchUiState<FlightDto>> = _flights.asStateFlow()+ private val _flights = MutableStateFlow(SearchUiState<OfferDto>())+ val flights: StateFlow<SearchUiState<OfferDto>> = _flights.asStateFlow()++ private val _review = MutableStateFlow(OfferReviewState())+ val review: StateFlow<OfferReviewState> = _review.asStateFlow() - private val _hotels = MutableStateFlow(SearchUiState<HotelDto>())- val hotels: StateFlow<SearchUiState<HotelDto>> = _hotels.asStateFlow()+ private val _passengers = MutableStateFlow<List<PassengerInputDto>>(emptyList())+ val passengers: StateFlow<List<PassengerInputDto>> = _passengers.asStateFlow() - private val _cars = MutableStateFlow(SearchUiState<CarDto>())- val cars: StateFlow<SearchUiState<CarDto>> = _cars.asStateFlow()+ private val _booking = MutableStateFlow<BookingState>(BookingState.Idle)+ val booking: StateFlow<BookingState> = _booking.asStateFlow() val recentSearches: StateFlow<List<RecentSearch>> = recentSearchDao.observeRecent() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) - val favorites: StateFlow<List<Favorite>> = favoriteDao.observeAll()+ val bookedTrips: StateFlow<List<BookedTrip>> = bookedTripDao.observeAll() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) // --- Autocomplete -----------------------------------------------------@@ -65,7 +84,7 @@ class TravelViewModel( suspend fun autocomplete(query: String): List<PlaceDto> = runCatching { TravelApi.places(query) }.getOrDefault(emptyList()) - // --- Searches ---------------------------------------------------------+ // --- Search ----------------------------------------------------------- fun searchFlights( origin: String,@@ -73,7 +92,7 @@ class TravelViewModel( depart: String, ret: String?, adults: Int,- currency: String = "usd",+ cabin: String = "economy", ) { recordRecent( RecentSearch(@@ -84,82 +103,111 @@ class TravelViewModel( depart = depart, returnDate = ret, adults = adults,+ cabin = cabin, ) ) _flights.value = SearchUiState(loading = true, hasSearched = true) viewModelScope.launch {- runCatching { TravelApi.flights(origin, destination, depart, ret, adults, currency) }- .onSuccess { _flights.value = SearchUiState(results = it, hasSearched = true) }+ runCatching { TravelApi.flights(origin, destination, depart, ret, adults, cabin) }+ .onSuccess { _flights.value = SearchUiState(results = it.offers, hasSearched = true) } .onFailure { _flights.value = SearchUiState(error = errorMessage(it), hasSearched = true) } } } - fun searchHotels(- location: String,- checkin: String,- checkout: String,- adults: Int,- currency: String = "usd",- ) {- recordRecent(- RecentSearch(- vertical = Vertical.HOTELS.name,- label = "$location · ${prettyDate(checkin)}–${prettyDate(checkout)}",- location = location,- checkin = checkin,- checkout = checkout,- adults = adults,- )- )- _hotels.value = SearchUiState(loading = true, hasSearched = true)- viewModelScope.launch {- runCatching { TravelApi.hotels(location, checkin, checkout, adults, currency) }- .onSuccess { _hotels.value = SearchUiState(results = it, hasSearched = true) }- .onFailure { _hotels.value = SearchUiState(error = errorMessage(it), hasSearched = true) }- }+ // --- Offer review / re-price -----------------------------------------++ /** Seed the review screen with the tapped offer. */+ fun selectOffer(offer: OfferDto) {+ _review.value = OfferReviewState(offer = offer) } - fun searchCars(- location: String,- pickup: String,- dropoff: String,- currency: String = "usd",- ) {- recordRecent(- RecentSearch(- vertical = Vertical.CARS.name,- label = "$location · ${prettyDate(pickup)}–${prettyDate(dropoff)}",- location = location,- pickup = pickup,- dropoff = dropoff,- )- )- _cars.value = SearchUiState(loading = true, hasSearched = true)+ /** Re-price the chosen offer right before booking (offers expire). */+ fun refreshOffer(offerId: String) {+ _review.value = _review.value.copy(loading = true, error = null) viewModelScope.launch {- runCatching { TravelApi.cars(location, pickup, dropoff, currency) }- .onSuccess { _cars.value = SearchUiState(results = it, hasSearched = true) }- .onFailure { _cars.value = SearchUiState(error = errorMessage(it), hasSearched = true) }+ runCatching { TravelApi.offer(offerId) }+ .onSuccess { _review.value = OfferReviewState(offer = it) }+ .onFailure {+ // Keep the previously selected offer so the user can still proceed.+ _review.value = _review.value.copy(loading = false, error = errorMessage(it))+ } } } - // --- Favorites --------------------------------------------------------+ // --- Passengers -------------------------------------------------------++ /**+ * Initialize one blank passenger per Duffel passenger id on the offer,+ * unless a matching set is already present (so returning to the form keeps+ * entered values).+ */+ fun initPassengers(offer: OfferDto) {+ val ids = offer.passengerIds.ifEmpty { listOf("") }+ if (_passengers.value.map { it.id } == ids) return+ _passengers.value = ids.map { PassengerInputDto(id = it) }+ }++ fun updatePassenger(index: Int, passenger: PassengerInputDto) {+ _passengers.value = _passengers.value.toMutableList().also {+ if (index in it.indices) it[index] = passenger+ }+ } - fun isFavorite(bookingUrl: String): Boolean =- favorites.value.any { it.bookingUrl == bookingUrl }+ // --- Booking ---------------------------------------------------------- - /** Add the offer to favorites, or remove it if it's already saved. */- fun toggleFavorite(favorite: Favorite) {+ /** Book the reviewed offer with the collected passengers via test balance. */+ fun createOrder() {+ val offer = _review.value.offer ?: return+ val pax = _passengers.value+ _booking.value = BookingState.Loading viewModelScope.launch {- if (favorites.value.any { it.bookingUrl == favorite.bookingUrl }) {- favoriteDao.deleteByUrl(favorite.bookingUrl)- } else {- favoriteDao.upsert(favorite)+ runCatching {+ TravelApi.createOrder(+ OrderRequestDto(+ offerId = offer.offerId,+ passengers = pax,+ payment = PaymentInputDto(type = "balance"),+ )+ ) }+ .onSuccess { result ->+ persistTrip(offer, pax, result)+ _booking.value = BookingState.Success(result)+ }+ .onFailure { _booking.value = BookingState.Error(errorMessage(it)) } } } - fun removeFavorite(favorite: Favorite) {- viewModelScope.launch { favoriteDao.deleteByUrl(favorite.bookingUrl) }+ fun resetBooking() {+ _booking.value = BookingState.Idle+ }++ fun tripById(orderId: String): BookedTrip? = bookedTrips.value.find { it.orderId == orderId }++ private suspend fun persistTrip(+ offer: OfferDto,+ passengers: List<PassengerInputDto>,+ result: OrderResultDto,+ ) {+ val first = offer.slices.firstOrNull()+ val roundTrip = offer.slices.size > 1+ val route = if (first == null) {+ ""+ } else {+ val base = "${first.origin} → ${first.destination}"+ if (roundTrip) "$base (round trip)" else base+ }+ bookedTripDao.upsert(+ BookedTrip(+ orderId = result.orderId,+ bookingReference = result.bookingReference,+ route = route,+ departDate = first?.departureAt?.take(10).orEmpty(),+ amount = result.totalAmount,+ currency = result.currency,+ passengersJson = runCatching { json.encodeToString(passengers) }.getOrDefault(""),+ )+ ) } // --- Recents ----------------------------------------------------------@@ -176,6 +224,8 @@ class TravelViewModel( } companion object {+ private val json = Json { ignoreUnknownKeys = true }+ /** "2026-09-01" -> "Sep 1"; falls back to the raw string on any parse error. */ fun prettyDate(iso: String): String = runCatching { val date = java.time.LocalDate.parse(iso.take(10))@@ -190,13 +240,13 @@ class TravelViewModel( class TravelViewModelFactory( private val application: Application, private val recentSearchDao: RecentSearchDao,- private val favoriteDao: FavoriteDao,+ private val bookedTripDao: BookedTripDao, ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { require(modelClass.isAssignableFrom(TravelViewModel::class.java)) { "Unexpected ViewModel class: $modelClass" }- return TravelViewModel(application, recentSearchDao, favoriteDao) as T+ return TravelViewModel(application, recentSearchDao, bookedTripDao) as T } }