travel: dialog routes and per-route screenshot captures
- Commit
4c0729205a3bda43733cc22a82d342d6b71074cc- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 04:27 UTC (4 days ago)
- Parents
3573fd5
DialogAsRoute (2): the single-date picker in DateField and the passenger popup in PassengerField were gated by remember show-state. They are now Route destinations (DatePickerDialog, DateRangeDialog, PassengerPickerDialog) with DialogPage() entries in Navigation.kt, stateless contents under ui/dialogs/, their arguments in the routes, and results delivered through the nav result registry under caller-chosen keys (the calendar pattern). DateRangeFields pushes the range dialog the same way instead of gating its DatePickerDialog locally. PassengerDialog moves to ui/dialogs/PassengerPickerDialogContent, and FlightSearchForm/StaySearchForm/PlaceAutocompleteField take a back stack plus suggestion lambdas instead of the ViewModel. RouteScreenshotCoverage (20 routes + 3 new dialog routes): every Page is now a thin binder over a stateless Screen (state plus an Actions interface in platform/TravelUiContract.kt, following the existing FlightResults/SeatMap/OrderDetail/StayResults pattern), so MetadataPreviews renders each route from fixed literals: 1-flights-home through 20-settings, 21-date-picker-dialog, 22-date-range-dialog and 23-passenger-picker-dialog, with the old expanded capture renamed 24-flight-results-expanded. Compose tests host the fields the way Navigation does (a TestNavHost registry wrapper and updated widget/form tests); TravelW6Test's expired/live offers seed relative to the screen's real clock and carry the FIXTURE RELATIVE-TIME exception marker for it (that marker type is not in the structure-check inventory, so docs/structure/exceptions.tsv is unchanged). travel/AGENTS.md now documents Route.kt/Navigation.kt, the platform/ package (it said util/), the dialog routes and the screen/binder split. Verified: ./gradlew :travel:lint :travel:lintVitalRelease :travel:testDevUnitTest :travel:compileDevScreenshotTestKotlin :travel:compileReleaseKotlin all pass, with the lint analyze tasks re-run fresh (--rerun-tasks) so no stale cache hides FixtureDeterminism results.
Diff
travel/AGENTS.md
diff --git a/travel/AGENTS.md b/travel/AGENTS.mdindex 5176fcf308..e6c7f2dee6 100644--- a/travel/AGENTS.md+++ b/travel/AGENTS.md@@ -4,8 +4,8 @@ _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)+- Package roots present: ui, data, domain, network, platform+- Entry files: MainActivity.kt, Route.kt, Navigation.kt - Deps: :library:room, :library:network, :library:image, Stripe Android SDK (payment sheet) - Metadata: metadata_data/travel.md (present) - Rust: no / screenshotTest: yes@@ -19,17 +19,19 @@ _Install: ./install travel (dev by default)._ - 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`.+**Architecture / data-flow:** `ui/` search/results/booking pages → `platform/TravelViewModel` (+ `TravelUiContract`/`TravelUiState`, per-area `Travel*Ops`) → `domain/` grouping + `data/TravelRepository` over Room + `network/TravelApi`/`StaysApi`; booked trips stay readable from Room when offline. Every `*Page` is a thin binder over a stateless `*Screen` (state + `*Actions` from `platform/TravelUiContract.kt`), which is what `src/screenshotTest` renders.+**Entry points + reading order:** `MainActivity.kt` → `Navigation.kt` → `ui/HomePage.kt` → `ui/HomeScreen.kt` → `ui/FlightSearchForm.kt` → `platform/TravelViewModel.kt` → `platform/TravelSearchOps.kt` → `network/TravelApi.kt`. **Gotchas:**-- `util/` is NOT a closed package root — don't add more files there+- Dialogs are routes: `Route.DatePickerDialog`/`DateRangeDialog`/`PassengerPickerDialog` (`DialogPage()` entries in `Navigation.kt`, stateless contents in `ui/dialogs/`, results via the nav result registry under the caller's key). `DateField`/`DateRangeFields`/`PassengerField` push them; never gate a picker on `remember` show-state - 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)+### Root — entry + navigation - com/vayunmathur/travel/MainActivity.kt+- com/vayunmathur/travel/Navigation.kt+- com/vayunmathur/travel/Route.kt ### data/ — Room trips + profiles - com/vayunmathur/travel/data/TravelDatabase.kt - com/vayunmathur/travel/data/TravelRepository.kt@@ -40,8 +42,6 @@ _Install: ./install travel (dev by default)._ ### domain/ — on-device offer + trip logic - com/vayunmathur/travel/domain/OfferGrouping.kt - com/vayunmathur/travel/domain/TripStatus.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@@ -52,16 +52,17 @@ _Install: ./install travel (dev by default)._ - com/vayunmathur/travel/network/PlaceDto.kt - com/vayunmathur/travel/network/StaysApi.kt - com/vayunmathur/travel/network/StaysDto.kt-### util/ — ViewModel + booking ops-- com/vayunmathur/travel/util/TravelViewModel.kt-- com/vayunmathur/travel/util/TravelUiContract.kt-- com/vayunmathur/travel/util/TravelUiState.kt-- com/vayunmathur/travel/util/TravelSearchOps.kt-- com/vayunmathur/travel/util/TravelBookingOps.kt-- com/vayunmathur/travel/util/TravelOrderOps.kt-- com/vayunmathur/travel/util/TravelCustomerOps.kt-- com/vayunmathur/travel/util/TravelStayOps.kt-- com/vayunmathur/travel/util/ContactAutofill.kt+### platform/ — ViewModel + booking ops+- com/vayunmathur/travel/platform/TravelViewModel.kt+- com/vayunmathur/travel/platform/TravelUiContract.kt+- com/vayunmathur/travel/platform/TravelUiState.kt+- com/vayunmathur/travel/platform/TravelSearchOps.kt+- com/vayunmathur/travel/platform/TravelBookingOps.kt+- com/vayunmathur/travel/platform/TravelOrderOps.kt+- com/vayunmathur/travel/platform/TravelCustomerOps.kt+- com/vayunmathur/travel/platform/TravelStayOps.kt+- com/vayunmathur/travel/platform/ContactAutofill.kt+- com/vayunmathur/travel/platform/StripeCheckout.kt ### ui/ — search, results, booking, trips, stays - com/vayunmathur/travel/ui/HomePage.kt - com/vayunmathur/travel/ui/FlightSearchForm.kt@@ -88,6 +89,11 @@ _Install: ./install travel (dev by default)._ - com/vayunmathur/travel/ui/SettingsPage.kt - com/vayunmathur/travel/ui/Common.kt - com/vayunmathur/travel/ui/TravelFormat.kt+- Stateless `*Screen` slices beside their `*Page` binders: HomeScreen, OfferReviewScreen, OutboundSelectScreen, FareSelectScreen, AncillariesScreen, PassengersScreen, PaymentScreen, ConfirmationScreen, CancellationScreen, ChangeScreen, StayDetailScreen, StayGuestsScreen, StayConfirmationScreen, TripsScreen, SettingsScreen (plus FlightResultsScreen, SeatMapScreen, OrderDetailScreen, StayResultsScreen)+- com/vayunmathur/travel/ui/dialogs/DatePickerDialogContent.kt+- com/vayunmathur/travel/ui/dialogs/DateRangeDialogContent.kt+- com/vayunmathur/travel/ui/dialogs/PassengerPickerDialogContent.kt+- screenshotTest `ui/MetadataPreviews.kt` — one deterministic capture per `Route` leaf (`1-flights-home` … `20-settings`, `21-date-picker-dialog`, `22-date-range-dialog`, `23-passenger-picker-dialog`, `24-flight-results-expanded`) ## Verify (this module only) ```
travel/src/main/java/com/vayunmathur/travel/Navigation.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/Navigation.kt b/travel/src/main/java/com/vayunmathur/travel/Navigation.ktindex 4fe06ec387..301a1b3b4b 100644--- a/travel/src/main/java/com/vayunmathur/travel/Navigation.kt+++ b/travel/src/main/java/com/vayunmathur/travel/Navigation.kt@@ -4,8 +4,11 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier+import androidx.compose.runtime.rememberCoroutineScope+import com.vayunmathur.library.util.DialogPage import com.vayunmathur.library.util.ListDetailPage import com.vayunmathur.library.util.ListPage+import com.vayunmathur.library.util.LocalNavResultRegistry import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.MorphPage import com.vayunmathur.library.util.OpenSettingsIfRequested@@ -30,7 +33,13 @@ import com.vayunmathur.travel.ui.StayConfirmationPage import com.vayunmathur.travel.ui.StayDetailPage import com.vayunmathur.travel.ui.StayGuestsPage import com.vayunmathur.travel.ui.StayResultsPage+import com.vayunmathur.travel.ui.PassengerMix import com.vayunmathur.travel.ui.TripsPage+import com.vayunmathur.travel.ui.dialogs.DatePickerDialogContent+import com.vayunmathur.travel.ui.dialogs.DateRangeDialogContent+import com.vayunmathur.travel.ui.dialogs.DateRangeSelection+import com.vayunmathur.travel.ui.dialogs.PassengerPickerDialogContent+import kotlinx.coroutines.launch @Composable fun Navigation(viewModel: TravelViewModel) {@@ -61,6 +70,54 @@ fun Navigation(viewModel: TravelViewModel) { entry<Route.StayConfirmation> { StayConfirmationPage(backStack, viewModel, it) } entry<Route.Trips>(metadata = ListPage()) { TripsPage(backStack, viewModel) } entry<Route.Settings> { SettingsPage(backStack, viewModel) }+ entry<Route.DatePickerDialog>(metadata = DialogPage()) { route ->+ val registry = LocalNavResultRegistry.current+ val scope = rememberCoroutineScope()+ DatePickerDialogContent(+ initialDate = route.initialDate,+ minDate = route.minDate,+ maxDate = route.maxDate,+ onDismiss = { backStack.pop() },+ onConfirm = { picked ->+ scope.launch { registry.dispatchResult(route.key, picked) }+ backStack.pop()+ },+ )+ }+ entry<Route.DateRangeDialog>(metadata = DialogPage()) { route ->+ val registry = LocalNavResultRegistry.current+ val scope = rememberCoroutineScope()+ DateRangeDialogContent(+ startLabel = route.startLabel,+ endLabel = route.endLabel,+ start = route.start,+ end = route.end,+ minDate = route.minDate,+ allowSameDay = route.allowSameDay,+ onDismiss = { backStack.pop() },+ onConfirm = { start, end ->+ scope.launch { registry.dispatchResult(route.key, DateRangeSelection(start, end)) }+ backStack.pop()+ },+ )+ }+ entry<Route.PassengerPickerDialog>(metadata = DialogPage()) { route ->+ val registry = LocalNavResultRegistry.current+ val scope = rememberCoroutineScope()+ PassengerPickerDialogContent(+ mix = PassengerMix(+ adults = route.adults,+ childAges = route.childAges,+ infantsInSeat = route.infantsInSeat,+ infantsOnLap = route.infantsOnLap,+ ),+ onDone = { picked ->+ scope.launch { registry.dispatchResult(route.key, picked) }+ backStack.pop()+ },+ onCancel = { backStack.pop() },+ )+ } } } }
travel/src/main/java/com/vayunmathur/travel/Route.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/Route.kt b/travel/src/main/java/com/vayunmathur/travel/Route.ktindex aa34a298a6..42ff6b72f0 100644--- a/travel/src/main/java/com/vayunmathur/travel/Route.kt+++ b/travel/src/main/java/com/vayunmathur/travel/Route.kt@@ -108,4 +108,46 @@ sealed interface Route : NavKey { /** Singleton holding settings state and operations. */ @Serializable data object Settings : Route++ /**+ * Single-date picker dialog. [key] names the result the caller consumes+ * with `ResultEffect<LocalDate>`; [initialDate]/[minDate]/[maxDate] are+ * ISO `YYYY-MM-DD` strings (empty/null when unset).+ */+ @Serializable+ data class DatePickerDialog(+ val key: String,+ val initialDate: String,+ val minDate: String? = null,+ val maxDate: String? = null,+ ) : Route++ /**+ * Range date picker dialog (depart/return, check-in/check-out). [key]+ * names the `DateRangeSelection` result; labels and bounds travel in the+ * route like the single-date picker.+ */+ @Serializable+ data class DateRangeDialog(+ val key: String,+ val startLabel: String,+ val endLabel: String,+ val start: String,+ val end: String,+ val minDate: String? = null,+ val allowSameDay: Boolean = true,+ ) : Route++ /**+ * Passenger-mix picker dialog. [key] names the `PassengerMix` result;+ * the current mix travels in the route instead of screen-local state.+ */+ @Serializable+ data class PassengerPickerDialog(+ val key: String,+ val adults: Int,+ val childAges: List<Int>,+ val infantsInSeat: Int,+ val infantsOnLap: Int,+ ) : Route }
travel/src/main/java/com/vayunmathur/travel/platform/TravelUiContract.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/platform/TravelUiContract.kt b/travel/src/main/java/com/vayunmathur/travel/platform/TravelUiContract.ktindex 5ed611d07f..27e7cd8335 100644--- a/travel/src/main/java/com/vayunmathur/travel/platform/TravelUiContract.kt+++ b/travel/src/main/java/com/vayunmathur/travel/platform/TravelUiContract.kt@@ -94,3 +94,185 @@ interface OrderDetailActions { val Noop: OrderDetailActions = object : OrderDetailActions {} } }++/** Home (flights/stays search) callbacks. Same no-op-default arrangement. */+interface HomeActions {+ fun onFlightState(state: com.vayunmathur.travel.ui.FlightFormState) {}+ fun onStayState(state: com.vayunmathur.travel.ui.StayFormState) {}+ fun searchFlights(query: FlightQuery) {}+ fun searchStays(place: String, checkIn: String, checkOut: String, rooms: Int, adults: Int, latitude: Double?, longitude: Double?) {}+ fun openTrips() {}+ fun openSettings() {}+ fun clearRecents() {}+ fun openRecent(recent: com.vayunmathur.travel.data.RecentSearch) {}+ fun openTrip(trip: com.vayunmathur.travel.data.BookedTrip) {}+ fun seeAllTrips() {}+ fun selectFlights() {}+ fun selectStays() {}++ companion object {+ val Noop: HomeActions = object : HomeActions {}+ }+}++/** Offer-review callbacks. */+interface OfferReviewActions {+ fun continueToPassengers(offer: OfferDto) {}+ fun refreshOffer(offerId: String) {}+ fun back() {}++ companion object {+ val Noop: OfferReviewActions = object : OfferReviewActions {}+ }+}++/** Round-trip outbound-selection callbacks. */+interface OutboundSelectActions {+ fun pickReturn(offer: OfferDto, outboundSignature: String) {}+ fun back() {}++ companion object {+ val Noop: OutboundSelectActions = object : OutboundSelectActions {}+ }+}++/** Round-trip fare-selection callbacks. */+interface FareSelectActions {+ fun selectFare(offer: OfferDto) {}+ fun back() {}++ companion object {+ val Noop: FareSelectActions = object : FareSelectActions {}+ }+}++/** Ancillaries (extras) callbacks. */+interface AncillariesActions {+ fun setBaggageQuantity(serviceId: String, quantity: Long) {}+ fun setExtraQuantity(serviceId: String, quantity: Long) {}+ fun retrySeatMaps() {}+ fun openSeatMap(offerId: String, segmentId: String) {}+ fun continueToPayment(offer: OfferDto) {}+ fun back() {}++ companion object {+ val Noop: AncillariesActions = object : AncillariesActions {}+ }+}++/** Passengers-form callbacks. */+interface PassengersActions {+ fun prefillProfile(customer: com.vayunmathur.travel.data.Customer) {}+ fun updatePassenger(index: Int, passenger: com.vayunmathur.travel.network.PassengerInputDto) {}+ fun createTrip() {}+ fun back() {}++ companion object {+ val Noop: PassengersActions = object : PassengersActions {}+ }+}++/** Payment callbacks. */+interface PaymentActions {+ fun pay() {}+ fun acceptNewPrice() {}+ fun retryCheckout() {}+ fun back() {}++ companion object {+ val Noop: PaymentActions = object : PaymentActions {}+ }+}++/** Flight-confirmation callbacks. */+interface ConfirmationActions {+ fun completePayment() {}+ fun refreshStatus() {}+ fun done() {}+ fun viewItinerary() {}+ fun viewTrips() {}+ fun backToSearch() {}++ companion object {+ val Noop: ConfirmationActions = object : ConfirmationActions {}+ }+}++/** Stay-confirmation callbacks. */+interface StayConfirmationActions {+ fun completePayment() {}+ fun refreshStatus() {}+ fun done() {}++ companion object {+ val Noop: StayConfirmationActions = object : StayConfirmationActions {}+ }+}++/** Cancellation callbacks. */+interface CancellationActions {+ fun confirm() {}+ fun done() {}+ fun back() {}++ companion object {+ val Noop: CancellationActions = object : CancellationActions {}+ }+}++/** Change-flight callbacks. */+interface ChangeActions {+ fun requestChange(slice: com.vayunmathur.travel.network.SliceDto, newDate: String) {}+ fun priceChange(offer: com.vayunmathur.travel.network.ChangeOfferDto) {}+ fun confirmChange(offer: com.vayunmathur.travel.network.ChangeOfferDto) {}+ fun done() {}+ fun back() {}++ companion object {+ val Noop: ChangeActions = object : ChangeActions {}+ }+}++/** Trips-hub callbacks. */+interface TripsActions {+ fun openTrip(trip: com.vayunmathur.travel.data.BookedTrip) {}+ fun refreshTrip(trip: com.vayunmathur.travel.data.BookedTrip) {}+ fun back() {}++ companion object {+ val Noop: TripsActions = object : TripsActions {}+ }+}++/** Settings callbacks. */+interface SettingsActions {+ fun removeFrequentFlyer(airlineIata: String) {}+ fun saveFrequentFlyer(iata: String, number: String, name: String) {}+ fun removeCustomer(id: String) {}+ fun createCustomer(email: String, given: String, family: String, phone: String) {}+ fun back() {}++ companion object {+ val Noop: SettingsActions = object : SettingsActions {}+ }+}++/** Stay-detail callbacks. */+interface StayDetailActions {+ fun openRate(rateId: String) {}+ fun back() {}++ companion object {+ val Noop: StayDetailActions = object : StayDetailActions {}+ }+}++/** Stay-guests callbacks. */+interface StayGuestsActions {+ fun bookStay(guest: com.vayunmathur.travel.network.StayGuestInputDto, email: String, phone: String) {}+ fun back() {}++ companion object {+ val Noop: StayGuestsActions = object : StayGuestsActions {}+ }+}
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 89e6fc47dc..df825c1570 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesPage.kt@@ -1,50 +1,20 @@ package com.vayunmathur.travel.ui-import com.vayunmathur.travel.R-import com.vayunmathur.library.ui.R as UiR -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.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.compose.runtime.remember import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.AppScaffold-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.IconAdd-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconRemove-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route-import com.vayunmathur.travel.network.ServiceDto-import com.vayunmathur.travel.platform.AncillariesState+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.platform.AncillariesActions import com.vayunmathur.travel.platform.TravelViewModel-import com.vayunmathur.travel.platform.initPassengers import com.vayunmathur.travel.platform.retrySeatMaps import com.vayunmathur.travel.platform.saveAncillaries import com.vayunmathur.travel.platform.setBaggageQuantity import com.vayunmathur.travel.platform.setExtraQuantity-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 checkout.- */-@OptIn(ExperimentalMaterial3Api::class)+/** Binds [TravelViewModel] and the back stack to the stateless [AncillariesScreen]. */ @Composable fun AncillariesPage( backStack: NavBackStack<Route>,@@ -56,240 +26,33 @@ fun AncillariesPage( val selectedBaggage by viewModel.selectedBaggage.collectAsStateWithLifecycle() val selectedExtras by viewModel.selectedExtras.collectAsStateWithLifecycle() val selectedSeats by viewModel.selectedSeats.collectAsStateWithLifecycle()- val offer = review.offer- val services = state.ancillaries?.services.orEmpty() - AppScaffold(- title = stringResource(R.string.add_extras),- backStack = backStack,- ) { padding ->- if (offer == null) {- StatusBox(loading = false, error = null, isEmpty = true, emptyMessage = "No offer selected.")- return@AppScaffold- }- if (state.loading && services.isEmpty()) {- StatusBox(loading = true, error = null, isEmpty = false, modifier = Modifier.padding(padding))- return@AppScaffold- }- Column(- Modifier- .fillMaxSize()- .padding(padding)- .verticalScroll(rememberScrollState())- .padding(16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp),- ) {- val passengerCount = offer.passengers.size.coerceAtLeast(1)- val multiPassenger = passengerCount > 1- val bags = services.filter { it.type == "baggage" }- if (bags.isNotEmpty()) {- SectionHeader(stringResource(R.string.extra_baggage))- bags.forEach { svc ->- BaggageRow(- service = svc,- quantity = selectedBaggage[svc.id] ?: 0L,- passengerLabel = if (multiPassenger) passengerLabel(offer, svc.passengerIds.firstOrNull()) else null,- onQuantity = { viewModel.setBaggageQuantity(svc.id, it) },- )- }- }+ val actions = remember(viewModel, backStack) {+ object : AncillariesActions {+ override fun setBaggageQuantity(serviceId: String, quantity: Long) =+ viewModel.setBaggageQuantity(serviceId, quantity) - val extras = services.filter { it.type != "baggage" && it.type != "seat" }- if (extras.isNotEmpty()) {- SectionHeader(stringResource(R.string.extras))- extras.forEach { svc ->- ExtraServiceRow(- service = svc,- quantity = selectedExtras[svc.id] ?: 0L,- passengerLabel = if (multiPassenger) passengerLabel(offer, svc.passengerIds.firstOrNull()) else null,- onQuantity = { viewModel.setExtraQuantity(svc.id, it) },- )- }- }+ override fun setExtraQuantity(serviceId: String, quantity: Long) =+ viewModel.setExtraQuantity(serviceId, quantity) - SectionHeader(stringResource(R.string.seats_1))- if (state.seatMapsLoading) {- SeatMapsPendingCard { viewModel.retrySeatMaps() }- }- offer.slices.forEach { slice ->- slice.segments.forEach { seg ->- val segSeats = selectedSeats.filterKeys { it.startsWith("${seg.id}|") }.values- val chosenLabels = segSeats.joinToString(", ") { it.designator }- ElevatedCard(Modifier.fillMaxWidth()) {- Row(- Modifier.fillMaxWidth().padding(16.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween,- ) {- Column(Modifier.weight(1f)) {- Text("${seg.origin} → ${seg.destination}", style = MaterialTheme.typography.bodyLarge)- if (chosenLabels.isNotBlank()) {- Text(- stringResource(R.string.seats, chosenLabels),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.primary,- )- }- }- OutlinedButton(- onClick = { backStack.add(Route.SeatMap(offer.offerId, seg.id)) },- enabled = seg.id.isNotBlank(),- ) { Text(if (segSeats.isNotEmpty()) stringResource(R.string.change) else stringResource(R.string.choose)) }- }- }- }+ override fun retrySeatMaps() = viewModel.retrySeatMaps()+ override fun openSeatMap(offerId: String, segmentId: String) {+ backStack.add(Route.SeatMap(offerId, segmentId)) } - HorizontalDivider()- ExtrasSummary(offer.currency, services, selectedBaggage, selectedExtras, selectedSeats)-- state.error?.let {- Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)- }-- Button(- onClick = {- viewModel.saveAncillaries { backStack.add(Route.Payment(offer.offerId)) }- },- enabled = !state.loading,- modifier = Modifier.fillMaxWidth(),- ) { Text(stringResource(R.string.continue_to_checkout)) }- }- }-}--@Composable-private fun BaggageRow(- service: ServiceDto,- quantity: Long,- passengerLabel: String?,- onQuantity: (Long) -> Unit,-) {- ElevatedCard(Modifier.fillMaxWidth()) {- Row(- Modifier.fillMaxWidth().padding(16.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(8.dp),- ) {- Column(Modifier.weight(1f)) {- Text(service.title.ifBlank { stringResource(R.string.extra_bag) }, style = MaterialTheme.typography.bodyLarge)- Text(- formatMoney(service.totalAmount, service.totalCurrency) + stringResource(R.string.each),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- if (passengerLabel != null) {- Text(- stringResource(R.string.for_passenger, passengerLabel),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.primary,- )- }- }- // Compact stepper (must not fill width, or it squeezes the title column).- val max = service.maxQuantity.toInt().coerceAtLeast(1)- IconButton(- onClick = { onQuantity((quantity - 1).coerceAtLeast(0)) },- enabled = quantity > 0,- ) { IconRemove() }- Text("$quantity", style = MaterialTheme.typography.titleMedium)- IconButton(- onClick = { onQuantity((quantity + 1).coerceAtMost(max.toLong())) },- enabled = quantity < max,- ) { IconAdd() }- }- }-}--/** A non-baggage service (CFAR, priority boarding, …) as an on/off toggle. */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-private fun ExtraServiceRow(- service: ServiceDto,- quantity: Long,- passengerLabel: String?,- onQuantity: (Long) -> Unit,-) {- ElevatedCard(Modifier.fillMaxWidth()) {- Row(- Modifier.fillMaxWidth().padding(16.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(8.dp),- ) {- Column(Modifier.weight(1f)) {- Text(service.title.ifBlank { stringResource(R.string.extra) }, style = MaterialTheme.typography.bodyLarge)- Text(- formatMoney(service.totalAmount, service.totalCurrency),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- if (passengerLabel != null) {- Text(- stringResource(R.string.for_passenger, passengerLabel),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.primary,- )- }+ override fun continueToPayment(offer: OfferDto) {+ viewModel.saveAncillaries { backStack.add(Route.Payment(offer.offerId)) } }- com.vayunmathur.library.ui.Switch(- checked = quantity > 0,- onCheckedChange = { onQuantity(if (it) 1L else 0L) },- )- }- }-}--/** A human label for a passenger id, e.g. "Adult 1" / "Child 2". */-private fun passengerLabel(offer: com.vayunmathur.travel.network.OfferDto, passengerId: String?): String? {- if (passengerId == null) return null- val index = offer.passengers.indexOfFirst { it.id == passengerId }- if (index < 0) return null- val kind = offer.passengers[index].type- .replace('_', ' ')- .replaceFirstChar { it.uppercase() }- .ifBlank { "Passenger" }- return "$kind ${index + 1}"-} -@Composable-private fun SeatMapsPendingCard(onRetry: () -> Unit) {- ElevatedCard(Modifier.fillMaxWidth()) {- Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text(- stringResource(R.string.seat_maps_still_loading),- style = MaterialTheme.typography.bodyMedium,- )- OutlinedButton(onClick = onRetry, modifier = Modifier.fillMaxWidth()) {- Text(stringResource(UiR.string.retry))- }+ override fun back() = backStack.pop() } }-}--@Composable-private fun ExtrasSummary(- currency: String,- services: List<ServiceDto>,- selectedBaggage: Map<String, Long>,- selectedExtras: Map<String, Long>,- selectedSeats: Map<String, com.vayunmathur.travel.network.SeatElementDto>,-) {- var total = 0.0- (selectedBaggage + selectedExtras).forEach { (id, qty) ->- val svc = services.find { it.id == id }- total += (svc?.totalAmount?.toDoubleOrNull() ?: 0.0) * qty- }- selectedSeats.values.forEach { total += it.totalAmount?.toDoubleOrNull() ?: 0.0 }- Row(- Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- ) {- Text(stringResource(R.string.extras), style = MaterialTheme.typography.titleMedium)- Text(- formatMoney(total.toString(), currency),- style = MaterialTheme.typography.titleMedium,- fontWeight = FontWeight.SemiBold,- color = MaterialTheme.colorScheme.primary,- )- }+ AncillariesScreen(+ state = state,+ offer = review.offer,+ selectedBaggage = selectedBaggage,+ selectedExtras = selectedExtras,+ selectedSeats = selectedSeats,+ actions = actions,+ ) }
travel/src/main/java/com/vayunmathur/travel/ui/AncillariesScreen.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesScreen.kt b/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesScreen.ktnew file mode 100644index 0000000000..a445540d31--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/AncillariesScreen.kt@@ -0,0 +1,283 @@+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.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+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.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconRemove+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.travel.R+import com.vayunmathur.travel.network.OfferDto+import com.vayunmathur.travel.network.SeatElementDto+import com.vayunmathur.travel.network.ServiceDto+import com.vayunmathur.travel.platform.AncillariesActions+import com.vayunmathur.travel.platform.AncillariesState++/**+ * Stateless extras step: bag services + seat-map entries off the created+ * trip. Rendered from literals by previews.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun AncillariesScreen(+ state: AncillariesState,+ offer: OfferDto?,+ selectedBaggage: Map<String, Long>,+ selectedExtras: Map<String, Long>,+ selectedSeats: Map<String, SeatElementDto>,+ actions: AncillariesActions,+) {+ val services = state.ancillaries?.services.orEmpty()++ AppScaffold(+ title = stringResource(R.string.add_extras),+ onNavigateBack = { actions.back() },+ ) { padding ->+ if (offer == null) {+ StatusBox(loading = false, error = null, isEmpty = true, emptyMessage = "No offer selected.")+ return@AppScaffold+ }+ if (state.loading && services.isEmpty()) {+ StatusBox(loading = true, error = null, isEmpty = false, modifier = Modifier.padding(padding))+ return@AppScaffold+ }+ Column(+ Modifier+ .fillMaxSize()+ .padding(padding)+ .verticalScroll(rememberScrollState())+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ val passengerCount = offer.passengers.size.coerceAtLeast(1)+ val multiPassenger = passengerCount > 1+ val bags = services.filter { it.type == "baggage" }+ if (bags.isNotEmpty()) {+ SectionHeader(stringResource(R.string.extra_baggage))+ bags.forEach { svc ->+ BaggageRow(+ service = svc,+ quantity = selectedBaggage[svc.id] ?: 0L,+ passengerLabel = if (multiPassenger) ancillaryPassengerLabel(offer, svc.passengerIds.firstOrNull()) else null,+ onQuantity = { actions.setBaggageQuantity(svc.id, it) },+ )+ }+ }++ val extras = services.filter { it.type != "baggage" && it.type != "seat" }+ if (extras.isNotEmpty()) {+ SectionHeader(stringResource(R.string.extras))+ extras.forEach { svc ->+ ExtraServiceRow(+ service = svc,+ quantity = selectedExtras[svc.id] ?: 0L,+ passengerLabel = if (multiPassenger) ancillaryPassengerLabel(offer, svc.passengerIds.firstOrNull()) else null,+ onQuantity = { actions.setExtraQuantity(svc.id, it) },+ )+ }+ }++ SectionHeader(stringResource(R.string.seats_1))+ if (state.seatMapsLoading) {+ SeatMapsPendingCard { actions.retrySeatMaps() }+ }+ offer.slices.forEach { slice ->+ slice.segments.forEach { seg ->+ val segSeats = selectedSeats.filterKeys { it.startsWith("${seg.id}|") }.values+ val chosenLabels = segSeats.joinToString(", ") { it.designator }+ ElevatedCard(Modifier.fillMaxWidth()) {+ Row(+ Modifier.fillMaxWidth().padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Column(Modifier.weight(1f)) {+ Text("${seg.origin} → ${seg.destination}", style = MaterialTheme.typography.bodyLarge)+ if (chosenLabels.isNotBlank()) {+ Text(+ stringResource(R.string.seats, chosenLabels),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.primary,+ )+ }+ }+ OutlinedButton(+ onClick = { actions.openSeatMap(offer.offerId, seg.id) },+ enabled = seg.id.isNotBlank(),+ ) { Text(if (segSeats.isNotEmpty()) stringResource(R.string.change) else stringResource(R.string.choose)) }+ }+ }+ }+ }++ HorizontalDivider()+ ExtrasSummary(offer.currency, services, selectedBaggage, selectedExtras, selectedSeats)++ state.error?.let {+ Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)+ }++ Button(+ onClick = { actions.continueToPayment(offer) },+ enabled = !state.loading,+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.continue_to_checkout)) }+ }+ }+}++@Composable+private fun BaggageRow(+ service: ServiceDto,+ quantity: Long,+ passengerLabel: String?,+ onQuantity: (Long) -> Unit,+) {+ ElevatedCard(Modifier.fillMaxWidth()) {+ Row(+ Modifier.fillMaxWidth().padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Column(Modifier.weight(1f)) {+ Text(service.title.ifBlank { stringResource(R.string.extra_bag) }, style = MaterialTheme.typography.bodyLarge)+ Text(+ formatMoney(service.totalAmount, service.totalCurrency) + stringResource(R.string.each),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ if (passengerLabel != null) {+ Text(+ stringResource(R.string.for_passenger, passengerLabel),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.primary,+ )+ }+ }+ val max = service.maxQuantity.toInt().coerceAtLeast(1)+ IconButton(+ onClick = { onQuantity((quantity - 1).coerceAtLeast(0)) },+ enabled = quantity > 0,+ ) { IconRemove() }+ Text("$quantity", style = MaterialTheme.typography.titleMedium)+ IconButton(+ onClick = { onQuantity((quantity + 1).coerceAtMost(max.toLong())) },+ enabled = quantity < max,+ ) { IconAdd() }+ }+ }+}++/** A non-baggage service (CFAR, priority boarding, …) as an on/off toggle. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun ExtraServiceRow(+ service: ServiceDto,+ quantity: Long,+ passengerLabel: String?,+ onQuantity: (Long) -> Unit,+) {+ ElevatedCard(Modifier.fillMaxWidth()) {+ Row(+ Modifier.fillMaxWidth().padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Column(Modifier.weight(1f)) {+ Text(service.title.ifBlank { stringResource(R.string.extra) }, style = MaterialTheme.typography.bodyLarge)+ Text(+ formatMoney(service.totalAmount, service.totalCurrency),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ if (passengerLabel != null) {+ Text(+ stringResource(R.string.for_passenger, passengerLabel),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.primary,+ )+ }+ }+ Switch(+ checked = quantity > 0,+ onCheckedChange = { onQuantity(if (it) 1L else 0L) },+ )+ }+ }+}++/** A human label for a passenger id, e.g. "Adult 1" / "Child 2". */+private fun ancillaryPassengerLabel(offer: OfferDto, passengerId: String?): String? {+ if (passengerId == null) return null+ val index = offer.passengers.indexOfFirst { it.id == passengerId }+ if (index < 0) return null+ val kind = offer.passengers[index].type+ .replace('_', ' ')+ .replaceFirstChar { it.uppercase() }+ .ifBlank { "Passenger" }+ return "$kind ${index + 1}"+}++@Composable+private fun SeatMapsPendingCard(onRetry: () -> Unit) {+ ElevatedCard(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(+ stringResource(R.string.seat_maps_still_loading),+ style = MaterialTheme.typography.bodyMedium,+ )+ OutlinedButton(onClick = onRetry, modifier = Modifier.fillMaxWidth()) {+ Text(stringResource(UiR.string.retry))+ }+ }+ }+}++@Composable+private fun ExtrasSummary(+ currency: String,+ services: List<ServiceDto>,+ selectedBaggage: Map<String, Long>,+ selectedExtras: Map<String, Long>,+ selectedSeats: Map<String, SeatElementDto>,+) {+ var total = 0.0+ (selectedBaggage + selectedExtras).forEach { (id, qty) ->+ val svc = services.find { it.id == id }+ total += (svc?.totalAmount?.toDoubleOrNull() ?: 0.0) * qty+ }+ selectedSeats.values.forEach { total += it.totalAmount?.toDoubleOrNull() ?: 0.0 }+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Text(stringResource(R.string.extras), style = MaterialTheme.typography.titleMedium)+ Text(+ formatMoney(total.toString(), currency),+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.SemiBold,+ color = MaterialTheme.colorScheme.primary,+ )+ }+}
travel/src/main/java/com/vayunmathur/travel/ui/CancellationPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/CancellationPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/CancellationPage.ktindex 6f89549469..14332305d0 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/CancellationPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/CancellationPage.kt@@ -1,42 +1,19 @@ package com.vayunmathur.travel.ui-import com.vayunmathur.travel.R -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.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.compose.runtime.remember import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.DetailScaffold-import com.vayunmathur.library.ui.ElevatedCard-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.IconCheckCircle-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route+import com.vayunmathur.travel.platform.CancellationActions import com.vayunmathur.travel.platform.TravelViewModel import com.vayunmathur.travel.platform.confirmCancellation import com.vayunmathur.travel.platform.quoteCancellation import com.vayunmathur.travel.platform.resetCancellation-import androidx.compose.ui.res.stringResource -/**- * Shared flight/hotel cancellation: preview (refund, penalty,- * commitable/message) → confirm → poll until succeeded/failed.- */-@OptIn(ExperimentalMaterial3Api::class)+/** Binds [TravelViewModel] and the back stack to the stateless [CancellationScreen]. */ @Composable fun CancellationPage( backStack: NavBackStack<Route>,@@ -47,98 +24,16 @@ fun CancellationPage( LaunchedEffect(route.orderId) { viewModel.quoteCancellation(route.orderId) } - DetailScaffold(- title = stringResource(R.string.cancel_order),- onNavigateBack = { backStack.pop() },- ) {- Column(- Modifier.fillMaxWidth(),- verticalArrangement = Arrangement.spacedBy(16.dp),- horizontalAlignment = Alignment.CenterHorizontally,- ) {- when {- state.done -> {- IconCheckCircle(- modifier = Modifier.size(64.dp),- tint = MaterialTheme.colorScheme.primary,- )- Text(stringResource(R.string.order_cancelled), style = MaterialTheme.typography.headlineSmall)- state.quote?.let {- Text(- stringResource(R.string.refund_of_issued_to_your, formatMoney(it.refundAmount, it.refundCurrency), it.refundTo.ifBlank { stringResource(R.string.original_payment) }),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- Button(- onClick = {- viewModel.resetCancellation()- backStack.reset(Route.FlightsHome, Route.Trips)- },- modifier = Modifier.fillMaxWidth(),- ) { Text(stringResource(UiR.string.done)) }- }- state.quote != null -> {- val quote = state.quote!!- ElevatedCard(Modifier.fillMaxWidth()) {- Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {- Text(stringResource(R.string.cancel_this_order), style = MaterialTheme.typography.titleMedium)- HorizontalDivider()- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {- Text(stringResource(R.string.refund), color = MaterialTheme.colorScheme.onSurfaceVariant)- Text(- formatMoney(quote.refundAmount, quote.refundCurrency),- style = MaterialTheme.typography.titleMedium,- color = MaterialTheme.colorScheme.primary,- fontWeight = FontWeight.SemiBold,- )- }- if (!quote.penaltyAmount.isNullOrBlank()) {- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {- Text(stringResource(R.string.penalty), color = MaterialTheme.colorScheme.onSurfaceVariant)- Text(- formatMoney(quote.penaltyAmount, quote.refundCurrency),- style = MaterialTheme.typography.bodyMedium,- )- }- }- Text(- stringResource(R.string.refunded_to_your, quote.refundTo.ifBlank { stringResource(R.string.original_payment) }),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- if (!quote.message.isNullOrBlank()) {- Text(- quote.message,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- }- }- state.error?.let {- Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)- }- if (state.polling) {- Text(- stringResource(R.string.cancellation_processing),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- Button(- onClick = { viewModel.confirmCancellation(route.orderId) },- enabled = !state.confirming && !state.polling && quote.commitable,- modifier = Modifier.fillMaxWidth(),- ) { Text(if (state.confirming) stringResource(R.string.cancelling) else stringResource(R.string.confirm_cancellation)) }- }- else -> StatusBox(- loading = state.loading,- error = state.error,- isEmpty = !state.loading && state.error == null,- emptyMessage = "This order can't be cancelled.",- )+ val actions = remember(viewModel, backStack, route.orderId) {+ object : CancellationActions {+ override fun confirm() = viewModel.confirmCancellation(route.orderId)+ override fun done() {+ viewModel.resetCancellation()+ backStack.reset(Route.FlightsHome, Route.Trips) }++ override fun back() = backStack.pop() } }+ CancellationScreen(state = state, actions = actions) }
travel/src/main/java/com/vayunmathur/travel/ui/CancellationScreen.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/CancellationScreen.kt b/travel/src/main/java/com/vayunmathur/travel/ui/CancellationScreen.ktnew file mode 100644index 0000000000..11c16938ed--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/CancellationScreen.kt@@ -0,0 +1,126 @@+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.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconCheckCircle+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.Text+import com.vayunmathur.travel.R+import com.vayunmathur.travel.platform.CancellationActions+import com.vayunmathur.travel.platform.CancellationState++/**+ * Stateless cancellation flow: preview (refund, penalty, commitable/message)+ * → confirm → done, rendered from literals by previews.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun CancellationScreen(state: CancellationState, actions: CancellationActions) {+ DetailScaffold(+ title = stringResource(R.string.cancel_order),+ onNavigateBack = { actions.back() },+ ) {+ Column(+ Modifier.fillMaxWidth(),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ when {+ state.done -> {+ IconCheckCircle(+ modifier = Modifier.size(64.dp),+ tint = MaterialTheme.colorScheme.primary,+ )+ Text(stringResource(R.string.order_cancelled), style = MaterialTheme.typography.headlineSmall)+ state.quote?.let {+ Text(+ stringResource(R.string.refund_of_issued_to_your, formatMoney(it.refundAmount, it.refundCurrency), it.refundTo.ifBlank { stringResource(R.string.original_payment) }),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ Button(+ onClick = { actions.done() },+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(UiR.string.done)) }+ }+ state.quote != null -> {+ val quote = state.quote!!+ ElevatedCard(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Text(stringResource(R.string.cancel_this_order), style = MaterialTheme.typography.titleMedium)+ HorizontalDivider()+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ Text(stringResource(R.string.refund), color = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(+ formatMoney(quote.refundAmount, quote.refundCurrency),+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.primary,+ fontWeight = FontWeight.SemiBold,+ )+ }+ if (!quote.penaltyAmount.isNullOrBlank()) {+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ Text(stringResource(R.string.penalty), color = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(+ formatMoney(quote.penaltyAmount, quote.refundCurrency),+ style = MaterialTheme.typography.bodyMedium,+ )+ }+ }+ Text(+ stringResource(R.string.refunded_to_your, quote.refundTo.ifBlank { stringResource(R.string.original_payment) }),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ if (!quote.message.isNullOrBlank()) {+ Text(+ quote.message,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+ state.error?.let {+ Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)+ }+ if (state.polling) {+ Text(+ stringResource(R.string.cancellation_processing),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ Button(+ onClick = { actions.confirm() },+ enabled = !state.confirming && !state.polling && quote.commitable,+ modifier = Modifier.fillMaxWidth(),+ ) { Text(if (state.confirming) stringResource(R.string.cancelling) else stringResource(R.string.confirm_cancellation)) }+ }+ else -> StatusBox(+ loading = state.loading,+ error = state.error,+ isEmpty = !state.loading && state.error == null,+ emptyMessage = "This order can't be cancelled.",+ )+ }+ }+ }+}
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 1bcee5ad60..e809e3e93d 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/ChangePage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/ChangePage.kt@@ -1,51 +1,23 @@ package com.vayunmathur.travel.ui-import com.vayunmathur.travel.R -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.layout.size-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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-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.R as UiR-import com.vayunmathur.library.ui.AppScaffold-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.IconCheckCircle-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedCard-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.travel.Route import com.vayunmathur.travel.network.ChangeOfferDto import com.vayunmathur.travel.network.SliceDto+import com.vayunmathur.travel.platform.ChangeActions import com.vayunmathur.travel.platform.TravelViewModel import com.vayunmathur.travel.platform.confirmChange import com.vayunmathur.travel.platform.loadBookingDetail import com.vayunmathur.travel.platform.priceChange import com.vayunmathur.travel.platform.requestChange import com.vayunmathur.travel.platform.resetChange-import androidx.compose.ui.res.stringResource -@OptIn(ExperimentalMaterial3Api::class)+/** Binds [TravelViewModel] and the back stack to the stateless [ChangeScreen]. */ @Composable fun ChangePage( backStack: NavBackStack<Route>,@@ -60,190 +32,28 @@ fun ChangePage( viewModel.loadBookingDetail(route.orderId) } - var selectedSliceIndex by remember { mutableIntStateOf(0) }- var newDate by remember { mutableStateOf("") }-- AppScaffold(- title = stringResource(R.string.change_flights),- backStack = backStack,- ) { padding ->- val order = detail.order- Column(- Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp),- horizontalAlignment = Alignment.CenterHorizontally,- ) {- if (change.done) {- IconCheckCircle(- modifier = Modifier.size(64.dp),- tint = MaterialTheme.colorScheme.primary,+ val actions = remember(viewModel, backStack, route.orderId) {+ object : ChangeActions {+ override fun requestChange(slice: SliceDto, newDate: String) {+ viewModel.requestChange(+ orderId = route.orderId,+ removeSliceId = slice.id,+ origin = slice.origin,+ destination = slice.destination,+ newDate = newDate,+ cabin = "", )- Text(stringResource(R.string.change_confirmed), style = MaterialTheme.typography.headlineSmall)- Button(- onClick = {- viewModel.resetChange()- backStack.reset(Route.FlightsHome, Route.Trips)- },- modifier = Modifier.fillMaxWidth(),- ) { Text(stringResource(UiR.string.done)) }- return@Column- }-- if (order == null) {- StatusBox(loading = detail.loading, error = detail.error, isEmpty = !detail.loading)- return@Column } - if (!change.requested) {- Text(stringResource(R.string.pick_a_flight_to_change), style = MaterialTheme.typography.titleMedium, modifier = Modifier.fillMaxWidth())- order.slices.forEachIndexed { index, slice ->- SliceChoice(slice, selected = index == selectedSliceIndex) { selectedSliceIndex = index }- }- DateField(stringResource(R.string.new_date), newDate, onDate = { newDate = it }, modifier = Modifier.fillMaxWidth())- Button(- onClick = {- // The order can reload shorter while an index is- // selected; indexing directly would go out of bounds.- val slice = order.slices.getOrNull(selectedSliceIndex)- if (slice != null) {- viewModel.requestChange(- orderId = route.orderId,- removeSliceId = slice.id,- origin = slice.origin,- destination = slice.destination,- newDate = newDate,- cabin = "",- )- }- },- enabled = newDate.isNotBlank() && order.slices.getOrNull(selectedSliceIndex)?.id?.isNotBlank() == true,- modifier = Modifier.fillMaxWidth(),- ) { Text(stringResource(R.string.find_change_options)) }- } else {- if (change.loading) {- StatusBox(loading = true, error = null, isEmpty = false)- } else if (change.error != null) {- Text(change.error!!, color = MaterialTheme.colorScheme.error)- } else if (change.offers.isEmpty()) {- 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 {- Text(- stringResource(R.string.change_payment_needed),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- if (change.polling) {- Text(- stringResource(R.string.change_processing),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- change.offers.forEach { offer ->- ChangeOfferCard(- offer = offer,- price = if (change.pricingOfferId == offer.id) change.price else null,- pricing = change.loading && change.pricingOfferId == offer.id,- confirming = change.confirming,- onPrice = { viewModel.priceChange(route.orderId, offer.id) },- onConfirm = { viewModel.confirmChange(route.orderId, offer.id) },- )- }- change.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }- }+ override fun priceChange(offer: ChangeOfferDto) = viewModel.priceChange(route.orderId, offer.id)+ override fun confirmChange(offer: ChangeOfferDto) = viewModel.confirmChange(route.orderId, offer.id)+ override fun done() {+ viewModel.resetChange()+ backStack.reset(Route.FlightsHome, Route.Trips) }- }- }-} -@Composable-private fun SliceChoice(slice: SliceDto, selected: Boolean, onClick: () -> Unit) {- OutlinedCard(- modifier = Modifier.fillMaxWidth().clickable { onClick() },- ) {- Row(- Modifier.fillMaxWidth().padding(16.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween,- ) {- Column {- Text("${slice.origin} → ${slice.destination}", style = MaterialTheme.typography.bodyLarge)- Text(- TravelViewModel.prettyDate(slice.departureAt.take(10)),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- if (selected) {- IconCheckCircle(tint = MaterialTheme.colorScheme.primary)- }- }- }-}--@Composable-private fun ChangeOfferCard(- offer: ChangeOfferDto,- price: com.vayunmathur.travel.network.ChangePriceDto?,- pricing: Boolean,- confirming: Boolean,- onPrice: () -> Unit,- onConfirm: () -> Unit,-) {- ElevatedCard(Modifier.fillMaxWidth()) {- Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- offer.slices.forEach { slice ->- Text(- "${slice.origin} → ${slice.destination} · ${TravelViewModel.prettyDate(slice.departureAt.take(10))}",- style = MaterialTheme.typography.bodyMedium,- )- }- if (!offer.description.isBlank()) {- Text(- offer.description,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- HorizontalDivider()- val priced = price != null- val amount = price?.amount ?: offer.changeTotalAmount- val currency = price?.currency?.ifBlank { null } ?: offer.changeTotalCurrency- val diff = amount.toDoubleOrNull() ?: 0.0- Text(- when {- !priced && offer.changeTotalAmount.isBlank() -> stringResource(R.string.pricing_change)- diff > 0 -> stringResource(R.string.extra_to_pay, formatMoney(amount, currency))- diff < 0 -> stringResource(R.string.refund_1, formatMoney((-diff).toString(), currency))- else -> stringResource(R.string.no_price_change)- },- style = MaterialTheme.typography.titleSmall,- fontWeight = FontWeight.SemiBold,- color = MaterialTheme.colorScheme.primary,- )- if (priced && price.outcome.isNotBlank()) {- Text(- when (price.outcome) {- "pay" -> stringResource(R.string.extra_to_pay, formatMoney(price.amount, price.currency))- "refund" -> stringResource(R.string.refund_1, formatMoney(price.amount, price.currency))- else -> stringResource(R.string.no_price_change)- },- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- if (!priced) {- Button(onClick = onPrice, enabled = !pricing, modifier = Modifier.fillMaxWidth()) {- Text(if (pricing) stringResource(R.string.pricing_change) else stringResource(R.string.price_and_select))- }- } else {- Button(onClick = onConfirm, enabled = !confirming, modifier = Modifier.fillMaxWidth()) {- Text(if (confirming) stringResource(R.string.confirming) else stringResource(R.string.select_confirm))- }- }+ override fun back() = backStack.pop() } }+ ChangeScreen(detail = detail, change = change, backStack = backStack, actions = actions) }
travel/src/main/java/com/vayunmathur/travel/ui/ChangeScreen.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/ChangeScreen.kt b/travel/src/main/java/com/vayunmathur/travel/ui/ChangeScreen.ktnew file mode 100644index 0000000000..99844c5482--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/ChangeScreen.kt@@ -0,0 +1,229 @@+package com.vayunmathur.travel.ui+import com.vayunmathur.travel.R++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.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+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+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.AppScaffold+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.IconCheckCircle+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedCard+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.network.ChangeOfferDto+import com.vayunmathur.travel.network.SliceDto+import com.vayunmathur.travel.platform.ChangeActions+import com.vayunmathur.travel.platform.ChangeState+import com.vayunmathur.travel.platform.OrderDetailState+import com.vayunmathur.travel.platform.TravelViewModel+import androidx.compose.ui.res.stringResource++/**+ * Stateless change-flight flow: pick a slice + new date (via the shared+ * date-picker dialog route), then price/confirm an alternative. Rendered+ * from literals by previews.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ChangeScreen(+ detail: OrderDetailState,+ change: ChangeState,+ backStack: NavBackStack<Route>,+ actions: ChangeActions,+) {+ var selectedSliceIndex by remember { mutableIntStateOf(0) }+ var newDate by remember { mutableStateOf("") }++ AppScaffold(+ title = stringResource(R.string.change_flights),+ onNavigateBack = { actions.back() },+ ) { padding ->+ val order = detail.order+ Column(+ Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ if (change.done) {+ IconCheckCircle(+ modifier = Modifier.size(64.dp),+ tint = MaterialTheme.colorScheme.primary,+ )+ Text(stringResource(R.string.change_confirmed), style = MaterialTheme.typography.headlineSmall)+ Button(+ onClick = { actions.done() },+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(UiR.string.done)) }+ return@Column+ }++ if (order == null) {+ StatusBox(loading = detail.loading, error = detail.error, isEmpty = !detail.loading)+ return@Column+ }++ if (!change.requested) {+ Text(stringResource(R.string.pick_a_flight_to_change), style = MaterialTheme.typography.titleMedium, modifier = Modifier.fillMaxWidth())+ order.slices.forEachIndexed { index, slice ->+ SliceChoice(slice, selected = index == selectedSliceIndex) { selectedSliceIndex = index }+ }+ DateField(stringResource(R.string.new_date), newDate, onDate = { newDate = it }, backStack = backStack, resultKey = "travel-change-date", modifier = Modifier.fillMaxWidth())+ Button(+ onClick = {+ val slice = order.slices.getOrNull(selectedSliceIndex)+ if (slice != null) actions.requestChange(slice, newDate)+ },+ enabled = newDate.isNotBlank() && order.slices.getOrNull(selectedSliceIndex)?.id?.isNotBlank() == true,+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.find_change_options)) }+ } else {+ if (change.loading) {+ StatusBox(loading = true, error = null, isEmpty = false)+ } else if (change.error != null) {+ Text(change.error!!, color = MaterialTheme.colorScheme.error)+ } else if (change.offers.isEmpty()) {+ 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 {+ Text(+ stringResource(R.string.change_payment_needed),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ if (change.polling) {+ Text(+ stringResource(R.string.change_processing),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ change.offers.forEach { offer ->+ ChangeOfferCard(+ offer = offer,+ price = if (change.pricingOfferId == offer.id) change.price else null,+ pricing = change.loading && change.pricingOfferId == offer.id,+ confirming = change.confirming,+ onPrice = { actions.priceChange(offer) },+ onConfirm = { actions.confirmChange(offer) },+ )+ }+ change.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }+ }+ }+ }+ }+}++@Composable+private fun SliceChoice(slice: SliceDto, selected: Boolean, onClick: () -> Unit) {+ OutlinedCard(+ modifier = Modifier.fillMaxWidth().clickable { onClick() },+ ) {+ Row(+ Modifier.fillMaxWidth().padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Column {+ Text("${slice.origin} → ${slice.destination}", style = MaterialTheme.typography.bodyLarge)+ Text(+ TravelViewModel.prettyDate(slice.departureAt.take(10)),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ if (selected) {+ IconCheckCircle(tint = MaterialTheme.colorScheme.primary)+ }+ }+ }+}++@Composable+private fun ChangeOfferCard(+ offer: ChangeOfferDto,+ price: com.vayunmathur.travel.network.ChangePriceDto?,+ pricing: Boolean,+ confirming: Boolean,+ onPrice: () -> Unit,+ onConfirm: () -> Unit,+) {+ ElevatedCard(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ offer.slices.forEach { slice ->+ Text(+ "${slice.origin} → ${slice.destination} · ${TravelViewModel.prettyDate(slice.departureAt.take(10))}",+ style = MaterialTheme.typography.bodyMedium,+ )+ }+ if (!offer.description.isBlank()) {+ Text(+ offer.description,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ HorizontalDivider()+ val priced = price != null+ val amount = price?.amount ?: offer.changeTotalAmount+ val currency = price?.currency?.ifBlank { null } ?: offer.changeTotalCurrency+ val diff = amount.toDoubleOrNull() ?: 0.0+ Text(+ when {+ !priced && offer.changeTotalAmount.isBlank() -> stringResource(R.string.pricing_change)+ diff > 0 -> stringResource(R.string.extra_to_pay, formatMoney(amount, currency))+ diff < 0 -> stringResource(R.string.refund_1, formatMoney((-diff).toString(), currency))+ else -> stringResource(R.string.no_price_change)+ },+ style = MaterialTheme.typography.titleSmall,+ fontWeight = FontWeight.SemiBold,+ color = MaterialTheme.colorScheme.primary,+ )+ if (priced && price.outcome.isNotBlank()) {+ Text(+ when (price.outcome) {+ "pay" -> stringResource(R.string.extra_to_pay, formatMoney(price.amount, price.currency))+ "refund" -> stringResource(R.string.refund_1, formatMoney(price.amount, price.currency))+ else -> stringResource(R.string.no_price_change)+ },+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ if (!priced) {+ Button(onClick = onPrice, enabled = !pricing, modifier = Modifier.fillMaxWidth()) {+ Text(if (pricing) stringResource(R.string.pricing_change) else stringResource(R.string.price_and_select))+ }+ } else {+ Button(onClick = onConfirm, enabled = !confirming, modifier = Modifier.fillMaxWidth()) {+ Text(if (confirming) stringResource(R.string.confirming) else stringResource(R.string.select_confirm))+ }+ }+ }+ }+}
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 11aa8be49b..fa951ace0e 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationPage.kt@@ -1,61 +1,25 @@ package com.vayunmathur.travel.ui-import com.vayunmathur.travel.R -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.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.text.font.FontWeight-import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.DetailScaffold-import com.vayunmathur.library.ui.ElevatedCard-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.IconCheckCircle-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.Text 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-import com.vayunmathur.travel.data.TRIP_STATUS_PARTIAL-import com.vayunmathur.travel.data.TRIP_STATUS_PENDING_PAYMENT-import com.vayunmathur.travel.data.TRIP_STATUS_PROCESSING-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.platform.CardPaymentResult-import com.vayunmathur.travel.platform.rememberCardPayment import com.vayunmathur.travel.platform.CheckoutState+import com.vayunmathur.travel.platform.ConfirmationActions import com.vayunmathur.travel.platform.TravelViewModel-import com.vayunmathur.travel.platform.TripPollState import com.vayunmathur.travel.platform.confirmPaidTrip import com.vayunmathur.travel.platform.pollTrip import com.vayunmathur.travel.platform.recheckoutForStoredTrip-import androidx.compose.ui.res.stringResource+import com.vayunmathur.travel.platform.rememberCardPayment -/**- * 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" (in-app card sheet) + "Refresh status".- */-@OptIn(ExperimentalMaterial3Api::class)+/** Binds [TravelViewModel] and the back stack to the stateless [ConfirmationScreen]. */ @Composable fun ConfirmationPage( backStack: NavBackStack<Route>,@@ -90,146 +54,41 @@ fun ConfirmationPage( paying = cardPayment.present(ready.clientSecret, ready.publishableKey) } - DetailScaffold(- title = stringResource(confirmationTitle(trip?.status.orEmpty())),- ) {- Column(- Modifier.fillMaxWidth(),- verticalArrangement = Arrangement.spacedBy(16.dp),- horizontalAlignment = Alignment.CenterHorizontally,- ) {- if (trip == null) {- Text(stringResource(R.string.trip_not_found), color = MaterialTheme.colorScheme.onSurfaceVariant)- Button(onClick = { backStack.reset(Route.FlightsHome) }, modifier = Modifier.fillMaxWidth()) {- Text(stringResource(R.string.back_to_search))+ val actions = remember(viewModel, backStack, trip, checkout) {+ object : ConfirmationActions {+ override fun completePayment() {+ val current = trip ?: return+ val fresh = (checkout as? CheckoutState.Ready)?.checkout+ if (fresh != null && viewModel.currentTrip?.tripId == current.tripId.ifBlank { current.orderId }) {+ paying = cardPayment.present(fresh.clientSecret, fresh.publishableKey)+ } else {+ presentWhenReady = true+ viewModel.recheckoutForStoredTrip(current.orderId) }- return@Column } - IconCheckCircle(- modifier = Modifier.size(64.dp).padding(top = 8.dp),- tint = MaterialTheme.colorScheme.primary,- )- Text(- stringResource(confirmationHeadline(trip.status)),- style = MaterialTheme.typography.headlineSmall- )-- if (poll is TripPollState.Polling || trip.status == TRIP_STATUS_PROCESSING) {- Text(- stringResource(R.string.confirming_payment),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )+ override fun refreshStatus() {+ val current = trip ?: return+ viewModel.pollTrip(current.tripId.ifBlank { current.orderId }) } - ElevatedCard(Modifier.fillMaxWidth()) {- Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {- DetailRow(- stringResource(R.string.booking_reference),- trip.bookingReference.ifBlank { "—" },- emphasize = true- )- HorizontalDivider()- DetailRow(stringResource(R.string.route_label), trip.route)- DetailRow(stringResource(R.string.departs), TravelViewModel.prettyDate(trip.departDate))- DetailRow(- stringResource(if (isTripAwaitingPayment(trip.status)) R.string.amount_due else R.string.amount_paid),- formatMoney(trip.amount, trip.currency)- )- DetailRow(stringResource(R.string.status_label), stringResource(tripStatusLabel(trip.status)))- if (trip.status == TRIP_STATUS_FAILED && trip.failureMessage.isNotBlank()) {- Text(- trip.failureMessage,- color = MaterialTheme.colorScheme.error,- style = MaterialTheme.typography.bodySmall,- )- }- }+ override fun done() {+ backStack.reset(Route.FlightsHome) } - 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)- }- if (isCheckoutUnexpired(trip.checkoutExpiresAt)) {- val loading = checkout is CheckoutState.Loading- Button(- 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 {- Text(- stringResource(R.string.payment_link_expired),- color = MaterialTheme.colorScheme.onSurfaceVariant,- style = MaterialTheme.typography.bodySmall,- )- }+ override fun viewItinerary() {+ val current = trip ?: return+ backStack.add(Route.OrderDetail(current.orderId)) } - if (isTripPollingStatus(trip.status) || trip.status == TRIP_STATUS_PARTIAL) {- OutlinedButton(- onClick = { viewModel.pollTrip(trip.tripId.ifBlank { trip.orderId }) },- enabled = poll !is TripPollState.Polling,- modifier = Modifier.fillMaxWidth(),- ) { Text(stringResource(R.string.refresh_status)) }+ override fun viewTrips() {+ backStack.reset(Route.FlightsHome, Route.Trips) } - Button(onClick = { backStack.reset(Route.FlightsHome) }, modifier = Modifier.fillMaxWidth()) {- Text(stringResource(UiR.string.done))+ override fun backToSearch() {+ backStack.reset(Route.FlightsHome) }- OutlinedButton(- onClick = { backStack.add(Route.OrderDetail(trip.orderId)) },- modifier = Modifier.fillMaxWidth(),- ) { Text(stringResource(R.string.view_full_itinerary)) }- OutlinedButton(- onClick = { backStack.reset(Route.FlightsHome, Route.Trips) },- modifier = Modifier.fillMaxWidth(),- ) { Text(stringResource(R.string.view_my_trips)) } } }-}--private fun confirmationTitle(status: String): Int = when (status) {- TRIP_STATUS_PENDING_PAYMENT -> R.string.status_payment_pending- TRIP_STATUS_PROCESSING -> R.string.status_processing- TRIP_STATUS_PARTIAL -> R.string.status_partial- TRIP_STATUS_FAILED -> R.string.status_failed- else -> R.string.booking_confirmed-}--private fun confirmationHeadline(status: String): Int = when (status) {- TRIP_STATUS_PENDING_PAYMENT -> R.string.payment_pending_headline- TRIP_STATUS_PROCESSING -> R.string.confirming_payment- TRIP_STATUS_PARTIAL -> R.string.partial_headline- TRIP_STATUS_FAILED -> R.string.booking_failed_headline- else -> R.string.you_re_booked-}--@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,- )- }+ ConfirmationScreen(trip = trip, poll = poll, checkout = checkout, paying = paying, actions = actions) }
travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationScreen.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationScreen.kt b/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationScreen.ktnew file mode 100644index 0000000000..215632c38c--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/ConfirmationScreen.kt@@ -0,0 +1,188 @@+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.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconCheckCircle+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.Text+import com.vayunmathur.travel.R+import com.vayunmathur.travel.data.BookedTrip+import com.vayunmathur.travel.data.TRIP_STATUS_FAILED+import com.vayunmathur.travel.data.TRIP_STATUS_PARTIAL+import com.vayunmathur.travel.data.TRIP_STATUS_PENDING_PAYMENT+import com.vayunmathur.travel.data.TRIP_STATUS_PROCESSING+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.platform.CheckoutState+import com.vayunmathur.travel.platform.ConfirmationActions+import com.vayunmathur.travel.platform.TravelViewModel+import com.vayunmathur.travel.platform.TripPollState++/**+ * Stateless post-payment confirmation: the booked trip's final status with+ * its booking reference, plus complete-payment/refresh actions while the+ * payment is still pending. Rendered from literals by previews.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ConfirmationScreen(+ trip: BookedTrip?,+ poll: TripPollState,+ checkout: CheckoutState,+ paying: Boolean,+ actions: ConfirmationActions,+) {+ DetailScaffold(+ title = stringResource(confirmationTitle(trip?.status.orEmpty())),+ ) {+ Column(+ Modifier.fillMaxWidth(),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ if (trip == null) {+ Text(stringResource(R.string.trip_not_found), color = MaterialTheme.colorScheme.onSurfaceVariant)+ Button(onClick = { actions.backToSearch() }, modifier = Modifier.fillMaxWidth()) {+ Text(stringResource(R.string.back_to_search))+ }+ return@Column+ }++ IconCheckCircle(+ modifier = Modifier.size(64.dp).padding(top = 8.dp),+ tint = MaterialTheme.colorScheme.primary,+ )+ Text(+ stringResource(confirmationHeadline(trip.status)),+ style = MaterialTheme.typography.headlineSmall+ )++ if (poll is TripPollState.Polling || trip.status == TRIP_STATUS_PROCESSING) {+ Text(+ stringResource(R.string.confirming_payment),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }++ ElevatedCard(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {+ ConfirmationDetailRow(+ stringResource(R.string.booking_reference),+ trip.bookingReference.ifBlank { "—" },+ emphasize = true+ )+ HorizontalDivider()+ ConfirmationDetailRow(stringResource(R.string.route_label), trip.route)+ ConfirmationDetailRow(stringResource(R.string.departs), TravelViewModel.prettyDate(trip.departDate))+ ConfirmationDetailRow(+ stringResource(if (isTripAwaitingPayment(trip.status)) R.string.amount_due else R.string.amount_paid),+ formatMoney(trip.amount, trip.currency)+ )+ ConfirmationDetailRow(stringResource(R.string.status_label), stringResource(tripStatusLabel(trip.status)))+ if (trip.status == TRIP_STATUS_FAILED && trip.failureMessage.isNotBlank()) {+ Text(+ trip.failureMessage,+ color = MaterialTheme.colorScheme.error,+ style = MaterialTheme.typography.bodySmall,+ )+ }+ }+ }++ 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)+ }+ if (isCheckoutUnexpired(trip.checkoutExpiresAt)) {+ val loading = checkout is CheckoutState.Loading+ Button(+ onClick = { actions.completePayment() },+ enabled = !loading && !paying,+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.complete_payment)) }+ } else {+ Text(+ stringResource(R.string.payment_link_expired),+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ style = MaterialTheme.typography.bodySmall,+ )+ }+ }++ if (isTripPollingStatus(trip.status) || trip.status == TRIP_STATUS_PARTIAL) {+ OutlinedButton(+ onClick = { actions.refreshStatus() },+ enabled = poll !is TripPollState.Polling,+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.refresh_status)) }+ }++ Button(onClick = { actions.done() }, modifier = Modifier.fillMaxWidth()) {+ Text(stringResource(UiR.string.done))+ }+ OutlinedButton(+ onClick = { actions.viewItinerary() },+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.view_full_itinerary)) }+ OutlinedButton(+ onClick = { actions.viewTrips() },+ modifier = Modifier.fillMaxWidth(),+ ) { Text(stringResource(R.string.view_my_trips)) }+ }+ }+}++private fun confirmationTitle(status: String): Int = when (status) {+ TRIP_STATUS_PENDING_PAYMENT -> R.string.status_payment_pending+ TRIP_STATUS_PROCESSING -> R.string.status_processing+ TRIP_STATUS_PARTIAL -> R.string.status_partial+ TRIP_STATUS_FAILED -> R.string.status_failed+ else -> R.string.booking_confirmed+}++private fun confirmationHeadline(status: String): Int = when (status) {+ TRIP_STATUS_PENDING_PAYMENT -> R.string.payment_pending_headline+ TRIP_STATUS_PROCESSING -> R.string.confirming_payment+ TRIP_STATUS_PARTIAL -> R.string.partial_headline+ TRIP_STATUS_FAILED -> R.string.booking_failed_headline+ else -> R.string.you_re_booked+}++@Composable+private fun ConfirmationDetailRow(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/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 34279c64c8..1b42105690 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/DateField.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/DateField.kt@@ -1,6 +1,5 @@ package com.vayunmathur.travel.ui -import com.vayunmathur.library.ui.R as UiR import kotlin.time.Clock import kotlin.time.Instant import kotlinx.datetime.LocalDate@@ -12,74 +11,54 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box 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 com.vayunmathur.library.ui.DatePicker-import com.vayunmathur.library.ui.DatePickerDialog-import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.IconCalendar import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton-import com.vayunmathur.library.ui.rememberDatePickerState-import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.ResultEffect+import com.vayunmathur.travel.Route /**- * A read-only field that opens a Material date picker on tap. [value] is an ISO- * `YYYY-MM-DD` string (empty when unset); [onDate] receives the picked ISO date.- * [minDate]/[maxDate] optionally clamp selection (e.g. no past dates, return not- * before depart); dates outside the range are disabled in the picker.+ * A read-only field that pushes the `DatePickerDialog` route on tap. [value]+ * is an ISO `YYYY-MM-DD` string (empty when unset); the picked date returns+ * through the nav result registry under [resultKey] and is reported to+ * [onDate] as an ISO string. [minDate]/[maxDate] optionally clamp selection+ * (e.g. no past dates, return not before depart); dates outside the range+ * are disabled in the picker. */-@OptIn(ExperimentalMaterial3Api::class) @Composable fun DateField( label: String, value: String, onDate: (String) -> Unit,+ backStack: NavBackStack<Route>,+ resultKey: String, modifier: Modifier = Modifier, dateFormat: (LocalDate) -> String = DateString::dateWeekdayNoYear, minDate: LocalDate? = null, maxDate: LocalDate? = null, ) {- var show by remember { mutableStateOf(false) }+ ResultEffect<LocalDate>(resultKey) { picked -> onDate(picked.toString()) } val display = if (value.isBlank()) "" else runCatching { dateFormat(LocalDate.parse(value)) }.getOrDefault(value) - DateFieldBox(label, display, onClick = { show = true }, modifier = modifier)-- if (show) {- val minMillis = minDate?.atStartOfDayIn(TimeZone.UTC)?.toEpochMilliseconds()- val maxMillis = maxDate?.atStartOfDayIn(TimeZone.UTC)?.toEpochMilliseconds()- val selectable = object : com.vayunmathur.library.ui.SelectableDates {- override fun isSelectableDate(utcTimeMillis: Long): Boolean =- (minMillis == null || utcTimeMillis >= minMillis) &&- (maxMillis == null || utcTimeMillis <= maxMillis)- }- val state = rememberDatePickerState(- initialSelectedDateMillis = runCatching { LocalDate.parse(value) }- .getOrNull()- ?.atStartOfDayIn(TimeZone.UTC)- ?.toEpochMilliseconds(),- selectableDates = selectable,- )- DatePickerDialog(- onDismissRequest = { show = false },- confirmButton = {- TextButton(onClick = {- state.selectedDateMillis?.let { ms ->- val date = Instant.fromEpochMilliseconds(ms).toLocalDateTime(TimeZone.UTC).date- onDate(date.toString())- }- show = false- }) { Text(stringResource(UiR.string.ok)) }- },- dismissButton = { TextButton(onClick = { show = false }) { Text(stringResource(UiR.string.cancel)) } },- ) { DatePicker(state) }- }+ DateFieldBox(+ label,+ display,+ onClick = {+ backStack.add(+ Route.DatePickerDialog(+ key = resultKey,+ initialDate = value,+ minDate = minDate?.toString(),+ maxDate = maxDate?.toString(),+ )+ )+ },+ modifier = modifier,+ ) } /**@@ -125,3 +104,4 @@ fun todayIn(zone: TimeZone, instant: Instant): LocalDate = instant.toLocalDateTi * in the evening west of UTC (and still yesterday in the morning east of it). */ fun todayLocal(): LocalDate = todayIn(TimeZone.currentSystemDefault(), Clock.System.now())+
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.ktindex 1b36bec273..77d683007c 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/DateRangeFields.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/DateRangeFields.kt@@ -1,30 +1,25 @@ package com.vayunmathur.travel.ui -import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.travel.R 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.DatePickerDialog import com.vayunmathur.library.ui.DateString-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.ResultEffect+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.ui.dialogs.DateRangeSelection import kotlinx.datetime.LocalDate /** * Two side-by-side date fields (e.g. Depart / Return, Check-in / Check-out)- * that open one range calendar ([RangeCalendar], styled like the single date- * picker) in the same dialog: 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).+ * that push the `DateRangeDialog` route: tap either to pick both dates at+ * once in its range calendar. 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). The picked range returns through+ * the nav result registry under [resultKey]. */ @Composable fun DateRangeFields(@@ -33,53 +28,33 @@ fun DateRangeFields( start: String, end: String, onRange: (start: String, end: String) -> Unit,+ backStack: NavBackStack<Route>,+ resultKey: String, modifier: Modifier = Modifier, minDate: LocalDate? = null, allowSameDay: Boolean = true, ) {- var show by remember { mutableStateOf(false) }+ ResultEffect<DateRangeSelection>(resultKey) { picked ->+ onRange(picked.start.toString(), picked.end.toString())+ } 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-- // Work on a draft so Cancel leaves the fields untouched.- var draftStart by remember { mutableStateOf(start.toJavaDate()) }- var draftEnd by remember { mutableStateOf(end.toJavaDate()) }- val complete = draftStart != null && draftEnd != null- DatePickerDialog(- onDismissRequest = { show = false },- confirmButton = {- TextButton(- onClick = {- val s = draftStart- val e = draftEnd- if (s != null && e != null) onRange(s.toString(), e.toString())- show = false- },- enabled = complete,- ) { Text(stringResource(UiR.string.ok)) }- },- dismissButton = { TextButton(onClick = { show = false }) { Text(stringResource(UiR.string.cancel)) } },- ) {- RangeCalendar(- title = stringResource(R.string.select_dates),- startLabel = startLabel,- endLabel = endLabel,- start = draftStart,- end = draftEnd,- onChange = { s, e ->- draftStart = s- draftEnd = e- },- minDate = minDate?.let { java.time.LocalDate.parse(it.toString()) } ?: java.time.LocalDate.now(),- allowSameDay = allowSameDay,+ val openPicker = {+ backStack.add(+ Route.DateRangeDialog(+ key = resultKey,+ startLabel = startLabel,+ endLabel = endLabel,+ start = start,+ end = end,+ minDate = minDate?.toString(),+ allowSameDay = allowSameDay,+ ) ) }+ Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ DateFieldBox(startLabel, display(start), onClick = openPicker, modifier = Modifier.weight(1f))+ DateFieldBox(endLabel, display(end), onClick = openPicker, modifier = Modifier.weight(1f))+ } }--private fun String.toJavaDate(): java.time.LocalDate? = runCatching { java.time.LocalDate.parse(this) }.getOrNull()
travel/src/main/java/com/vayunmathur/travel/ui/FareSelectPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/FareSelectPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/FareSelectPage.ktindex 16e5b1cb26..941d2194f6 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/FareSelectPage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FareSelectPage.kt@@ -52,18 +52,15 @@ fun FareSelectPage( viewModel.loadPartialFares(route.outboundSignature, route.inboundSignature) } val state by viewModel.partialFlow.collectAsStateWithLifecycle()- PartialScaffold(- title = stringResource(R.string.choose_fare),- subtitle = stringResource(R.string.step_2_of_2),- backStack = backStack,- state = state,- isEmpty = state.offers.isEmpty(),- ) {- items(state.offers) { offer ->- FareCard(offer) {+ val actions = remember(viewModel, backStack) {+ object : com.vayunmathur.travel.platform.FareSelectActions {+ override fun selectFare(offer: OfferDto) { viewModel.selectOffer(offer) backStack.add(Route.OfferReview(offer.offerId)) }++ override fun back() = backStack.pop() } }+ FareSelectScreen(state = state, actions = actions) }
travel/src/main/java/com/vayunmathur/travel/ui/FareSelectScreen.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/FareSelectScreen.kt b/travel/src/main/java/com/vayunmathur/travel/ui/FareSelectScreen.ktnew file mode 100644index 0000000000..94676b9f62--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FareSelectScreen.kt@@ -0,0 +1,29 @@+package com.vayunmathur.travel.ui++import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.travel.R+import com.vayunmathur.travel.platform.FareSelectActions+import com.vayunmathur.travel.platform.PartialFlowState++/**+ * Stateless round-trip step 2: pick the fare for the chosen outbound ++ * return, then review. Rendered from literals by previews.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun FareSelectScreen(state: PartialFlowState, actions: FareSelectActions) {+ PartialScaffold(+ title = stringResource(R.string.choose_fare),+ subtitle = stringResource(R.string.step_2_of_2),+ onBack = { actions.back() },+ state = state,+ isEmpty = state.offers.isEmpty(),+ ) {+ items(state.offers) { offer ->+ FareCard(offer) { actions.selectFare(offer) }+ }+ }+}
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 a66f81c7b4..7373d6471f 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt@@ -19,8 +19,10 @@ import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconSwapLanguages import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.network.PlaceDto import com.vayunmathur.travel.platform.FlightQuery-import com.vayunmathur.travel.platform.TravelViewModel import androidx.compose.ui.res.stringResource import androidx.annotation.StringRes import com.vayunmathur.travel.R@@ -61,7 +63,8 @@ enum class MaxStops(val apiValue: Int, @StringRes val label: Int) { */ @Composable fun FlightSearchForm(- viewModel: TravelViewModel,+ backStack: NavBackStack<Route>,+ autocomplete: suspend (String) -> List<PlaceDto>, state: FlightFormState, onState: (FlightFormState) -> Unit, modifier: Modifier = Modifier,@@ -87,7 +90,7 @@ fun FlightSearchForm( selectedValue = state.tripType.name, onSelect = { name -> onState(state.copy(tripType = TripType.valueOf(name))) }, )- PassengerField(mix = state.mix, onMix = { onState(state.copy(mix = it)) })+ PassengerField(mix = state.mix, onMix = { onState(state.copy(mix = it)) }, backStack = backStack, resultKey = "travel-flight-passengers") SearchDropdown( display = stringResource(state.cabin.label), options = Cabin.entries.map { it.name to stringResource(it.label) },@@ -110,7 +113,7 @@ fun FlightSearchForm( androidx.compose.runtime.key(swapNonce) { PlaceAutocompleteField( "From",- viewModel,+ autocomplete, onChange = { code, text -> onState(state.copy(origin = code, originText = text)) }, modifier = Modifier.weight(1f), initialText = state.originText.ifBlank { state.origin },@@ -123,7 +126,7 @@ fun FlightSearchForm( androidx.compose.runtime.key(swapNonce) { PlaceAutocompleteField( "To",- viewModel,+ autocomplete, onChange = { code, text -> onState(state.copy(destination = code, destinationText = text)) }, modifier = Modifier.weight(1f), initialText = state.destinationText.ifBlank { state.destination },@@ -138,6 +141,8 @@ fun FlightSearchForm( start = state.depart, end = state.returnDate, onRange = { start, end -> onState(state.copy(depart = start, returnDate = end)) },+ backStack = backStack,+ resultKey = "travel-flight-range", minDate = today, ) } else {@@ -145,6 +150,8 @@ fun FlightSearchForm( stringResource(R.string.depart), state.depart, onDate = { onState(state.copy(depart = it)) },+ backStack = backStack,+ resultKey = "travel-flight-depart", modifier = Modifier.fillMaxWidth(), minDate = today, )
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 ee081f8bbb..3c8623a669 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/HomePage.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/HomePage.kt@@ -1,50 +1,24 @@ package com.vayunmathur.travel.ui -import androidx.compose.ui.res.pluralStringResource-import androidx.compose.foundation.clickable-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.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.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-import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle-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.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.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 import com.vayunmathur.travel.data.RecentSearch+import com.vayunmathur.travel.platform.FlightQuery+import com.vayunmathur.travel.platform.HomeActions import com.vayunmathur.travel.platform.TravelViewModel+import com.vayunmathur.travel.platform.autocomplete import com.vayunmathur.travel.platform.clearRecents-import androidx.compose.ui.res.stringResource-import com.vayunmathur.travel.R+import com.vayunmathur.travel.platform.staySuggestions -@OptIn(ExperimentalMaterial3Api::class)+/** Binds [TravelViewModel], the saved form states and the back stack to [HomeScreen]. */ @Composable fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel, homeRoute: Route) { val recents by viewModel.recentSearches.collectAsStateWithLifecycle()@@ -55,176 +29,112 @@ fun HomePage(backStack: NavBackStack<Route>, viewModel: TravelViewModel, homeRou var flightForm by rememberSaveable(stateSaver = FlightFormSaver) { mutableStateOf(FlightFormState()) } var stayForm by rememberSaveable(stateSaver = StayFormSaver) { mutableStateOf(StayFormState()) } - AppScaffold(- title = stringResource(R.string.app_name),- actions = {- if (trips.isNotEmpty()) {- TextButton(onClick = { backStack.add(Route.Trips) }) { Text(stringResource(R.string.my_trips)) }+ val actions = remember(viewModel, backStack) {+ object : HomeActions {+ override fun onFlightState(state: FlightFormState) {+ flightForm = state }- IconButton(onClick = { backStack.add(Route.Settings) }) {- IconSettings()- }- },- bottomBar = {- BottomNavBar {- BottomNavBarItem(- selected = !isStays,- onClick = { backStack.reset(Route.FlightsHome) },- icon = { IconFlight() },- label = stringResource(R.string.flights),- )- BottomNavBarItem(- selected = isStays,- onClick = { backStack.reset(Route.StaysHome) },- icon = { IconHotel() },- label = stringResource(R.string.stays),- )++ override fun onStayState(state: StayFormState) {+ stayForm = state }- },- ) { padding ->- Column(- Modifier- .fillMaxSize()- .padding(padding)- .verticalScroll(rememberScrollState()),- ) { - if (!isStays) {- FlightSearchForm(- viewModel,- state = flightForm,- onState = { flightForm = it },- onSearch = { query ->- if (query.isRoundTrip) {- backStack.add(- Route.OutboundSelect(- slices = query.slices,- adults = query.adults,- children = query.children,- infants = query.infants,- cabin = query.cabin,- maxConnections = query.maxConnections,- )- )- } else {- backStack.add(- Route.FlightResults(- slices = query.slices,- adults = query.adults,- children = query.children,- infants = query.infants,- cabin = query.cabin,- maxConnections = query.maxConnections,- )- )- }- },- )- } else {- StaySearchForm(viewModel, stayForm, { stayForm = it }) { place, checkIn, checkOut, rooms, adults, lat, lng ->+ override fun searchFlights(query: FlightQuery) {+ if (query.isRoundTrip) { backStack.add(- Route.StayResults(- place = place,- checkIn = checkIn,- checkOut = checkOut,- rooms = rooms,- adults = adults,- latitude = lat ?: Double.NaN,- longitude = lng ?: Double.NaN,+ Route.OutboundSelect(+ slices = query.slices,+ adults = query.adults,+ children = query.children,+ infants = query.infants,+ cabin = query.cabin,+ maxConnections = query.maxConnections,+ )+ )+ } else {+ backStack.add(+ Route.FlightResults(+ slices = query.slices,+ adults = query.adults,+ children = query.children,+ infants = query.infants,+ cabin = query.cabin,+ maxConnections = query.maxConnections, ) ) } } - if (recents.isNotEmpty()) {- Row(- Modifier.fillMaxWidth().padding(end = 8.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween,- ) {- SectionHeader(stringResource(R.string.recent_searches))- TextButton(onClick = { viewModel.clearRecents() }) { Text(stringResource(UiR.string.clear)) }- }- recents.forEach { recent ->- RecentSearchCard(recent) { openRecent(backStack, recent) }- }+ override fun searchStays(+ place: String,+ checkIn: String,+ checkOut: String,+ rooms: Int,+ adults: Int,+ latitude: Double?,+ longitude: Double?,+ ) {+ backStack.add(+ Route.StayResults(+ place = place,+ chec
Diff truncated.