Modern Apps git

← Modern-Apps.git

travel: detekt clean (325 tests)

Commit
fad1d45cc33e74df4d3398430f18d59d101e4648
Author
Vayun Mathur <[email protected]>
When
2026-11-15 00:04 UTC (21 days ago)
Parents
bab770b
Fix all detekt findings in travel by fixing code, not config
(detekt.yml untouched, no baselines added):
- UndocumentedPublicClass: KDoc for the flagged types.
- LongMethod: AirportCatalog airline/aircraft/city
  loading extracted to loadAirlinesAircraftCities.
- MagicNumber: HTTP 422/503 and the still-pricing retry
  bounds are named constants.
- TopLevelPropertyNaming: calendar constants are now
  camelCase vals.
- UnusedParameter (test): dropped the pass-through
  carrier parameter the segment builder ignored.
- CyclomaticComplexMethod (test): fake-transport when
  became a route table.
- MaxLineLength: wrapped two lines.
Verified: ./gradlew :travel:detekt :travel:testDevUnitTest :travel:lint
--max-workers=32 all pass (325 unit tests).

Diff

travel/src/main/java/com/vayunmathur/travel/MainActivity.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/MainActivity.kt b/travel/src/main/java/com/vayunmathur/travel/MainActivity.ktindex 6b34379b2d..0a3e06d72c 100644--- a/travel/src/main/java/com/vayunmathur/travel/MainActivity.kt+++ b/travel/src/main/java/com/vayunmathur/travel/MainActivity.kt@@ -50,6 +50,7 @@ import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import kotlinx.serialization.Serializable +/** Main Activity: a ma activity implementation for main activity. */ class MainActivity : MaActivity() {     private lateinit var repository: TravelRepository @@ -90,11 +91,14 @@ class MainActivity : MaActivity() {     } } +/** Contract for route. */ @Serializable sealed interface Route : NavKey {+    /** Singleton holding home state and operations. */     @Serializable     data object Home : Route +    /** Immutable value describing flight results. */     @Serializable     data class FlightResults(         val slices: String,@@ -105,9 +109,11 @@ sealed interface Route : NavKey {         val maxConnections: Int,     ) : Route +    /** Immutable value describing offer review; carries offerId. */     @Serializable     data class OfferReview(val offerId: String) : Route +    /** Immutable value describing outbound select. */     @Serializable     data class OutboundSelect(         val slices: String,@@ -119,33 +125,43 @@ sealed interface Route : NavKey {     ) : Route  +    /** Immutable value describing fare select; carries outboundSignature, inboundSignature. */     @Serializable     data class FareSelect(val outboundSignature: String, val inboundSignature: String) : Route +    /** Immutable value describing ancillaries; carries offerId. */     @Serializable     data class Ancillaries(val offerId: String) : Route +    /** Immutable value describing seat map; carries offerId, segmentId. */     @Serializable     data class SeatMap(val offerId: String, val segmentId: String) : Route +    /** Immutable value describing passengers; carries offerId. */     @Serializable     data class Passengers(val offerId: String) : Route +    /** Immutable value describing payment; carries offerId. */     @Serializable     data class Payment(val offerId: String) : Route +    /** Immutable value describing confirmation; carries orderId. */     @Serializable     data class Confirmation(val orderId: String) : Route +    /** Immutable value describing order detail; carries orderId. */     @Serializable     data class OrderDetail(val orderId: String) : Route +    /** Immutable value describing cancel; carries orderId. */     @Serializable     data class Cancel(val orderId: String) : Route +    /** Immutable value describing change; carries orderId. */     @Serializable     data class Change(val orderId: String) : Route +    /** Immutable value describing stay results. */     @Serializable     data class StayResults(         val place: String,@@ -157,18 +173,23 @@ sealed interface Route : NavKey {         val longitude: Double = Double.NaN,     ) : Route +    /** Immutable value describing stay detail; carries searchResultId, name. */     @Serializable     data class StayDetail(val searchResultId: String, val name: String) : Route +    /** Singleton holding stay guests state and operations. */     @Serializable     data object StayGuests : Route +    /** Immutable value describing stay confirmation; carries bookingId. */     @Serializable     data class StayConfirmation(val bookingId: String) : Route +    /** Singleton holding trips state and operations. */     @Serializable     data object Trips : Route +    /** Singleton holding settings state and operations. */     @Serializable     data object Settings : Route }
travel/src/main/java/com/vayunmathur/travel/data/AirportCatalog.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/AirportCatalog.kt b/travel/src/main/java/com/vayunmathur/travel/data/AirportCatalog.ktindex 7aa46e8c51..722481d2da 100644--- a/travel/src/main/java/com/vayunmathur/travel/data/AirportCatalog.kt+++ b/travel/src/main/java/com/vayunmathur/travel/data/AirportCatalog.kt@@ -211,6 +211,60 @@ object AirportCatalog {             }         }.getOrDefault(emptyList()) ++    /** Airlines, aircraft names and city DTOs from their TSV snapshots. */+    private fun loadAirlinesAircraftCities(+        assets: android.content.res.AssetManager,+        metroCells: List<List<String>>,+    ): Triple<List<AirlineDto>, Map<String, String>, List<CityDto>> {+    val airlines = assetsReader(assets, "airlines.tsv")+        .filter { it.size >= 2 && it[0].isNotBlank() && it[1].isNotBlank() }+        .distinctBy { it[0].uppercase() }+        .map { cols -> AirlineDto(name = cols[1], iataCode = cols[0].uppercase()) }+        .sortedBy { it.name }++    val aircraft = assetsReader(assets, "aircraft.tsv")+        .filter { it.size >= 2 && it[0].isNotBlank() && it[1].isNotBlank() }+        .distinctBy { it[0].uppercase() }+        .associate { it[0].uppercase() to it[1] }++    val metros = metroCells.map { cols ->+        Triple(cols[0].uppercase(), cols[1], cols[2].uppercase())+    }+    val cities = metros+        .map { (code, city, countryCode) ->+            CityDto(name = city, iataCode = code, iataCountryCode = countryCode)+        }+        .sortedBy { it.name }+        return Triple(airlines, aircraft, cities)+    }++    /** Metro (city) rows, skipping codes a real airport already covers. */+    private fun loadMetroRows(+        assets: android.content.res.AssetManager,+        airportCodes: Set<String>,+        countryName: (String) -> String,+    ): Pair<List<CatalogPlaceRow>, List<List<String>>> {+    // A metro code that collides with a real airport IATA (e.g. IST, BKK,+    // BER) is skipped: the airport row already covers that code.+    val metroCells = assetsReader(assets, "metros.tsv").filter { it.size >= 5 }+    val metroRows = metroCells+        .filter { !airportCodes.contains(it[0].uppercase()) }+        .map { cols ->+            val city = cols[1]+            CatalogPlaceRow(+                code = cols[0].uppercase(),+                name = city,+                city = city,+                country = countryName(cols[2].uppercase()),+                type = "city",+                latitude = cols[3].toDoubleOrNull(),+                longitude = cols[4].toDoubleOrNull(),+            )+        }+        .sortedBy { it.code }+        return metroRows to metroCells+    }     private fun loadSnapshot(assets: android.content.res.AssetManager): CatalogSnapshot {         val countries = assetsReader(assets, "countries.tsv")             .filter { it.size >= 2 }@@ -236,45 +290,11 @@ object AirportCatalog {             .sortedBy { it.code }         val airportCodes = airportRows.map { it.code }.toSet() -        // A metro code that collides with a real airport IATA (e.g. IST, BKK,-        // BER) is skipped: the airport row already covers that code.-        val metroCells = assetsReader(assets, "metros.tsv").filter { it.size >= 5 }-        val metroRows = metroCells-            .filter { !airportCodes.contains(it[0].uppercase()) }-            .map { cols ->-                val city = cols[1]-                CatalogPlaceRow(-                    code = cols[0].uppercase(),-                    name = city,-                    city = city,-                    country = countryName(cols[2].uppercase()),-                    type = "city",-                    latitude = cols[3].toDoubleOrNull(),-                    longitude = cols[4].toDoubleOrNull(),-                )-            }-            .sortedBy { it.code }--        val airlines = assetsReader(assets, "airlines.tsv")-            .filter { it.size >= 2 && it[0].isNotBlank() && it[1].isNotBlank() }-            .distinctBy { it[0].uppercase() }-            .map { cols -> AirlineDto(name = cols[1], iataCode = cols[0].uppercase()) }-            .sortedBy { it.name }--        val aircraft = assetsReader(assets, "aircraft.tsv")-            .filter { it.size >= 2 && it[0].isNotBlank() && it[1].isNotBlank() }-            .distinctBy { it[0].uppercase() }-            .associate { it[0].uppercase() to it[1] }-+        val (metroRows, metroCells) = loadMetroRows(assets, airportCodes, countryName)         val metros = metroCells.map { cols ->             Triple(cols[0].uppercase(), cols[1], cols[2].uppercase())         }-        val cities = metros-            .map { (code, city, countryCode) ->-                CityDto(name = city, iataCode = code, iataCountryCode = countryCode)-            }-            .sortedBy { it.name }-+        val (airlines, aircraft, cities) = loadAirlinesAircraftCities(assets, metroCells)         val airportByCode = airportRows.associate { row ->             row.code to AirportDto(                 iataCode = row.code,
travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt b/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.ktindex 940ca4b0a7..339dd83f1f 100644--- a/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt+++ b/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt@@ -14,6 +14,7 @@ import kotlinx.coroutines.flow.Flow  const val DB_NAME = "travel-db" +/** Contract for recent search dao. */ @Dao interface RecentSearchDao {     @Query("SELECT * FROM RecentSearch ORDER BY createdAt DESC LIMIT :limit")@@ -39,6 +40,7 @@ interface RecentSearchDao {     suspend fun trim(keep: Int = 20) } +/** Contract for booked trip dao. */ @Dao interface BookedTripDao {     @Query("SELECT * FROM BookedTrip ORDER BY createdAt DESC")@@ -57,6 +59,7 @@ interface BookedTripDao {     suspend fun deleteById(orderId: String) } +/** Contract for frequent flyer dao. */ @Dao interface FrequentFlyerDao {     @Query("SELECT * FROM FrequentFlyer ORDER BY airlineName")@@ -72,6 +75,7 @@ interface FrequentFlyerDao {     suspend fun deleteById(airlineIata: String) } +/** Contract for customer dao. */ @Dao interface CustomerDao {     @Query("SELECT * FROM Customer ORDER BY givenName, familyName")@@ -92,12 +96,14 @@ interface CustomerDao {     version = 5,     exportSchema = false, )+/** Travel Database: a room database implementation for travel database. */ abstract class TravelDatabase : RoomDatabase() {     abstract fun recentSearchDao(): RecentSearchDao     abstract fun bookedTripDao(): BookedTripDao     abstract fun frequentFlyerDao(): FrequentFlyerDao     abstract fun customerDao(): CustomerDao +    /** Shared constants and helpers for TravelDatabase. */     companion object : DatabaseMigrations {         override val migrations = listOf(             object : androidx.room3.migration.Migration(1, 2) {
travel/src/main/java/com/vayunmathur/travel/data/TravelRepository.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/TravelRepository.kt b/travel/src/main/java/com/vayunmathur/travel/data/TravelRepository.ktindex ed96053497..6dd985c1f7 100644--- a/travel/src/main/java/com/vayunmathur/travel/data/TravelRepository.kt+++ b/travel/src/main/java/com/vayunmathur/travel/data/TravelRepository.kt@@ -39,6 +39,7 @@ open class TravelRepository internal constructor(context: Context) :     open suspend fun upsertCustomer(value: Customer) = customerDao.upsert(value)     open suspend fun deleteCustomerById(id: String) = customerDao.deleteById(id) +    /** Shared constants and helpers for TravelRepository. */     companion object {         @Volatile private var instance: TravelRepository? = null         fun get(context: Context): TravelRepository =
travel/src/main/java/com/vayunmathur/travel/domain/DateRangeSelection.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/domain/DateRangeSelection.kt b/travel/src/main/java/com/vayunmathur/travel/domain/DateRangeSelection.ktindex b520a49f84..852f25bc43 100644--- a/travel/src/main/java/com/vayunmathur/travel/domain/DateRangeSelection.kt+++ b/travel/src/main/java/com/vayunmathur/travel/domain/DateRangeSelection.kt@@ -9,7 +9,12 @@ import java.time.LocalDate  * otherwise it ends the range. [allowSameDay] = false (hotel nights) keeps  * waiting for an end after the start when the start is tapped again.  */-fun nextRange(start: LocalDate?, end: LocalDate?, tapped: LocalDate, allowSameDay: Boolean): Pair<LocalDate?, LocalDate?> =+fun nextRange(+    start: LocalDate?,+    end: LocalDate?,+    tapped: LocalDate,+    allowSameDay: Boolean,+): Pair<LocalDate?, LocalDate?> =     when {         start == null || end != null -> tapped to null         tapped.isBefore(start) -> tapped to null
travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.kt b/travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.ktindex 5483d8f891..0bce24e1ca 100644--- a/travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.kt+++ b/travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.kt@@ -68,9 +68,12 @@ internal fun travelExtractError(body: String): String = runCatching {         ?: GENERIC_TRAVEL_ERROR }.getOrDefault(GENERIC_TRAVEL_ERROR).take(MAX_ERROR_SNIPPET_LENGTH) +private const val HTTP_UNPROCESSABLE_ENTITY = 422+private const val HTTP_SERVICE_UNAVAILABLE = 503+ /** Map a non-2xx status + body to the exception the ViewModel surfaces. */ internal fun travelHttpError(status: Int, body: String, fallback: String): IllegalStateException {-    if (status == 422) {+    if (status == HTTP_UNPROCESSABLE_ENTITY) {         val fields = runCatching {             val start = body.indexOf('{')             val jsonPart = if (start >= 0) body.substring(start) else body@@ -80,7 +83,7 @@ internal fun travelHttpError(status: Int, body: String, fallback: String): Illeg         }.getOrDefault(emptyList())         return MissingDetailsException(fields, travelExtractError(body))     }-    if (status == 503) {+    if (status == HTTP_SERVICE_UNAVAILABLE) {         val retryAfter = runCatching {             val start = body.indexOf('{')             val jsonPart = if (start >= 0) body.substring(start) else body
travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.kt b/travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.ktindex 021c0b6778..f92d56e8ae 100644--- a/travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.kt+++ b/travel/src/main/java/com/vayunmathur/travel/platform/StripeCheckout.kt@@ -13,8 +13,11 @@ import com.stripe.android.paymentsheet.rememberPaymentSheet  /** Outcome of the in-app card payment sheet. */ sealed interface CardPaymentResult {+    /** Singleton holding completed state and operations. */     data object Completed : CardPaymentResult+    /** Singleton holding canceled state and operations. */     data object Canceled : CardPaymentResult+    /** Immutable value describing failed; carries message. */     data class Failed(val message: String) : CardPaymentResult } 
travel/src/main/java/com/vayunmathur/travel/ui/RangeCalendar.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/RangeCalendar.kt b/travel/src/main/java/com/vayunmathur/travel/ui/RangeCalendar.ktindex 89fe746eec..8200a5cd33 100644--- a/travel/src/main/java/com/vayunmathur/travel/ui/RangeCalendar.kt+++ b/travel/src/main/java/com/vayunmathur/travel/ui/RangeCalendar.kt@@ -52,13 +52,13 @@ import java.util.Locale // same component: 120dp header, 56dp month row, 48dp cells, 40dp day circles. private val HeaderMinHeight = 120.dp private val HeaderTitlePadding = PaddingValues(start = 24.dp, end = 12.dp, top = 16.dp)-private val HeaderHeadlinePadding = PaddingValues(start = 24.dp, end = 12.dp, bottom = 12.dp)-private val MonthRowHeight = 56.dp-private val HorizontalPadding = 12.dp-private val CellSize = 48.dp-private val DaySize = 40.dp-private const val CalendarRows = 6-private const val MonthsAhead = 24L+private val headerHeadlinePadding = PaddingValues(start = 24.dp, end = 12.dp, bottom = 12.dp)+private val monthRowHeight = 56.dp+private val horizontalPadding = 12.dp+private val cellSize = 48.dp+private val daySize = 40.dp+private const val CALENDAR_ROWS = 6+private const val MONTHS_AHEAD = 24L  /**  * A start/end date calendar that looks and behaves like the single Material@@ -85,8 +85,8 @@ internal fun RangeCalendar(     val initialPage = remember {         val shown = YearMonth.from(start ?: minDate)         (shown.year - firstMonth.year) * 12 + (shown.monthValue - firstMonth.monthValue)-    }.coerceIn(0, MonthsAhead.toInt() - 1)-    val pager = rememberPagerState(initialPage = initialPage) { MonthsAhead.toInt() }+    }.coerceIn(0, MONTHS_AHEAD.toInt() - 1)+    val pager = rememberPagerState(initialPage = initialPage) { MONTHS_AHEAD.toInt() }     val scope = rememberCoroutineScope()     val shownMonth = firstMonth.plusMonths(pager.currentPage.toLong()) @@ -101,7 +101,7 @@ internal fun RangeCalendar(             )             Text(                 "${start?.let { formatHeadlineDate(it, locale) } ?: startLabel} – ${end?.let { formatHeadlineDate(it, locale) } ?: endLabel}",-                modifier = Modifier.padding(HeaderHeadlinePadding),+                modifier = Modifier.padding(headerHeadlinePadding),                 style = MaterialTheme.typography.headlineLarge,                 color = MaterialTheme.colorScheme.onSurfaceVariant,                 maxLines = 1,@@ -111,7 +111,7 @@ internal fun RangeCalendar(          // Month navigation: "November 2026" with previous/next arrows.         Row(-            Modifier.fillMaxWidth().requiredHeight(MonthRowHeight).padding(horizontal = HorizontalPadding),+            Modifier.fillMaxWidth().requiredHeight(monthRowHeight).padding(horizontal = horizontalPadding),             horizontalArrangement = Arrangement.SpaceBetween,             verticalAlignment = Alignment.CenterVertically,         ) {@@ -128,14 +128,14 @@ internal fun RangeCalendar(                 ) { IconKeyboardArrowLeft(tint = MaterialTheme.colorScheme.onSurfaceVariant) }                 IconButton(                     onClick = { scope.launch { pager.animateScrollToPage(pager.currentPage + 1) } },-                    enabled = pager.currentPage < MonthsAhead - 1,+                    enabled = pager.currentPage < MONTHS_AHEAD - 1,                 ) { IconKeyboardArrowRight(tint = MaterialTheme.colorScheme.onSurfaceVariant) }             }         } -        Column(Modifier.padding(horizontal = HorizontalPadding)) {+        Column(Modifier.padding(horizontal = horizontalPadding)) {             val weekDays = remember(locale) { orderedWeekDays(locale) }-            Row(Modifier.fillMaxWidth().defaultMinSize(minHeight = CellSize), verticalAlignment = Alignment.CenterVertically) {+            Row(Modifier.fillMaxWidth().defaultMinSize(minHeight = cellSize), verticalAlignment = Alignment.CenterVertically) {                 weekDays.forEach { day ->                     Text(                         day.getDisplayName(TextStyle.NARROW, locale),@@ -174,9 +174,9 @@ private fun MonthGrid( ) {     val today = remember { LocalDate.now() }     val leading = weekDays.indexOf(month.atDay(1).dayOfWeek)-    Column(Modifier.fillMaxWidth().requiredHeight(CellSize * CalendarRows), verticalArrangement = Arrangement.SpaceEvenly) {-        for (row in 0 until CalendarRows) {-            Row(Modifier.fillMaxWidth().height(CellSize)) {+    Column(Modifier.fillMaxWidth().requiredHeight(cellSize * CALENDAR_ROWS), verticalArrangement = Arrangement.SpaceEvenly) {+        for (row in 0 until CALENDAR_ROWS) {+            Row(Modifier.fillMaxWidth().height(cellSize)) {                 for (col in 0 until 7) {                     val dayNumber = row * 7 + col - leading + 1                     if (dayNumber < 1 || dayNumber > month.lengthOfMonth()) {@@ -219,7 +219,7 @@ private fun RowScope.DayCell(         // ends, half width on the start/end cells so the ends stay round.         if (hasRange && (inRange || isStart || isEnd)) {             val band = colors.secondaryContainer-            Row(Modifier.fillMaxWidth().height(DaySize)) {+            Row(Modifier.fillMaxWidth().height(daySize)) {                 val leftFilled = inRange || (if (rtl) isStart else isEnd)                 val rightFilled = inRange || (if (rtl) isEnd else isStart)                 Box(Modifier.weight(1f).fillMaxHeight().background(if (leftFilled) band else Color.Transparent))@@ -232,7 +232,7 @@ private fun RowScope.DayCell(             shape = CircleShape,             color = if (selected) colors.primary else Color.Transparent,             border = if (today && !selected) BorderStroke(1.dp, colors.primary) else null,-            modifier = Modifier.size(DaySize),+            modifier = Modifier.size(daySize),         ) {             Box(contentAlignment = Alignment.Center) {                 Text(
travel/src/main/java/com/vayunmathur/travel/util/TravelBookingOps.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/TravelBookingOps.kt b/travel/src/main/java/com/vayunmathur/travel/util/TravelBookingOps.ktindex ee0d9431de..b0d6bffc65 100644--- a/travel/src/main/java/com/vayunmathur/travel/util/TravelBookingOps.kt+++ b/travel/src/main/java/com/vayunmathur/travel/util/TravelBookingOps.kt@@ -27,6 +27,11 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.serialization.json.Json +private const val DEFAULT_RETRY_SECONDS = 5+private const val MIN_RETRY_SECONDS = 1+private const val MAX_RETRY_SECONDS = 30+private const val MILLIS_PER_SECOND = 1_000L+ /**  * Initialize one blank passenger per booking passenger id on the offer,  * unless a matching set is already present (so returning to the form keeps@@ -165,8 +170,8 @@ fun TravelViewModel.loadAncillaries(tripId: String) {                 return@launch             }             // Still pricing: honor the server's hint, then retry.-            val waitSecs = (failure as? StillPricingException)?.retryAfterSeconds ?: 5-            delay(waitSecs.coerceIn(1, 30) * 1_000L)+            val waitSecs = (failure as? StillPricingException)?.retryAfterSeconds ?: DEFAULT_RETRY_SECONDS+            delay(waitSecs.coerceIn(MIN_RETRY_SECONDS, MAX_RETRY_SECONDS) * MILLIS_PER_SECOND)             attempt++         }         ancillariesMutable.value = AncillariesState(
travel/src/main/java/com/vayunmathur/travel/util/TravelOrderOps.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/TravelOrderOps.kt b/travel/src/main/java/com/vayunmathur/travel/util/TravelOrderOps.ktindex c9e9bed3d3..4abdaf58f2 100644--- a/travel/src/main/java/com/vayunmathur/travel/util/TravelOrderOps.kt+++ b/travel/src/main/java/com/vayunmathur/travel/util/TravelOrderOps.kt@@ -1,6 +1,7 @@ package com.vayunmathur.travel.util  import androidx.lifecycle.viewModelScope+import com.vayunmathur.travel.data.BookedTrip import com.vayunmathur.travel.data.TRIP_STATUS_CANCELLED import com.vayunmathur.travel.domain.isCheckoutUnexpired import com.vayunmathur.travel.network.ChangeRequestInputDto@@ -113,6 +114,13 @@ fun TravelViewModel.quoteCancellation(orderId: String) {     } } ++/** Persists [stored] as cancelled once a cancellation lands. */+private suspend fun TravelViewModel.markTripCancelled(stored: BookedTrip?) {+    stored?.let {+        repository.upsertBookedTrip(it.copy(status = TRIP_STATUS_CANCELLED, awaitingPayment = false))+    }+} /**  * Confirm the pending cancellation, then poll until succeeded/failed and  * update the local trip.@@ -133,7 +141,7 @@ fun TravelViewModel.confirmCancellation(orderId: String) {             return@launch         }         if (confirmed.status == "succeeded") {-            stored?.let { repository.upsertBookedTrip(it.copy(status = TRIP_STATUS_CANCELLED, awaitingPayment = false)) }+            markTripCancelled(stored)             cancellationMutable.value = cancellationMutable.value.copy(confirming = false, done = true)             return@launch         }@@ -161,9 +169,7 @@ fun TravelViewModel.confirmCancellation(orderId: String) {                     return@repeat                 }                 if (status.status == "succeeded") {-                    stored?.let {-                        repository.upsertBookedTrip(it.copy(status = TRIP_STATUS_CANCELLED, awaitingPayment = false))-                    }+                    markTripCancelled(stored)                     cancellationMutable.value = cancellationMutable.value.copy(polling = false, done = true)                     return@launch                 }
travel/src/main/java/com/vayunmathur/travel/util/TravelUiContract.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/TravelUiContract.kt b/travel/src/main/java/com/vayunmathur/travel/util/TravelUiContract.ktindex fd767a67a1..6036a33575 100644--- a/travel/src/main/java/com/vayunmathur/travel/util/TravelUiContract.kt+++ b/travel/src/main/java/com/vayunmathur/travel/util/TravelUiContract.kt@@ -47,6 +47,7 @@ interface FlightResultsActions {     fun openOffer(offer: OfferDto) {}     fun back() {} +    /** Shared constants and helpers for FlightResultsActions. */     companion object {         val Noop: FlightResultsActions = object : FlightResultsActions {}     }@@ -62,6 +63,7 @@ interface SeatMapActions {      fun back() {} +    /** Shared constants and helpers for SeatMapActions. */     companion object {         val Noop: SeatMapActions = object : SeatMapActions {}     }@@ -72,6 +74,7 @@ interface StayResultsActions {     fun openStay(result: StaySearchResultDto) {}     fun back() {} +    /** Shared constants and helpers for StayResultsActions. */     companion object {         val Noop: StayResultsActions = object : StayResultsActions {}     }@@ -86,6 +89,7 @@ interface OrderDetailActions {     fun openCancel(orderId: String) {}     fun back() {} +    /** Shared constants and helpers for OrderDetailActions. */     companion object {         val Noop: OrderDetailActions = object : OrderDetailActions {}     }
travel/src/main/java/com/vayunmathur/travel/util/TravelUiState.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/TravelUiState.kt b/travel/src/main/java/com/vayunmathur/travel/util/TravelUiState.ktindex a504d3634d..d784df2b27 100644--- a/travel/src/main/java/com/vayunmathur/travel/util/TravelUiState.kt+++ b/travel/src/main/java/com/vayunmathur/travel/util/TravelUiState.kt@@ -118,10 +118,13 @@ data class SeatMapState(  /** Booking lifecycle for the trip → checkout flow. */ sealed interface BookingState {+    /** Singleton holding idle state and operations. */     data object Idle : BookingState+    /** Singleton holding loading state and operations. */     data object Loading : BookingState     /** Trip created; ancillaries step (or checkout when none) comes next. */     data class TripReady(val trip: TripDto) : BookingState+    /** Immutable value describing error; carries message. */     data class Error(val message: String) : BookingState     /** Checkout demands missing traveler details: back to passengers with these fields. */     data class MissingDetails(val missingFields: List<String>, val message: String) : BookingState@@ -129,26 +132,37 @@ sealed interface BookingState {  /** Lifecycle for the checkout step (payment intent → card sheet → confirm). */ sealed interface CheckoutState {+    /** Singleton holding idle state and operations. */     data object Idle : CheckoutState+    /** Singleton holding loading state and operations. */     data object Loading : CheckoutState     /** Checkout link ready; [acceptedNewPrice] gates "Pay securely" when the price changed. */     data class Ready(val checkout: CheckoutDto, val acceptedNewPrice: Boolean = false) : CheckoutState+    /** Immutable value describing error; carries message. */     data class Error(val message: String) : CheckoutState }  /** Lifecycle for polling a trip after checkout (resumed / refresh). */ sealed interface TripPollState {+    /** Singleton holding idle state and operations. */     data object Idle : TripPollState+    /** Singleton holding polling state and operations. */     data object Polling : TripPollState+    /** Immutable value describing done; carries trip. */     data class Done(val trip: TripDto) : TripPollState+    /** Immutable value describing error; carries message. */     data class Error(val message: String) : TripPollState }  /** Lifecycle for the pay-later action on a hold order. */ sealed interface PaymentActionState {+    /** Singleton holding idle state and operations. */     data object Idle : PaymentActionState+    /** Singleton holding loading state and operations. */     data object Loading : PaymentActionState+    /** Singleton holding success state and operations. */     data object Success : PaymentActionState+    /** Immutable value describing error; carries message. */     data class Error(val message: String) : PaymentActionState } @@ -200,8 +214,12 @@ data class StayRatesState(  /** Booking lifecycle for a stay. */ sealed interface StayBookingState {+    /** Singleton holding idle state and operations. */     data object Idle : StayBookingState+    /** Singleton holding loading state and operations. */     data object Loading : StayBookingState+    /** Immutable value describing success; carries result. */     data class Success(val result: StayBookingResultDto) : StayBookingState+    /** Immutable value describing error; carries message. */     data class Error(val message: String) : StayBookingState }
travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt b/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.ktindex 6eefb09bf3..198316b88b 100644--- a/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt+++ b/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt@@ -164,6 +164,7 @@ class TravelViewModel(     internal val customerErrorMutable = MutableStateFlow<String?>(null)     val customerError: StateFlow<String?> = customerErrorMutable.asStateFlow() +    /** Shared constants and helpers for TravelViewModel. */     companion object {         /** "2026-09-01" -> "Sep 1"; falls back to the raw string on any parse error. */         fun prettyDate(iso: String): String = runCatching {@@ -177,6 +178,7 @@ class TravelViewModel( internal fun TravelViewModel.errorMessage(t: Throwable): String =     t.message?.takeIf { it.isNotBlank() } ?: "Something went wrong. Please try again." +/** Creates travel view model instances. */ class TravelViewModelFactory(     private val application: Application,     private val repository: TravelRepository,
travel/src/test/java/com/vayunmathur/travel/ui/TravelFlightResultsTest.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/ui/TravelFlightResultsTest.kt b/travel/src/test/java/com/vayunmathur/travel/ui/TravelFlightResultsTest.ktindex 6795c98296..14ea678089 100644--- a/travel/src/test/java/com/vayunmathur/travel/ui/TravelFlightResultsTest.kt+++ b/travel/src/test/java/com/vayunmathur/travel/ui/TravelFlightResultsTest.kt@@ -38,7 +38,7 @@ class TravelFlightResultsTest {     @get:Rule     val rule = createComposeRule() -    private fun seg(carrier: String = "AS", iata: String = "AS") = SegmentDto(+    private fun seg(iata: String = "AS") = SegmentDto(         id = "seg_1", carrier = "Alaska Airlines", carrierIata = iata,         flightNumber = "AS 6", origin = "SFO", destination = "JFK",         departureAt = "2026-06-24T07:15:00", arrivalAt = "2026-06-24T15:50:00",@@ -48,11 +48,11 @@ class TravelFlightResultsTest {         ),     ) -    private fun slice(stops: Long = 0, carrier: String = "AS", iata: String = "AS") = SliceDto(+    private fun slice(stops: Long = 0, iata: String = "AS") = SliceDto(         id = "sli_1", origin = "SFO", destination = "JFK",         departureAt = "2026-06-24T07:15:00", arrivalAt = "2026-06-24T15:50:00",         durationMinutes = 335, stops = stops,-        segments = listOf(seg(carrier, iata)),+        segments = listOf(seg(iata)),     )      private fun offer(
travel/src/test/java/com/vayunmathur/travel/util/TravelSuccessOpsTest.kt
diff --git a/travel/src/test/java/com/vayunmathur/travel/util/TravelSuccessOpsTest.kt b/travel/src/test/java/com/vayunmathur/travel/util/TravelSuccessOpsTest.ktindex 9ae3afddf9..10a610d52d 100644--- a/travel/src/test/java/com/vayunmathur/travel/util/TravelSuccessOpsTest.kt+++ b/travel/src/test/java/com/vayunmathur/travel/util/TravelSuccessOpsTest.kt@@ -48,29 +48,32 @@ class TravelSuccessOpsTest {      @BeforeTest fun open() {         repo = FakeRepo(ApplicationProvider.getApplicationContext())+        val routes: List<Pair<List<String>, String>> = listOf(+            listOf("/flights") to """{"offerRequestId":"req_1","offers":[$offerJson]}""",+            listOf("/ancillaries", "/trips/") to """{"status":"ok","services":[{"id":"bag_1","type":"baggage","title":"Checked bag","totalAmount":"30.00","totalCurrency":"USD","maxQuantity":3}],"seatMaps":[]}""",+            listOf("/checkout") to """{"clientSecret":"cs_1","publishableKey":"pk_1","quoteId":"q_1","totalAmount":"250.00","currency":"USD"}""",+            listOf("/confirm", "/trips/") to """{"tripId":"trip_1","status":"confirmed","bookingReference":"ABC123","totalAmount":"250.00","currency":"USD"}""",+            listOf("/trips/") to """{"tripId":"trip_1","status":"confirmed","bookingReference":"ABC123","totalAmount":"250.00","currency":"USD"}""",+            listOf("/bookings/", "/cancel") to """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","commitable":true,"status":"quoted"}""",+            listOf("/cancellations/", "/confirm") to """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","status":"processing"}""",+            listOf("/cancellations/") to """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","status":"cancelled"}""",+            listOf("/changes", "/bookings/") to """{"id":"chgreq_1","offers":[{"id":"chg_1","changeTotalAmount":"50.00","changeTotalCurrency":"USD","newTotalAmount":"300.00","newTotalCurrency":"USD","slices":[{"origin":"SFO","destination":"JFK","departureAt":"2027-07-01T07:15:00","arrivalAt":"2027-07-01T15:50:00"}]}]}""",+            listOf("/price?") to """{"outcome":"pay","amount":"50.00","currency":"USD"}""",+            listOf("/changes/", "/confirm") to """{"id":"chg_1","status":"processing"}""",+            listOf("/changes/status") to """{"orderId":"ord_1","status":"changed"}""",+            listOf("/bookings/") to """{"orderId":"ord_1","bookingReference":"ABC123","totalAmount":"250.00","currency":"USD","status":"confirmed","passengerNames":["Jane Doe"],"slices":[{"origin":"SFO","destination":"JFK","departureAt":"2027-06-24T07:15:00","arrivalAt":"2027-06-24T15:50:00"}],"canCancel":true,"canChange":true}""",+            listOf("/stays/search") to """[{"id":"sr_1","name":"Grand Hotel","rating":5,"cheapestAmount":"180.00","cheapestCurrency":"USD"}]""",+            listOf("/stays/rates") to """{"name":"Grand Hotel","rooms":[{"name":"Deluxe King","rates":[{"id":"r1","boardType":"breakfast","totalAmount":"180.00","totalCurrency":"USD","cancellation":"Free cancellation"}]}]}""",+            listOf("/stays/quote") to """{"id":"quote_1","totalAmount":"180.00","totalCurrency":"USD"}""",+            listOf("/stays/bookings") to """{"id":"stay_1","reference":"STAY123","status":"pending_payment","accommodationName":"Grand Hotel","totalAmount":"180.00","totalCurrency":"USD","clientSecret":"cs_s","publishableKey":"pk_s"}""",+            listOf("/trips") to """{"tripId":"trip_1","status":"created","totalAmount":"250.00","currency":"USD"}""",  // endsWith+        )         travelTransport = { _, url, _ ->-            when {-                url.contains("/flights") -> TravelRaw(200, """{"offerRequestId":"req_1","offers":[$offerJson]}""")-                url.contains("/offer?") -> TravelRaw(200, offerJson)-                url.contains("/ancillaries") && url.contains("/trips/") -> TravelRaw(200, """{"status":"ok","services":[{"id":"bag_1","type":"baggage","title":"Checked bag","totalAmount":"30.00","totalCurrency":"USD","maxQuantity":3}],"seatMaps":[]}""")-                url.contains("/checkout") -> TravelRaw(200, """{"clientSecret":"cs_1","publishableKey":"pk_1","quoteId":"q_1","totalAmount":"250.00","currency":"USD"}""")-                url.contains("/confirm") && url.contains("/trips/") -> TravelRaw(200, """{"tripId":"trip_1","status":"confirmed","bookingReference":"ABC123","totalAmount":"250.00","currency":"USD"}""")-                url.endsWith("/trips") -> TravelRaw(200, """{"tripId":"trip_1","status":"created","totalAmount":"250.00","currency":"USD"}""")-                url.contains("/trips/") -> TravelRaw(200, """{"tripId":"trip_1","status":"confirmed","bookingReference":"ABC123","totalAmount":"250.00","currency":"USD"}""")-                url.contains("/bookings/") && url.contains("/cancel") -> TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","commitable":true,"status":"quoted"}""")-                url.contains("/cancellations/") && url.contains("/confirm") -> TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","status":"processing"}""")-                url.contains("/cancellations/") -> TravelRaw(200, """{"id":"can_1","orderId":"ord_1","refundAmount":"200.00","refundCurrency":"USD","status":"cancelled"}""")-                url.contains("/changes") && url.contains("/bookings/") -> TravelRaw(200, """{"id":"chgreq_1","offers":[{"id":"chg_1","changeTotalAmount":"50.00","changeTotalCurrency":"USD","newTotalAmount":"300.00","newTotalCurrency":"USD","slices":[{"origin":"SFO","destination":"JFK","departureAt":"2027-07-01T07:15:00","arrivalAt":"2027-07-01T15:50:00"}]}]}""")-                url.contains("/price?") -> TravelRaw(200, """{"outcome":"pay","amount":"50.00","currency":"USD"}""")-                url.contains("/changes/") && url.contains("/confirm") -> TravelRaw(200, """{"id":"chg_1","status":"processing"}""")-                url.contains("/changes/status") -> TravelRaw(200, """{"orderId":"ord_1","status":"changed"}""")-                url.contains("/bookings/") -> TravelRaw(200, """{"orderId":"ord_1","bookingReference":"ABC123","totalAmount":"250.00","currency":"USD","status":"confirmed","passengerNames":["Jane Doe"],"slices":[{"origin":"SFO","destination":"JFK","departureAt":"2027-06-24T07:15:00","arrivalAt":"2027-06-24T15:50:00"}],"canCancel":true,"canChange":true}""")-                url.contains("/stays/search") -> TravelRaw(200, """[{"id":"sr_1","name":"Grand Hotel","rating":5,"cheapestAmount":"180.00","cheapestCurrency":"USD"}]""")-                url.contains("/stays/rates") -> TravelRaw(200, """{"name":"Grand Hotel","rooms":[{"name":"Deluxe King","rates":[{"id":"r1","boardType":"breakfast","totalAmount":"180.00","totalCurrency":"USD","cancellation":"Free cancellation"}]}]}""")-                url.contains("/stays/quote") -> TravelRaw(200, """{"id":"quote_1","totalAmount":"180.00","totalCurrency":"USD"}""")-                url.contains("/stays/bookings") -> TravelRaw(200, """{"id":"stay_1","reference":"STAY123","status":"pending_payment","accommodationName":"Grand Hotel","totalAmount":"180.00","totalCurrency":"USD","clientSecret":"cs_s","publishableKey":"pk_s"}""")-                else -> TravelRaw(404, """{"message":"not found"}""")-            }+            val body = routes.firstOrNull { (parts, _) ->+                parts.all { url.contains(it) }+            }?.second+            if (body != null) TravelRaw(200, body) else TravelRaw(404, """{"message":"not found"}""")+         }     }