Modern Apps git

← Modern-Apps.git

shop: encrypted buyer profile gate; checkout fills buyer and delivery address from profile

Commit
08e44e13844acab4f4dcd56ca2f208f63ddeecb4
Author
Vayun Mathur <[email protected]>
When
2026-11-01 05:51 UTC (1 month ago)
Parents
af9916e

Diff

metadata_data/shop.md
diff --git a/metadata_data/shop.md b/metadata_data/shop.mdindex 9419802484..61eb803dc9 100644--- a/metadata_data/shop.md+++ b/metadata_data/shop.md@@ -5,6 +5,7 @@ Features: - Validate each merchant's live advertised profile before showing products; directory badges are leads, not access grants - Refresh product details to confirm the exact variant before adding integer-quantity items to the cart - Prepare checkout sessions with per-merchant totals plus authoritative checkout totals and legal links+- Save your name, contact details and delivery address once in an encrypted profile; checkout fills them in automatically - Pending sessions and cart lines survive browser handoffs and partial failures without confirming a paid order - Native payment completion stays disabled without a supported handler, provider approval, and authorized merchant access 
shop/AGENTS.md
diff --git a/shop/AGENTS.md b/shop/AGENTS.mdindex e86892dc43..bd8294f6d3 100644--- a/shop/AGENTS.md+++ b/shop/AGENTS.md@@ -10,8 +10,9 @@ Entry types: MainActivity, Route, Navigation. Navigation remains a root-only gra - Anonymous catalog and checkout preparation using supported UCP 2026-08-25 and 2026-04-08 profiles, resolved server-side. The server selects one complete advertised profile and exact capability/service versions; it never merges releases. - Server error codes mirror the former client `UcpError` (`transport | rate_limited | http | malformed | rpc | unsupported | uncertain`, plus `retryAfterMs`): `unsupported` routes to the merchant website, anything else on a write is uncertain and never auto-retried on either side. - The Merchants tab loads the directory through the proxy. Cache/filter locally; the server validates on first use.-- Buyer/fulfillment review is ephemeral. Merchant totals and legal links are authoritative.-- Checkout writes require explicit user action and a stable idempotency key per intent. Never replay an uncertain mutation automatically.+- The buyer profile (first name, last name, email, phone required; delivery address optional) is stored only in the module's SQLCipher Room database (`ProfileRepository`). The app is locked behind the profile form until the required fields validate; the Profile tab edits it.+- Checkout takes no buyer input: every session field comes from the saved profile (`ProfileCheckout`). Merchant shipping-option choices remain selectable. Merchant totals and legal links are authoritative.+- Checkout writes require explicit user action and a stable idempotency key per intent. Never replay an uncertain mutation automatically. One Create press may issue a second write that carries the saved delivery address, only after the create succeeded and the merchant advertised shipping or reported `delivery_address_required`. - Preserve cart lines through partial failures and browser handoffs. A session or browser return is not a paid order. - No raw card entry, wallet tokenization, completion or authenticated order-read integration while provider authorization is unavailable. - Only supported integer quantities can be added. Detail refresh sends the product ID and selected options, and must confirm the exact variant before cart actions. If a valid detail response returns only another featured option, one fresh advertised merchant search may confirm the exact SKU. Cached snapshots and empty lookup responses are not verification; denied/rate-limited calls are never retried automatically.@@ -23,7 +24,7 @@ Entry types: MainActivity, Route, Navigation. Navigation remains a root-only gra  ## Responsibilities - `ShopBackend` owns the four server calls (search/product/checkout/merchants) plus error-envelope mapping. It never talks to merchant hosts.-- ShopViewModel owns explicit cart and per-merchant native-review state. Buyer PII must never enter logs or persisted history.+- ShopViewModel owns explicit cart, profile and per-merchant native-review state. Buyer PII must never enter logs or persisted history; the encrypted profile database is its only store. - Local stores retain pending checkout records for browser recovery, not order confirmations. - UI uses shared app scaffolds and controls; one public composable per file. Metadata previews are class members with PreviewTest and Preview. 
shop/build.gradle.kts
diff --git a/shop/build.gradle.kts b/shop/build.gradle.ktsindex 5a205d124f..257bd303d7 100644--- a/shop/build.gradle.kts+++ b/shop/build.gradle.kts@@ -23,4 +23,7 @@ dependencies {     implementation(project(":library:image"))     // Hosted-checkout fallback (continue_url) in a Custom Tab.     implementation(libs.androidx.browser)+    // Buyer profile (name, contact, delivery address), encrypted at rest.+    implementRoom(libs)+    implementation(project(":library:room")) }
shop/src/main/java/com/vayunmathur/shop/Navigation.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt b/shop/src/main/java/com/vayunmathur/shop/Navigation.ktindex 2ffc3123d7..0d3973fdfa 100644--- a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt+++ b/shop/src/main/java/com/vayunmathur/shop/Navigation.kt@@ -1,6 +1,8 @@ package com.vayunmathur.shop  import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.platform.LocalContext import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.shop.platform.ShopViewModel@@ -8,10 +10,18 @@ import com.vayunmathur.shop.ui.CartScreen import com.vayunmathur.shop.ui.CheckoutScreen import com.vayunmathur.shop.ui.OrdersScreen import com.vayunmathur.shop.ui.ProductScreen+import com.vayunmathur.shop.ui.ProfileScreen import com.vayunmathur.shop.ui.ShopTabs  @Composable fun Navigation(viewModel: ShopViewModel) {+    val context = LocalContext.current+    LaunchedEffect(viewModel) { viewModel.observeProfile(context) }+    if (!viewModel.profileLoaded) return+    if (!viewModel.profileComplete) {+        ProfileScreen(viewModel, required = true)+        return+    }     val backStack = rememberNavBackStack<Route>(Route.Search)     MainNavigation(backStack) {         entry<Route.Search> {
shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.kt b/shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.ktnew file mode 100644index 0000000000..4640c31275--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.kt@@ -0,0 +1,24 @@+package com.vayunmathur.shop.data++import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Query+import androidx.room3.RoomDatabase+import androidx.room3.Upsert+import kotlinx.coroutines.flow.Flow++const val PROFILE_DB_NAME = "shop-profile-db"++@Dao+interface ProfileDao {+    @Query("SELECT * FROM ShopProfile WHERE id = 0")+    fun observe(): Flow<ShopProfile?>++    @Upsert+    suspend fun upsert(profile: ShopProfile)+}++@Database(entities = [ShopProfile::class], version = 1, exportSchema = false)+abstract class ProfileDatabase : RoomDatabase() {+    abstract fun profileDao(): ProfileDao+}
shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.kt b/shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.ktnew file mode 100644index 0000000000..ebb3568560--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.kt@@ -0,0 +1,21 @@+package com.vayunmathur.shop.data++import android.content.Context+import com.vayunmathur.library.room.RoomRepository+import kotlinx.coroutines.flow.Flow++class ProfileRepository private constructor(context: Context) :+    RoomRepository<ProfileDatabase>(context, ProfileDatabase::class, PROFILE_DB_NAME) {++    val profile: Flow<ShopProfile?> get() = db.profileDao().observe()++    suspend fun save(profile: ShopProfile) = db.profileDao().upsert(profile.copy(id = 0))++    companion object {+        @Volatile private var instance: ProfileRepository? = null+        fun get(context: Context): ProfileRepository =+            instance ?: synchronized(this) {+                instance ?: ProfileRepository(context).also { instance = it }+            }+    }+}
shop/src/main/java/com/vayunmathur/shop/data/ShopProfile.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/ShopProfile.kt b/shop/src/main/java/com/vayunmathur/shop/data/ShopProfile.ktnew file mode 100644index 0000000000..c7194bf183--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/ShopProfile.kt@@ -0,0 +1,38 @@+package com.vayunmathur.shop.data++import androidx.room3.Entity+import androidx.room3.PrimaryKey++/** Single-row buyer profile. Lives only in the SQLCipher database; never logged or put in history. */+@Entity+data class ShopProfile(+    @PrimaryKey val id: Int = 0,+    val firstName: String = "",+    val lastName: String = "",+    val email: String = "",+    val phone: String = "",+    val street: String = "",+    val extendedAddress: String = "",+    val city: String = "",+    val region: String = "",+    val country: String = "",+    val postalCode: String = "",+) {+    val hasAddress: Boolean get() = checkoutInputs().hasAddress++    fun checkoutInputs(shippingRequested: Boolean = false, options: Map<String, String> = emptyMap()) = CheckoutInputs(+        firstName = firstName.trim(), lastName = lastName.trim(), email = email.trim(), phone = phone.trim(),+        street = street.trim(), extendedAddress = extendedAddress.trim(), city = city.trim(),+        region = region.trim(), country = country.trim(), postalCode = postalCode.trim(),+        options = options, shippingRequested = shippingRequested,+    )++    fun validationError(): String? =+        if (listOf(firstName, lastName, email, phone).any { it.isBlank() }) {+            "Enter your first name, last name, email and phone number."+        } else {+            checkoutInputs().validationError()+        }++    override fun toString(): String = "ShopProfile(redacted)"+}
shop/src/main/java/com/vayunmathur/shop/domain/ProfileCheckout.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/ProfileCheckout.kt b/shop/src/main/java/com/vayunmathur/shop/domain/ProfileCheckout.ktnew file mode 100644index 0000000000..0e6f6a9ceb--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/domain/ProfileCheckout.kt@@ -0,0 +1,22 @@+package com.vayunmathur.shop.domain++import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.NativeCheckoutState+import com.vayunmathur.shop.data.ShopProfile+import com.vayunmathur.shop.data.UcpCheckout++/** Checkout never takes buyer input; every session field is derived from the saved profile. */+object ProfileCheckout {+    fun needsDeliveryAddress(checkout: UcpCheckout?): Boolean = checkout != null && (+        checkout.review.availableShippingLineIds.isNotEmpty() || checkout.review.shipping.isNotEmpty() ||+            checkout.messages.any { it.code == "delivery_address_required" }+        )++    /** The address is only sent once the merchant has issued shipping lines it can attach to. */+    fun inputs(profile: ShopProfile, state: NativeCheckoutState): CheckoutInputs {+        val shipping = profile.hasAddress && needsDeliveryAddress(state.checkout)+        val inputs = profile.checkoutInputs()+        return if (shipping) inputs.copy(shippingRequested = true, options = state.inputs.options)+        else inputs.copy(street = "", extendedAddress = "", city = "", region = "", country = "", postalCode = "")+    }+}
shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.ktindex 593a165dea..7c13bc7698 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -7,17 +7,21 @@ import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.CheckoutPhase import com.vayunmathur.shop.data.NativeCheckoutState import com.vayunmathur.shop.domain.NativeCheckoutCoordinator import com.vayunmathur.shop.domain.PendingCheckoutSink import com.vayunmathur.shop.data.CartLine import com.vayunmathur.shop.data.OrderStore import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.ProfileRepository import com.vayunmathur.shop.data.ShopCartStore+import com.vayunmathur.shop.data.ShopProfile import com.vayunmathur.shop.data.UcpCheckout import com.vayunmathur.shop.data.UcpProduct import com.vayunmathur.shop.data.message import com.vayunmathur.shop.domain.MerchantUrls+import com.vayunmathur.shop.domain.ProfileCheckout import com.vayunmathur.shop.network.ShopBackend import com.vayunmathur.shop.network.ShopBackendException import com.vayunmathur.shop.network.ShopHttpBackend@@ -50,11 +54,32 @@ class ShopViewModel(         private set     var nativeCheckouts by mutableStateOf<List<NativeCheckoutState>>(emptyList())         private set+    var profile by mutableStateOf<ShopProfile?>(null)+        private set+    var profileLoaded by mutableStateOf(false)+        private set+    val profileComplete: Boolean get() = profile?.validationError() == null && profile != null+    private var profileRepository: ProfileRepository? = null     private val nativeCheckout = NativeCheckoutCoordinator(changed = { states ->         nativeCheckouts = states         browserCheckouts = states.mapNotNull { it.checkout }.filter { MerchantUrls.httpsUrl(it.continueUrl) != null }     }) +    fun observeProfile(context: Context) {+        if (profileRepository != null) return+        val repository = ProfileRepository.get(context).also { profileRepository = it }+        viewModelScope.launch { repository.profile.collect { profile = it; profileLoaded = true } }+    }++    fun saveProfile(value: ShopProfile) {+        val repository = profileRepository ?: return+        if (value.validationError() != null) return+        viewModelScope.launch { repository.save(value) }+    }++    fun checkoutInputs(state: NativeCheckoutState): CheckoutInputs? =+        profile?.takeIf { it.validationError() == null }?.let { ProfileCheckout.inputs(it, state) }+     fun editCheckoutInputs(platformId: String, shop: String, inputs: CheckoutInputs) {         nativeCheckout.edit(platformId, shop, inputs)     }@@ -68,14 +93,36 @@ class ShopViewModel(     fun prepareMerchantCheckout(platformId: String, shop: String, context: Context) {         if (placingCheckout) return         val lines = cart.filter { it.platformId == platformId && it.shopDomain == shop }.toList()+        val sink = PendingCheckoutSink { OrderStore.add(context, it) }         viewModelScope.launch {             AppInit.awaitReady()-            nativeCheckout.submit(platformId, shop, lines, PendingCheckoutSink { OrderStore.add(context, it) })+            val created = submitFromProfile(platformId, shop, lines, sink) == null+            // A new session can't carry fulfillment, so the saved address follows as its own write+            // only after the create succeeded. Nothing is replayed if either write is uncertain.+            val state = nativeCheckout.snapshot.firstOrNull { it.platformId == platformId && it.shopDomain == shop }+            if (created && state?.phase == CheckoutPhase.Reviewing && state.checkout != null) {+                submitFromProfile(platformId, shop, lines, sink)+            }             nativeCheckout.cartChanged(cart)             orders = OrderStore.getAll(context)         }     } +    /** Returns the session that existed before this write, if any. */+    private suspend fun submitFromProfile(+        platformId: String,+        shop: String,+        lines: List<CartLine>,+        sink: PendingCheckoutSink,+    ): UcpCheckout? {+        val state = nativeCheckout.snapshot.firstOrNull { it.platformId == platformId && it.shopDomain == shop }+            ?: NativeCheckoutState(platformId, shop)+        val inputs = checkoutInputs(state) ?: return state.checkout+        nativeCheckout.edit(platformId, shop, inputs)+        nativeCheckout.submit(platformId, shop, lines, sink)+        return state.checkout+    }+     fun updateQuery(value: String) { query = value }     fun updateShopDomain(value: String) { searchShopDomain = value } 
shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.ktindex d21b155b5e..2e6060a996 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt@@ -1,35 +1,30 @@ package com.vayunmathur.shop.ui  import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DetailSection-import com.vayunmathur.library.ui.FilterChip 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.appBarScrollBehavior import com.vayunmathur.shop.R-import com.vayunmathur.shop.data.CheckoutInputs import com.vayunmathur.shop.data.CheckoutPhase import com.vayunmathur.shop.data.NativeCheckoutState import com.vayunmathur.shop.domain.MerchantUrls+import com.vayunmathur.shop.domain.ProfileCheckout import com.vayunmathur.shop.platform.ShopViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.isActive@@ -49,7 +44,7 @@ fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit) {         ) {             item {                 Text("Review a merchant checkout session. No order is placed or payment collected here.")-                Text("Buyer details stay in this app session and are sent only when you press Create or Update.", style = MaterialTheme.typography.bodySmall)+                Text("Your profile details are sent only when you press Create or Update.", style = MaterialTheme.typography.bodySmall)             }             viewModel.cart.groupBy { it.platformId to it.shopDomain }.forEach { (key, lines) ->                 val state = viewModel.nativeCheckouts.firstOrNull { it.platformId == key.first && it.shopDomain == key.second }@@ -58,16 +53,12 @@ fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit) {                     DetailSection(key.second.ifBlank { "Unknown store" }) {                         lines.forEach { line -> Text("${line.productTitle} x ${line.quantity}", style = MaterialTheme.typography.bodyMedium) }                         val editable = !state.busy && !viewModel.placingCheckout && state.phase !in setOf(CheckoutPhase.Uncertain, CheckoutPhase.Expired, CheckoutPhase.BrowserRequired)-                        if (state.checkout?.review?.availableShippingLineIds?.isNotEmpty() == true && state.checkout.review.shipping.isEmpty()) {-                            FilterChip(selected = state.inputs.shippingRequested, enabled = editable,-                                onClick = { viewModel.editCheckoutInputs(key.first, key.second, state.inputs.copy(shippingRequested = true)) },-                                label = { Text("Use merchant-advertised shipping") })-                            Text("Select shipping, add an address and update to obtain delivery options.", style = MaterialTheme.typography.bodySmall)-                        }-                        CheckoutBuyerForm(state.inputs, editable, state.checkout?.review?.shipping?.isNotEmpty() == true || state.inputs.shippingRequested) {-                            viewModel.editCheckoutInputs(key.first, key.second, it)-                        }+                        val profileInputs = viewModel.checkoutInputs(state)+                        Text("Buyer details come from your profile.", style = MaterialTheme.typography.bodySmall)                         val checkout = state.checkout+                        if (ProfileCheckout.needsDeliveryAddress(checkout) && viewModel.profile?.hasAddress != true) {+                            Text("This merchant needs a delivery address. Add one in the Profile tab, then update the session.", color = MaterialTheme.colorScheme.error)+                        }                         if (checkout != null) {                             CheckoutReviewContent(                                 state = state,@@ -77,12 +68,11 @@ fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit) {                                 onRefresh = { viewModel.reconcileCheckout(key.first, key.second) },                             )                         }-                        state.inputs.validationError()?.let { Text(it, color = MaterialTheme.colorScheme.error) }                         state.message?.let { Text(it) }                         if (state.phase == CheckoutPhase.Expired) Text("Session expired. Native updates are disabled.")                         Button(                             modifier = Modifier.fillMaxWidth(),-                            enabled = editable && state.inputs.validationError() == null && (checkout == null || state.inputs != state.submittedInputs),+                            enabled = editable && profileInputs != null && (checkout == null || profileInputs != state.submittedInputs),                             onClick = { viewModel.prepareMerchantCheckout(key.first, key.second, context) },                         ) {                             if (state.busy) CircularProgressIndicator()@@ -99,28 +89,3 @@ fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit) {         }     } }--@Composable-private fun CheckoutBuyerForm(inputs: CheckoutInputs, enabled: Boolean, shipping: Boolean, onChange: (CheckoutInputs) -> Unit) {-    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {-        BuyerField("First name", inputs.firstName, enabled) { onChange(inputs.copy(firstName = it)) }-        BuyerField("Last name", inputs.lastName, enabled) { onChange(inputs.copy(lastName = it)) }-        BuyerField("Email", inputs.email, enabled, KeyboardType.Email) { onChange(inputs.copy(email = it)) }-        BuyerField("Phone (international format)", inputs.phone, enabled, KeyboardType.Phone) { onChange(inputs.copy(phone = it)) }-        if (shipping) {-            Text("Shipping address", style = MaterialTheme.typography.titleSmall)-            BuyerField("Street address", inputs.street, enabled) { onChange(inputs.copy(street = it)) }-            BuyerField("Apartment / additional address", inputs.extendedAddress, enabled) { onChange(inputs.copy(extendedAddress = it)) }-            BuyerField("City", inputs.city, enabled) { onChange(inputs.copy(city = it)) }-            BuyerField("State / province", inputs.region, enabled) { onChange(inputs.copy(region = it)) }-            BuyerField("Country (two-letter code)", inputs.country, enabled) { onChange(inputs.copy(country = it.uppercase())) }-            BuyerField("Postal code", inputs.postalCode, enabled) { onChange(inputs.copy(postalCode = it)) }-        } else Text("Create a session first to discover the merchant's shipping choices.", style = MaterialTheme.typography.bodySmall)-    }-}--@Composable-private fun BuyerField(label: String, value: String, enabled: Boolean, keyboard: KeyboardType = KeyboardType.Text, onChange: (String) -> Unit) {-    OutlinedTextField(value = value, onValueChange = onChange, enabled = enabled, label = { Text(label) },-        modifier = Modifier.fillMaxWidth(), singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = keyboard))-}
shop/src/main/java/com/vayunmathur/shop/ui/ProfileScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/ProfileScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/ProfileScreen.ktnew file mode 100644index 0000000000..2b89462088--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ProfileScreen.kt@@ -0,0 +1,81 @@+package com.vayunmathur.shop.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.text.KeyboardOptions+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.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.shop.data.ShopProfile+import com.vayunmathur.shop.platform.ShopViewModel++/** Buyer profile. With [required] it is the first-run gate and the rest of the app stays locked until saved. */+@Composable+fun ProfileScreen(viewModel: ShopViewModel, required: Boolean) {+    val messenger = rememberMessenger()+    val saved = viewModel.profile+    var draft by remember(saved) { mutableStateOf(saved ?: ShopProfile()) }+    val error = draft.validationError()+    AppScaffold(title = "Profile", scrollBehavior = appBarScrollBehavior()) { padding ->+        LazyColumn(+            modifier = Modifier.fillMaxSize().padding(padding),+            contentPadding = PaddingValues(16.dp),+            verticalArrangement = Arrangement.spacedBy(8.dp),+        ) {+            item {+                if (required) Text("Add your details to start shopping.", style = MaterialTheme.typography.titleMedium)+                Text("Encrypted on this device. Checkout uses these details and sends them to a merchant only when you create or update a session.",+                    style = MaterialTheme.typography.bodySmall)+            }+            item {+                ProfileField("First name", draft.firstName) { draft = draft.copy(firstName = it) }+                ProfileField("Last name", draft.lastName) { draft = draft.copy(lastName = it) }+                ProfileField("Email", draft.email, KeyboardType.Email) { draft = draft.copy(email = it) }+                ProfileField("Phone (international, e.g. +14155550123)", draft.phone, KeyboardType.Phone) { draft = draft.copy(phone = it) }+            }+            item {+                Text("Delivery address (optional)", style = MaterialTheme.typography.titleSmall)+                Text("Needed when a merchant ships your order.", style = MaterialTheme.typography.bodySmall)+                ProfileField("Street address", draft.street) { draft = draft.copy(street = it) }+                ProfileField("Apartment / additional address", draft.extendedAddress) { draft = draft.copy(extendedAddress = it) }+                ProfileField("City", draft.city) { draft = draft.copy(city = it) }+                ProfileField("State / province", draft.region) { draft = draft.copy(region = it) }+                ProfileField("Country (two-letter code)", draft.country) { draft = draft.copy(country = it.uppercase()) }+                ProfileField("Postal code", draft.postalCode) { draft = draft.copy(postalCode = it) }+            }+            item {+                if (error != null && (draft != ShopProfile() || saved != null)) Text(error, color = MaterialTheme.colorScheme.error)+                Button(+                    modifier = Modifier.fillMaxWidth(),+                    enabled = error == null && draft != saved,+                    onClick = {+                        viewModel.saveProfile(draft)+                        if (!required) messenger.show("Profile saved")+                    },+                ) { Text(if (required) "Continue" else "Save") }+            }+        }+    }+}++@Composable+private fun ProfileField(label: String, value: String, keyboard: KeyboardType = KeyboardType.Text, onChange: (String) -> Unit) {+    OutlinedTextField(value = value, onValueChange = onChange, label = { Text(label) },+        modifier = Modifier.fillMaxWidth(), singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = keyboard))+}
shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt b/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.ktindex cbce58e336..4a7763c679 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt@@ -7,6 +7,7 @@ import androidx.compose.runtime.rememberCoroutineScope import kotlinx.coroutines.launch import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.ui.IconPerson import com.vayunmathur.library.ui.IconReceipt import com.vayunmathur.library.ui.IconSearch import com.vayunmathur.library.ui.IconStore@@ -25,7 +26,7 @@ fun ShopTabs(viewModel: ShopViewModel, onProductClick: (String, String, String)         viewModel.loadOrders(context)     }     val scope = rememberCoroutineScope()-    val pagerState = rememberPagerState(initialPage = 0, pageCount = { 4 })+    val pagerState = rememberPagerState(initialPage = 0, pageCount = { 5 })     val tabs = listOf(         PagerTab(stringResource(R.string.search), { IconSearch() }) {             SearchScreen(viewModel, onProductClick)@@ -42,6 +43,9 @@ fun ShopTabs(viewModel: ShopViewModel, onProductClick: (String, String, String)         PagerTab(stringResource(R.string.orders), { IconReceipt() }) {             OrdersScreen(viewModel)         },+        PagerTab("Profile", { IconPerson() }) {+            ProfileScreen(viewModel, required = false)+        },     )     TabbedPagerScaffold(tabs = tabs, pagerState = pagerState, tabStyle = TabStyle.BottomNav) }
shop/src/test/java/com/vayunmathur/shop/domain/ProfileCheckoutTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/domain/ProfileCheckoutTest.kt b/shop/src/test/java/com/vayunmathur/shop/domain/ProfileCheckoutTest.ktnew file mode 100644index 0000000000..6d7cc67acf--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/domain/ProfileCheckoutTest.kt@@ -0,0 +1,56 @@+package com.vayunmathur.shop.domain++import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.CheckoutReview+import com.vayunmathur.shop.data.NativeCheckoutState+import com.vayunmathur.shop.data.ShopProfile+import com.vayunmathur.shop.data.UcpMessage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class ProfileCheckoutTest {+    private val contact = ShopProfile(firstName = "Ada", lastName = "Lovelace", email = "[email protected]", phone = "+14155550123")+    private val withAddress = contact.copy(street = "1 Main St", city = "Austin", region = "TX", country = "US", postalCode = "78701")+    private val noShipping = NativeCheckoutFixtures.checkout(review = CheckoutReview())++    @Test fun requiredFieldsGateProfile() {+        assertNotNull(ShopProfile().validationError())+        assertNotNull(contact.copy(phone = "").validationError())+        assertNotNull(contact.copy(phone = "4155550123").validationError())+        assertNotNull(contact.copy(street = "1 Main St").validationError())+        assertNull(contact.validationError())+        assertNull(withAddress.validationError())+        assertFalse(withAddress.toString().contains("Ada"))+    }++    @Test fun createNeverCarriesAddress() {+        val inputs = ProfileCheckout.inputs(withAddress, NativeCheckoutState("generic", "shop.example"))+        assertEquals("Ada", inputs.firstName)+        assertFalse(inputs.hasAddress)+        assertFalse(inputs.shippingRequested)+    }++    @Test fun deliveryAddressRequiredSendsSavedAddress() {+        val checkout = noShipping.copy(messages = listOf(UcpMessage("error", "Add an address", null, "delivery_address_required", "recoverable")))+        val state = NativeCheckoutState("generic", "shop.example", checkout = checkout, inputs = CheckoutInputs(options = mapOf("m/g" to "express")))+        val inputs = ProfileCheckout.inputs(withAddress, state)+        assertTrue(ProfileCheckout.needsDeliveryAddress(checkout))+        assertTrue(inputs.shippingRequested)+        assertEquals("1 Main St", inputs.street)+        assertEquals(mapOf("m/g" to "express"), inputs.options)+        assertNull(inputs.validationError())+    }++    @Test fun addressWithheldWhenMerchantDoesNotShipOrProfileHasNone() {+        assertFalse(ProfileCheckout.inputs(withAddress, NativeCheckoutState("generic", "shop.example", checkout = noShipping)).hasAddress)+        val shipping = NativeCheckoutState("generic", "shop.example", checkout = NativeCheckoutFixtures.checkout())+        assertTrue(ProfileCheckout.needsDeliveryAddress(shipping.checkout))+        val inputs = ProfileCheckout.inputs(contact, shipping)+        assertFalse(inputs.hasAddress)+        assertFalse(inputs.shippingRequested)+    }+}