Modern Apps git

← Modern-Apps.git

travel: new app

Commit
12d740f914c87cf00d8b76eabd431d100245983a
Author
Vayun Mathur <[email protected]>
When
2026-07-20 20:33 UTC (4 months ago)
Parents
e4d8bed

Diff

settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 5a3f3ed205..c33f7abb5d 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -68,3 +68,4 @@ include(":office") include(":tools:holidaygen") include(":education") include(":everysync")+include(":travel")
travel/build.gradle.kts
diff --git a/travel/build.gradle.kts b/travel/build.gradle.ktsnew file mode 100644index 0000000000..4980089a6a--- /dev/null+++ b/travel/build.gradle.kts@@ -0,0 +1,25 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-metadata")+    alias(libs.plugins.ksp)+}++launcherIcon {+    symbol = "travel"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.travel"+    }+}++dependencies {+    implementRoom(libs)+    implementation(project(":library:room"))+    implementation(project(":library:network"))++    implementation("androidx.compose.material:material-icons-extended")++    testImplementation(libs.junit)+}
travel/src/main/AndroidManifest.xml
diff --git a/travel/src/main/AndroidManifest.xml b/travel/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..c52ad71392--- /dev/null+++ b/travel/src/main/AndroidManifest.xml@@ -0,0 +1,26 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="android.permission.INTERNET" />++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:name=".MainActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>+    </application>++</manifest>
travel/src/main/java/com/vayunmathur/travel/data/Favorite.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/Favorite.kt b/travel/src/main/java/com/vayunmathur/travel/data/Favorite.ktnew file mode 100644index 0000000000..a00a34da30--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/data/Favorite.kt@@ -0,0 +1,20 @@+package com.vayunmathur.travel.data++import androidx.room.Entity+import androidx.room.PrimaryKey++/**+ * An offer the user has saved. Keyed by [bookingUrl] because that uniquely+ * identifies a specific offer across all verticals and makes toggling a+ * favorite a simple upsert/delete-by-key.+ */+@Entity+data class Favorite(+    @PrimaryKey val bookingUrl: String,+    val vertical: String,+    val title: String,+    val subtitle: String = "",+    val price: Double = 0.0,+    val currency: String = "usd",+    val createdAt: Long = System.currentTimeMillis(),+)
travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.kt b/travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.ktnew file mode 100644index 0000000000..c1af8fc88a--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/data/RecentSearch.kt@@ -0,0 +1,30 @@+package com.vayunmathur.travel.data++import androidx.room.Entity+import androidx.room.PrimaryKey++/** The three built vertical searches persisted as recent history. */+enum class Vertical { FLIGHTS, HOTELS, CARS }++/**+ * A search the user has run, kept so the Home screen can offer one-tap+ * re-runs. All fields needed to rebuild the query are stored as columns+ * ([origin]…[dropoff]); [label] is a pre-rendered human summary for the chip.+ */+@Entity+data class RecentSearch(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val vertical: String,+    val label: String,+    val origin: String? = null,+    val destination: String? = null,+    val depart: String? = null,+    val returnDate: String? = null,+    val location: String? = null,+    val checkin: String? = null,+    val checkout: String? = null,+    val pickup: String? = null,+    val dropoff: String? = null,+    val adults: Int = 1,+    val createdAt: Long = System.currentTimeMillis(),+)
travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt b/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.ktnew file mode 100644index 0000000000..2b290c1523--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/data/TravelDatabase.kt@@ -0,0 +1,64 @@+package com.vayunmathur.travel.data++import androidx.room.Dao+import androidx.room.Database+import androidx.room.Delete+import androidx.room.Insert+import androidx.room.Query+import androidx.room.RoomDatabase+import androidx.room.Upsert+import com.vayunmathur.library.util.DatabaseMigrations+import kotlinx.coroutines.flow.Flow++const val DB_NAME = "travel-db"++@Dao+interface RecentSearchDao {+    @Query("SELECT * FROM RecentSearch ORDER BY createdAt DESC LIMIT :limit")+    fun observeRecent(limit: Int = 10): Flow<List<RecentSearch>>++    @Insert+    suspend fun insert(value: RecentSearch)++    @Delete+    suspend fun delete(value: RecentSearch)++    @Query("DELETE FROM RecentSearch")+    suspend fun clear()++    /**+     * Drop rows beyond the newest [keep], so history doesn't grow unbounded.+     * Called after each insert.+     */+    @Query(+        "DELETE FROM RecentSearch WHERE id NOT IN " ++            "(SELECT id FROM RecentSearch ORDER BY createdAt DESC LIMIT :keep)"+    )+    suspend fun trim(keep: Int = 20)+}++@Dao+interface FavoriteDao {+    @Query("SELECT * FROM Favorite ORDER BY createdAt DESC")+    fun observeAll(): Flow<List<Favorite>>++    @Upsert+    suspend fun upsert(value: Favorite)++    @Query("DELETE FROM Favorite WHERE bookingUrl = :bookingUrl")+    suspend fun deleteByUrl(bookingUrl: String)+}++@Database(+    entities = [RecentSearch::class, Favorite::class],+    version = 1,+    exportSchema = false,+)+abstract class TravelDatabase : RoomDatabase() {+    abstract fun recentSearchDao(): RecentSearchDao+    abstract fun favoriteDao(): FavoriteDao++    companion object : DatabaseMigrations {+        override val migrations = emptyList<androidx.room.migration.Migration>()+    }+}
travel/src/main/java/com/vayunmathur/travel/network/CarDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/CarDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/CarDto.ktnew file mode 100644index 0000000000..31ba24ff13--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/network/CarDto.kt@@ -0,0 +1,17 @@+package com.vayunmathur.travel.network++import kotlinx.serialization.Serializable++/**+ * A car-rental offer from `/api/travel/cars`. Coverage is limited upstream, so+ * this is deep-link-first: [price] is often 0 (unknown) and the UI shows a+ * "See prices" affordance that opens [bookingUrl].+ */+@Serializable+data class CarDto(+    val name: String = "",+    val price: Double = 0.0,+    val currency: String = "usd",+    val provider: String = "",+    val bookingUrl: String = "",+)
travel/src/main/java/com/vayunmathur/travel/network/FlightDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/FlightDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/FlightDto.ktnew file mode 100644index 0000000000..f7d29cd4bd--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/network/FlightDto.kt@@ -0,0 +1,24 @@+package com.vayunmathur.travel.network++import kotlinx.serialization.Serializable++/**+ * A single cheapest-fare flight offer from `/api/travel/flights`.+ *+ * Note: Aviasales data is *cached aggregated prices* (cheapest fare seen per+ * route/date), not live availability, so [price] is indicative. [bookingUrl] is+ * the affiliate deep-link that opens the provider to complete the booking.+ */+@Serializable+data class FlightDto(+    val price: Double = 0.0,+    val currency: String = "usd",+    val origin: String = "",+    val destination: String = "",+    val departureAt: String = "",+    val returnAt: String? = null,+    val airline: String = "",+    val flightNumber: String = "",+    val transfers: Int = 0,+    val bookingUrl: String = "",+)
travel/src/main/java/com/vayunmathur/travel/network/HotelDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/HotelDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/HotelDto.ktnew file mode 100644index 0000000000..4fa93781c5--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/network/HotelDto.kt@@ -0,0 +1,14 @@+package com.vayunmathur.travel.network++import kotlinx.serialization.Serializable++/** A single hotel offer from `/api/travel/hotels`. */+@Serializable+data class HotelDto(+    val name: String = "",+    val stars: Int = 0,+    val price: Double = 0.0,+    val currency: String = "usd",+    val location: String = "",+    val bookingUrl: String = "",+)
travel/src/main/java/com/vayunmathur/travel/network/PlaceDto.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/PlaceDto.kt b/travel/src/main/java/com/vayunmathur/travel/network/PlaceDto.ktnew file mode 100644index 0000000000..a6a5bfbff8--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/network/PlaceDto.kt@@ -0,0 +1,26 @@+package com.vayunmathur.travel.network++import kotlinx.serialization.Serializable++/**+ * An airport or city returned by `/api/travel/places`. [code] is the IATA+ * airport code (or a city code) the flight/hotel searches take as input;+ * [kind] is `"airport"` or `"city"`.+ */+@Serializable+data class PlaceDto(+    val code: String = "",+    val name: String = "",+    val city: String = "",+    val country: String = "",+    val type: String = "",+) {+    /** A one-line label for autocomplete rows, e.g. "JFK · New York, United States". */+    val label: String+        get() = buildString {+            append(code)+            if (name.isNotBlank() && name != code) append(" · ").append(name)+            val place = listOf(city, country).filter { it.isNotBlank() && it != name }+            if (place.isNotEmpty()) append(", ").append(place.joinToString(", "))+        }+}
travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt b/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.ktnew file mode 100644index 0000000000..edcdfb3bdf--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt@@ -0,0 +1,87 @@+package com.vayunmathur.travel.network++import com.vayunmathur.library.network.NetworkClient+import java.net.URLEncoder++/**+ * Thin wrapper over the shared [NetworkClient] for the `/api/travel/*` endpoints+ * on the self-hosted proxy (`api.vayunmathur.com`). The proxy holds the+ * Travelpayouts token/affiliate marker server-side, so the app ships no secret;+ * it just does URL construction + delegation to the Ktor client.+ *+ * Modeled after [com.vayunmathur.weather.network.WeatherApi]. Each call throws+ * on network/parse failure; callers (the ViewModel) wrap in try/catch and+ * surface an error state.+ */+object TravelApi {++    private const val BASE = "https://api.vayunmathur.com/api/travel"++    private fun enc(s: String): String = URLEncoder.encode(s, "UTF-8")++    /** Airport/city autocomplete. Returns empty for a blank query. */+    suspend fun places(query: String): List<PlaceDto> {+        if (query.isBlank()) return emptyList()+        return NetworkClient.getJson("$BASE/places?q=${enc(query)}")+    }++    /**+     * Cheapest fares for a route. [depart] / [ret] are `YYYY-MM-DD`; omit [ret]+     * for one-way. [adults] is forwarded but ignored by the aggregated upstream.+     */+    suspend fun flights(+        origin: String,+        destination: String,+        depart: String,+        ret: String? = null,+        adults: Int = 1,+        currency: String = "usd",+    ): List<FlightDto> {+        val url = buildString {+            append(BASE).append("/flights")+            append("?origin=").append(enc(origin))+            append("&destination=").append(enc(destination))+            append("&depart=").append(enc(depart))+            if (!ret.isNullOrBlank()) append("&return=").append(enc(ret))+            append("&adults=").append(adults)+            append("&currency=").append(enc(currency))+        }+        return NetworkClient.getJson(url)+    }++    /** Hotel offers for a location and date range. */+    suspend fun hotels(+        location: String,+        checkin: String,+        checkout: String,+        adults: Int = 2,+        currency: String = "usd",+    ): List<HotelDto> {+        val url = buildString {+            append(BASE).append("/hotels")+            append("?location=").append(enc(location))+            append("&checkin=").append(enc(checkin))+            append("&checkout=").append(enc(checkout))+            append("&adults=").append(adults)+            append("&currency=").append(enc(currency))+        }+        return NetworkClient.getJson(url)+    }++    /** Best-effort car-rental offers (deep-link-first; see [CarDto]). */+    suspend fun cars(+        location: String,+        pickup: String,+        dropoff: String,+        currency: String = "usd",+    ): List<CarDto> {+        val url = buildString {+            append(BASE).append("/cars")+            append("?location=").append(enc(location))+            append("&pickup=").append(enc(pickup))+            append("&dropoff=").append(enc(dropoff))+            append("&currency=").append(enc(currency))+        }+        return NetworkClient.getJson(url)+    }+}
travel/src/main/java/com/vayunmathur/travel/ui/CarSearchForm.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/CarSearchForm.kt b/travel/src/main/java/com/vayunmathur/travel/ui/CarSearchForm.ktnew file mode 100644index 0000000000..a86732db5e--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/CarSearchForm.kt@@ -0,0 +1,51 @@+package com.vayunmathur.travel.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.travel.util.TravelViewModel++/**+ * Car search form: pickup location + pickup/drop-off dates. Upstream car+ * coverage is limited, so this is deep-link-first — the results page opens the+ * affiliate provider to see live prices.+ */+@Composable+fun CarSearchForm(+    @Suppress("UNUSED_PARAMETER") viewModel: TravelViewModel,+    onSearch: (location: String, pickup: String, dropoff: String) -> Unit,+    modifier: Modifier = Modifier,+) {+    var location by remember { mutableStateOf("") }+    var pickup by remember { mutableStateOf("") }+    var dropoff by remember { mutableStateOf("") }++    Column(modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+        OutlinedTextField(+            value = location,+            onValueChange = { location = it },+            label = { Text("Pickup city or airport") },+            singleLine = true,+            modifier = Modifier.fillMaxWidth(),+        )+        DateField("Pickup", pickup, onDate = { pickup = it })+        DateField("Drop-off", dropoff, onDate = { dropoff = it })++        Button(+            onClick = { onSearch(location, pickup, dropoff) },+            enabled = location.isNotBlank() && pickup.isNotBlank() && dropoff.isNotBlank(),+            modifier = Modifier.fillMaxWidth(),+        ) { Text("Search cars") }+    }+}
travel/src/main/java/com/vayunmathur/travel/ui/Common.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/Common.kt b/travel/src/main/java/com/vayunmathur/travel/ui/Common.ktnew file mode 100644index 0000000000..004a7634bb--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/Common.kt@@ -0,0 +1,330 @@+package com.vayunmathur.travel.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.matchParentSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.filled.CalendarMonth+import androidx.compose.material.icons.filled.DirectionsCar+import androidx.compose.material.icons.filled.Favorite+import androidx.compose.material.icons.filled.FavoriteBorder+import androidx.compose.material.icons.filled.Flight+import androidx.compose.material.icons.filled.Hotel+import androidx.compose.material.icons.filled.Remove+import androidx.compose.material.icons.filled.Star+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+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.graphics.vector.ImageVector+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.DatePicker+import com.vayunmathur.library.ui.DatePickerDialog+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+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 com.vayunmathur.travel.network.PlaceDto+import com.vayunmathur.travel.util.TravelViewModel+import java.time.Instant+import java.time.LocalDate+import java.time.ZoneOffset+import java.time.format.DateTimeFormatter++@Composable+fun SectionHeader(text: String, modifier: Modifier = Modifier) {+    Text(+        text,+        style = MaterialTheme.typography.titleSmall,+        color = MaterialTheme.colorScheme.primary,+        fontWeight = FontWeight.SemiBold,+        modifier = modifier.padding(horizontal = 16.dp, vertical = 8.dp),+    )+}++/** A row of up to [max] stars, [stars] of them filled (hotel rating). */+@Composable+fun StarRow(stars: Int, max: Int = 5, modifier: Modifier = Modifier) {+    if (stars <= 0) return+    val filled = MaterialTheme.colorScheme.tertiary+    Row(modifier) {+        repeat(stars.coerceIn(0, max)) {+            Icon(Icons.Filled.Star, contentDescription = null, tint = filled, modifier = Modifier.size(16.dp))+        }+    }+}++/**+ * Airport/city autocomplete field. Owns its own text; reports the chosen code+ * back via [onCodeChange] — either an IATA/city code when a suggestion is+ * tapped, or the raw typed text as a fallback so power users can type "LON".+ */+@Composable+fun PlaceAutocompleteField(+    label: String,+    viewModel: TravelViewModel,+    onCodeChange: (String) -> Unit,+    modifier: Modifier = Modifier,+    initialText: String = "",+) {+    var text by remember { mutableStateOf(initialText) }+    var suggestions by remember { mutableStateOf<List<PlaceDto>>(emptyList()) }+    var justSelected by remember { mutableStateOf(false) }++    LaunchedEffect(text) {+        if (justSelected) {+            justSelected = false+            return@LaunchedEffect+        }+        if (text.length < 2) {+            suggestions = emptyList()+            return@LaunchedEffect+        }+        kotlinx.coroutines.delay(250)+        suggestions = viewModel.autocomplete(text)+    }++    Column(modifier) {+        OutlinedTextField(+            value = text,+            onValueChange = {+                text = it+                onCodeChange(it.trim())+            },+            label = { Text(label) },+            singleLine = true,+            modifier = Modifier.fillMaxWidth(),+        )+        if (suggestions.isNotEmpty()) {+            ElevatedCard(Modifier.fillMaxWidth().padding(top = 4.dp)) {+                Column {+                    suggestions.take(6).forEach { place ->+                        ListItem(+                            modifier = Modifier.clickable {+                                onCodeChange(place.code)+                                text = "${place.code} · ${place.city.ifBlank { place.name }}"+                                justSelected = true+                                suggestions = emptyList()+                            },+                        ) { Text(place.label) }+                    }+                }+            }+        }+    }+}++/**+ * 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.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DateField(+    label: String,+    value: String,+    onDate: (String) -> Unit,+    modifier: Modifier = Modifier,+) {+    var show by remember { mutableStateOf(false) }+    val display = if (value.isBlank()) "" else runCatching {+        LocalDate.parse(value).format(DateTimeFormatter.ofPattern("EEE, MMM d"))+    }.getOrDefault(value)++    Box(modifier) {+        OutlinedTextField(+            value = display,+            onValueChange = {},+            readOnly = true,+            enabled = false,+            label = { Text(label) },+            leadingIcon = { Icon(Icons.Filled.CalendarMonth, contentDescription = null) },+            modifier = Modifier.fillMaxWidth(),+        )+        Box(+            Modifier+                .matchParentSize()+                .clickable { show = true }+        )+    }++    if (show) {+        val state = rememberDatePickerState(+            initialSelectedDateMillis = runCatching { LocalDate.parse(value) }+                .getOrNull()+                ?.atStartOfDay(ZoneOffset.UTC)+                ?.toInstant()+                ?.toEpochMilli(),+        )+        DatePickerDialog(+            onDismissRequest = { show = false },+            confirmButton = {+                TextButton(onClick = {+                    state.selectedDateMillis?.let { ms ->+                        val date = Instant.ofEpochMilli(ms).atZone(ZoneOffset.UTC).toLocalDate()+                        onDate(date.toString())+                    }+                    show = false+                }) { Text("OK") }+            },+            dismissButton = { TextButton(onClick = { show = false }) { Text("Cancel") } },+        ) { DatePicker(state) }+    }+}++/** A +/- stepper for a small integer count (passengers, rooms). */+@Composable+fun CountStepper(+    label: String,+    count: Int,+    onCount: (Int) -> Unit,+    modifier: Modifier = Modifier,+    min: Int = 1,+    max: Int = 9,+) {+    Row(+        modifier+            .fillMaxWidth()+            .padding(vertical = 4.dp),+        verticalAlignment = Alignment.CenterVertically,+        horizontalArrangement = Arrangement.SpaceBetween,+    ) {+        Text(label, style = MaterialTheme.typography.bodyLarge)+        Row(verticalAlignment = Alignment.CenterVertically) {+            IconButton(onClick = { onCount((count - 1).coerceAtLeast(min)) }, enabled = count > min) {+                Icon(Icons.Filled.Remove, contentDescription = "Fewer")+            }+            Text("$count", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 8.dp))+            IconButton(onClick = { onCount((count + 1).coerceAtMost(max)) }, enabled = count < max) {+                Icon(Icons.Filled.Add, contentDescription = "More")+            }+        }+    }+}++/** A price like "$412" / "€220"; "See prices" when [price] is 0 (unknown). */+fun formatPrice(price: Double, currency: String): String {+    if (price <= 0.0) return "See prices"+    val symbol = when (currency.lowercase()) {+        "usd" -> "$"+        "eur" -> "€"+        "gbp" -> "£"+        else -> currency.uppercase() + " "+    }+    return symbol + (if (price % 1.0 == 0.0) price.toInt().toString() else "%.2f".format(price))+}++/**+ * A reusable result card: title + subtitle on the left, a price and a "Book"+ * button on the right, and a favorite toggle.+ */+@Composable+fun ResultCard(+    title: String,+    subtitle: String,+    price: Double,+    currency: String,+    isFavorite: Boolean,+    onFavorite: () -> Unit,+    onBook: () -> Unit,+    modifier: Modifier = Modifier,+    extra: (@Composable () -> Unit)? = null,+) {+    ElevatedCard(+        modifier = modifier+            .fillMaxWidth()+            .padding(horizontal = 16.dp, vertical = 4.dp),+    ) {+        Row(+            Modifier+                .fillMaxWidth()+                .padding(16.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            Column(Modifier.weight(1f)) {+                Text(title, style = MaterialTheme.typography.titleMedium)+                if (subtitle.isNotBlank()) {+                    Text(+                        subtitle,+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }+                extra?.invoke()+            }+            Column(horizontalAlignment = Alignment.End) {+                Text(+                    formatPrice(price, currency),+                    style = MaterialTheme.typography.titleMedium,+                    color = MaterialTheme.colorScheme.primary,+                    fontWeight = FontWeight.SemiBold,+                )+                Row(verticalAlignment = Alignment.CenterVertically) {+                    IconButton(onClick = onFavorite) {+                        if (isFavorite) {+                            Icon(Icons.Filled.Favorite, contentDescription = "Saved", tint = MaterialTheme.colorScheme.tertiary)+                        } else {+                            Icon(Icons.Filled.FavoriteBorder, contentDescription = "Save")+                        }+                    }+                    TextButton(onClick = onBook) { Text("Book") }+                }+            }+        }+    }+}++/** Centered loading/error/empty state used by every results page. */+@Composable+fun StatusBox(+    loading: Boolean,+    error: String?,+    isEmpty: Boolean,+    modifier: Modifier = Modifier,+    emptyMessage: String = "No results found. Try different dates or destinations.",+) {+    Box(modifier.fillMaxWidth().heightIn(min = 200.dp), contentAlignment = Alignment.Center) {+        when {+            loading -> CircularProgressIndicator()+            error != null -> Text(+                error,+                color = MaterialTheme.colorScheme.error,+                modifier = Modifier.padding(24.dp),+            )+            isEmpty -> Text(+                emptyMessage,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                modifier = Modifier.padding(24.dp),+            )+        }+    }+}++fun verticalIcon(vertical: com.vayunmathur.travel.data.Vertical): ImageVector = when (vertical) {+    com.vayunmathur.travel.data.Vertical.FLIGHTS -> Icons.Filled.Flight+    com.vayunmathur.travel.data.Vertical.HOTELS -> Icons.Filled.Hotel+    com.vayunmathur.travel.data.Vertical.CARS -> Icons.Filled.DirectionsCar+}
travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt b/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.ktnew file mode 100644index 0000000000..f70c935f6f--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FlightResultsPage.kt@@ -0,0 +1,109 @@+package com.vayunmathur.travel.ui++import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.travel.Route+import com.vayunmathur.travel.data.Favorite+import com.vayunmathur.travel.data.Vertical+import com.vayunmathur.travel.network.FlightDto+import com.vayunmathur.travel.util.TravelViewModel+import com.vayunmathur.travel.util.openBooking++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun FlightResultsPage(+    backStack: NavBackStack<Route>,+    viewModel: TravelViewModel,+    route: Route.FlightResults,+) {+    val context = LocalContext.current+    val state by viewModel.flights.collectAsStateWithLifecycle()+    val favorites by viewModel.favorites.collectAsStateWithLifecycle()++    LaunchedEffect(route) {+        viewModel.searchFlights(route.origin, route.destination, route.depart, route.returnDate, route.adults)+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("${route.origin} → ${route.destination}") },+                navigationIcon = {+                    IconButton(onClick = { backStack.pop() }) {+                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")+                    }+                },+            )+        },+    ) { padding ->+        LazyColumn(+            modifier = Modifier.fillMaxSize().padding(padding),+            contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp),+        ) {+            items(state.results) { flight ->+                val fav = favorites.any { it.bookingUrl == flight.bookingUrl }+                ResultCard(+                    title = flightTitle(flight),+                    subtitle = flightSubtitle(flight),+                    price = flight.price,+                    currency = flight.currency,+                    isFavorite = fav,+                    onFavorite = { viewModel.toggleFavorite(flight.toFavorite()) },+                    onBook = { openBooking(context, flight.bookingUrl) },+                )+            }+            if (state.loading || state.error != null || (state.hasSearched && state.results.isEmpty())) {+                item {+                    StatusBox(+                        loading = state.loading,+                        error = state.error,+                        isEmpty = state.hasSearched && state.results.isEmpty(),+                    )+                }+            }+        }+    }+}++private fun flightTitle(f: FlightDto): String {+    val airline = f.airline.ifBlank { "Flight" }+    return if (f.flightNumber.isBlank()) airline else "$airline ${f.flightNumber}"+}++private fun flightSubtitle(f: FlightDto): String {+    val date = TravelViewModel.prettyDate(f.departureAt.take(10))+    val stops = when (f.transfers) {+        0 -> "Nonstop"+        1 -> "1 stop"+        else -> "${f.transfers} stops"+    }+    val ret = f.returnAt?.takeIf { it.isNotBlank() }?.let { " · Return ${TravelViewModel.prettyDate(it.take(10))}" } ?: ""+    return "$date · $stops$ret"+}++private fun FlightDto.toFavorite() = Favorite(+    bookingUrl = bookingUrl,+    vertical = Vertical.FLIGHTS.name,+    title = flightTitle(this),+    subtitle = "$origin → $destination · ${flightSubtitle(this)}",+    price = price,+    currency = currency,+)
travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt b/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.ktnew file mode 100644index 0000000000..9ed9d73d8f--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/FlightSearchForm.kt@@ -0,0 +1,74 @@+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.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.unit.dp+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.travel.util.TravelViewModel++/**+ * Flight search form: origin/destination autocomplete, depart (+ optional+ * return) dates, and a passenger count. Calls [onSearch] with the collected+ * query when the user taps "Search flights".+ */+@Composable+fun FlightSearchForm(+    viewModel: TravelViewModel,+    onSearch: (origin: String, destination: String, depart: String, ret: String?, adults: Int) -> Unit,+    modifier: Modifier = Modifier,+) {+    var origin by remember { mutableStateOf("") }+    var destination by remember { mutableStateOf("") }+    var depart by remember { mutableStateOf("") }+    var roundTrip by remember { mutableStateOf(false) }+    var returnDate by remember { mutableStateOf("") }+    var adults by remember { mutableIntStateOf(1) }++    Column(modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+        PlaceAutocompleteField("From", viewModel, onCodeChange = { origin = it })+        PlaceAutocompleteField("To", viewModel, onCodeChange = { destination = it })+        DateField("Depart", depart, onDate = { depart = it })++        Row(+            Modifier.fillMaxWidth(),+            verticalAlignment = Alignment.CenterVertically,+            horizontalArrangement = Arrangement.SpaceBetween,+        ) {+            Text("Round trip")+            Switch(checked = roundTrip, onCheckedChange = { roundTrip = it })+        }+        if (roundTrip) {+            DateField("Return", returnDate, onDate = { returnDate = it })+        }++        CountStepper("Passengers", adults, onCount = { adults = it })++        Button(+            onClick = {+                onSearch(+                    origin,+                    destination,+                    depart,+                    returnDate.takeIf { roundTrip && it.isNotBlank() },+                    adults,+                )+            },+            enabled = origin.isNotBlank() && destination.isNotBlank() && depart.isNotBlank() &&+                (!roundTrip || returnDate.isNotBlank()),+            modifier = Modifier.fillMaxWidth(),+        ) { Text("Search flights") }+    }+}
travel/src/main/java/com/vayunmathur/travel/ui/HotelSearchForm.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/ui/HotelSearchForm.kt b/travel/src/main/java/com/vayunmathur/travel/ui/HotelSearchForm.ktnew file mode 100644index 0000000000..7c3a8f6a42--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/ui/HotelSearchForm.kt@@ -0,0 +1,53 @@+package com.vayunmathur.travel.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.travel.util.TravelViewModel++/**+ * Hotel search form: destination (free text — the proxy resolves the location),+ * check-in/out dates, and a guest count.+ */+@Composable+fun HotelSearchForm(+    @Suppress("UNUSED_PARAMETER") viewModel: TravelViewModel,+    onSearch: (location: String, checkin: String, checkout: String, adults: Int) -> Unit,+    modifier: Modifier = Modifier,+) {+    var location by remember { mutableStateOf("") }+    var checkin by remember { mutableStateOf("") }+    var checkout by remember { mutableStateOf("") }+    var adults by remember { mutableIntStateOf(2) }++    Column(modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+        OutlinedTextField(+            value = location,+            onValueChange = { location = it },+            label = { Text("City or destination") },+            singleLine = true,+            modifier = Modifier.fillMaxWidth(),+        )+        DateField("Check-in", checkin, onDate = { checkin = it })+        DateField("Check-out", checkout, onDate = { checkout = it })+        CountStepper("Guests", adults, onCount = { adults = it })++        Button(+            onClick = { onSearch(location, checkin, checkout, adults) },+            enabled = location.isNotBlank() && checkin.isNotBlank() && checkout.isNotBlank(),+            modifier = Modifier.fillMaxWidth(),+        ) { Text("Search hotels") }+    }+}
travel/src/main/java/com/vayunmathur/travel/util/Booking.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/Booking.kt b/travel/src/main/java/com/vayunmathur/travel/util/Booking.ktnew file mode 100644index 0000000000..b2bdc63729--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/util/Booking.kt@@ -0,0 +1,17 @@+package com.vayunmathur.travel.util++import android.content.Context+import android.content.Intent+import androidx.core.net.toUri++/**+ * Opens an affiliate [bookingUrl] in the user's browser / a Custom Tab via a+ * plain `ACTION_VIEW` intent. v1 deep-links out to the provider to complete the+ * booking — there are no in-app payments.+ */+fun openBooking(context: Context, bookingUrl: String) {+    if (bookingUrl.isBlank()) return+    val intent = Intent(Intent.ACTION_VIEW, bookingUrl.toUri())+        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+    runCatching { context.startActivity(intent) }+}
travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt b/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.ktnew file mode 100644index 0000000000..2326558ef9--- /dev/null+++ b/travel/src/main/java/com/vayunmathur/travel/util/TravelViewModel.kt@@ -0,0 +1,202 @@+package com.vayunmathur.travel.util++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import com.vayunmathur.travel.data.Favorite+import com.vayunmathur.travel.data.FavoriteDao+import com.vayunmathur.travel.data.RecentSearch+import com.vayunmathur.travel.data.RecentSearchDao+import com.vayunmathur.travel.data.Vertical+import com.vayunmathur.travel.network.CarDto+import com.vayunmathur.travel.network.FlightDto+import com.vayunmathur.travel.network.HotelDto+import com.vayunmathur.travel.network.PlaceDto+import com.vayunmathur.travel.network.TravelApi+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++/** Generic search state for one vertical's results list. */+data class SearchUiState<T>(+    val loading: Boolean = false,+    val error: String? = null,+    val results: List<T> = emptyList(),+    val hasSearched: Boolean = false,+)++/**+ * The single hub for the Travel app: owns the per-vertical search state (calling+ * [TravelApi] and exposing loading/error/results as [StateFlow]) and persists+ * recent searches + favorites through the Room [RecentSearchDao] / [FavoriteDao].+ *+ * Modeled after [com.vayunmathur.weather.util.WeatherViewModel] and+ * `EducationViewModel` (manual [ViewModelProvider.Factory]).+ */+class TravelViewModel(+    application: Application,+    private val recentSearchDao: RecentSearchDao,+    private val favoriteDao: FavoriteDao,+) : AndroidViewModel(application) {++    private val _flights = MutableStateFlow(SearchUiState<FlightDto>())+    val flights: StateFlow<SearchUiState<FlightDto>> = _flights.asStateFlow()++    private val _hotels = MutableStateFlow(SearchUiState<HotelDto>())+    val hotels: StateFlow<SearchUiState<HotelDto>> = _hotels.asStateFlow()++    private val _cars = MutableStateFlow(SearchUiState<CarDto>())+    val cars: StateFlow<SearchUiState<CarDto>> = _cars.asStateFlow()++    val recentSearches: StateFlow<List<RecentSearch>> = recentSearchDao.observeRecent()+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    val favorites: StateFlow<List<Favorite>> = favoriteDao.observeAll()+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    // --- Autocomplete -----------------------------------------------------++    /** Airport/city suggestions for [query]; never throws (empty on failure). */+    suspend fun autocomplete(query: String): List<PlaceDto> =+        runCatching { TravelApi.places(query) }.getOrDefault(emptyList())++    // --- Searches ---------------------------------------------------------++    fun searchFlights(+        origin: String,+        destination: String,+        depart: String,+        ret: String?,+        adults: Int,+        currency: String = "usd",+    ) {+        recordRecent(+            RecentSearch(+                vertical = Vertical.FLIGHTS.name,+                label = "$origin → $destination · ${prettyDate(depart)}",+                origin = origin,+                destination = destination,+                depart = depart,+                returnDate = ret,+                adults = adults,+            )+        )+        _flights.value = SearchUiState(loading = true, hasSearched = true)+        viewModelScope.launch {+            runCatching { TravelApi.flights(origin, destination, depart, ret, adults, currency) }+                .onSuccess { _flights.value = SearchUiState(results = it, hasSearched = true) }+                .onFailure { _flights.value = SearchUiState(error = errorMessage(it), hasSearched = true) }+        }+    }++    fun searchHotels(+        location: String,+        checkin: String,+        checkout: String,+        adults: Int,+        currency: String = "usd",+    ) {+        recordRecent(+            RecentSearch(+                vertical = Vertical.HOTELS.name,+                label = "$location · ${prettyDate(checkin)}–${prettyDate(checkout)}",+                location = location,+                checkin = checkin,+                checkout = checkout,+                adults = adults,+            )+        )+        _hotels.value = SearchUiState(loading = true, hasSearched = true)+        viewModelScope.launch {+            runCatching { TravelApi.hotels(location, checkin, checkout, adults, currency) }+                .onSuccess { _hotels.value = SearchUiState(results = it, hasSearched = true) }+                .onFailure { _hotels.value = SearchUiState(error = errorMessage(it), hasSearched = true) }+        }+    }++    fun searchCars(+        location: String,+        pickup: String,+        dropoff: String,+        currency: String = "usd",+    ) {+        recordRecent(+            RecentSearch(+                vertical = Vertical.CARS.name,+                label = "$location · ${prettyDate(pickup)}–${prettyDate(dropoff)}",+                location = location,+                pickup = pickup,+                dropoff = dropoff,+            )+        )+        _cars.value = SearchUiState(loading = true, hasSearched = true)+        viewModelScope.launch {+            runCatching { TravelApi.cars(location, pickup, dropoff, currency) }+                .onSuccess { _cars.value = SearchUiState(results = it, hasSearched = true) }+                .onFailure { _cars.value = SearchUiState(error = errorMessage(it), hasSearched = true) }+        }+    }++    // --- Favorites --------------------------------------------------------++    fun isFavorite(bookingUrl: String): Boolean =+        favorites.value.any { it.bookingUrl == bookingUrl }++    /** Add the offer to favorites, or remove it if it's already saved. */+    fun toggleFavorite(favorite: Favorite) {+        viewModelScope.launch {+            if (favorites.value.any { it.bookingUrl == favorite.bookingUrl }) {+                favoriteDao.deleteByUrl(favorite.bookingUrl)+            } else {+                favoriteDao.upsert(favorite)+            }+        }+    }++    fun removeFavorite(favorite: Favorite) {+        viewModelScope.launch { favoriteDao.deleteByUrl(favorite.bookingUrl) }+    }++    // --- Recents ----------------------------------------------------------++    fun clearRecents() {+        viewModelScope.launch { recentSearchDao.clear() }+    }++    private fun recordRecent(search: RecentSearch) {+        viewModelScope.launch {+            recentSearchDao.insert(search)+            recentSearchDao.trim()+        }+    }++    companion object {+        /** "2026-09-01" -> "Sep 1"; falls back to the raw string on any parse error. */+        fun prettyDate(iso: String): String = runCatching {+            val date = java.time.LocalDate.parse(iso.take(10))+            date.format(java.time.format.DateTimeFormatter.ofPattern("MMM d"))+        }.getOrDefault(iso)++        private fun errorMessage(t: Throwable): String =+            t.message?.takeIf { it.isNotBlank() } ?: "Something went wrong. Please try again."+    }+}++class TravelViewModelFactory(+    private val application: Application,+    private val recentSearchDao: RecentSearchDao,+    private val favoriteDao: FavoriteDao,+) : ViewModelProvider.Factory {+    @Suppress("UNCHECKED_CAST")+    override fun <T : ViewModel> create(modelClass: Class<T>): T {+        require(modelClass.isAssignableFrom(TravelViewModel::class.java)) {+            "Unexpected ViewModel class: $modelClass"+        }+        return TravelViewModel(application, recentSearchDao, favoriteDao) as T+    }+}
travel/src/main/res/values/strings.xml
diff --git a/travel/src/main/res/values/strings.xml b/travel/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..732581df10--- /dev/null+++ b/travel/src/main/res/values/strings.xml@@ -0,0 +1,3 @@+<resources>+    <string name="app_name">Travel</string>+</resources>