Modern Apps git

← Modern-Apps.git

shop: one-tap checkout straight into the merchant's embedded checkout; drop the review screen

Commit
6fae9787e19d3e7417bf687c332e13cf6b1414fb
Author
Vayun Mathur <[email protected]>
When
2026-11-01 21:05 UTC (1 month ago)
Parents
0e33bee

Diff

metadata_data/photos/shop/phone/2.png
diff --git a/metadata_data/photos/shop/phone/2.png b/metadata_data/photos/shop/phone/2.pngindex e8b0e37014..5bd3b4b7e9 100644Binary files a/metadata_data/photos/shop/phone/2.png and b/metadata_data/photos/shop/phone/2.png differ
metadata_data/photos/shop/phone/3.png
diff --git a/metadata_data/photos/shop/phone/3.png b/metadata_data/photos/shop/phone/3.pngindex 840d3a6cf1..f7323d2bbb 100644Binary files a/metadata_data/photos/shop/phone/3.png and b/metadata_data/photos/shop/phone/3.png differ
metadata_data/photos/shop/phone/4.png
diff --git a/metadata_data/photos/shop/phone/4.png b/metadata_data/photos/shop/phone/4.pngdeleted file mode 100644index f7323d2bbb..0000000000Binary files a/metadata_data/photos/shop/phone/4.png and /dev/null differ
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 389b76223a..b192e4b6ff 100644--- a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt+++ b/shop/src/main/java/com/vayunmathur/shop/Navigation.kt@@ -7,7 +7,6 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.shop.platform.ShopViewModel import com.vayunmathur.shop.ui.CartScreen-import com.vayunmathur.shop.ui.CheckoutScreen import com.vayunmathur.shop.ui.EmbeddedCheckoutScreen import com.vayunmathur.shop.ui.OrdersScreen import com.vayunmathur.shop.ui.ProductScreen@@ -36,7 +35,7 @@ fun Navigation(viewModel: ShopViewModel) {                 onProductClick = { variantId, platformId, shopDomain ->                     backStack.add(Route.ProductDetail(variantId, platformId, shopDomain))                 },-                onCheckout = { backStack.add(Route.Checkout) },+                onPayInApp = { backStack.add(Route.EmbeddedCheckout) },             )         }         entry<Route.ProductDetail> { route ->@@ -46,18 +45,11 @@ fun Navigation(viewModel: ShopViewModel) {                 platformId = route.platformId,                 shopDomain = route.shopDomain,                 onBack = { backStack.pop() },-                onCheckout = { backStack.add(Route.Checkout) },+                onPayInApp = { backStack.add(Route.EmbeddedCheckout) },             )         }         entry<Route.Cart> {-            CartScreen(viewModel, onCheckout = { backStack.add(Route.Checkout) })-        }-        entry<Route.Checkout> {-            CheckoutScreen(-                viewModel = viewModel,-                onBack = { backStack.pop() },-                onPayInApp = { backStack.add(Route.EmbeddedCheckout) },-            )+            CartScreen(viewModel, onPayInApp = { backStack.add(Route.EmbeddedCheckout) })         }         entry<Route.EmbeddedCheckout> {             EmbeddedCheckoutScreen(viewModel = viewModel, onClose = {
shop/src/main/java/com/vayunmathur/shop/Route.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/Route.kt b/shop/src/main/java/com/vayunmathur/shop/Route.ktindex 2f4053f6e5..53ad266097 100644--- a/shop/src/main/java/com/vayunmathur/shop/Route.kt+++ b/shop/src/main/java/com/vayunmathur/shop/Route.kt@@ -18,9 +18,6 @@ sealed interface Route : NavKey {     @Serializable     data object Cart : Route -    @Serializable-    data object Checkout : Route-     @Serializable     data object Orders : Route 
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.ktindex 58635817c9..b4e5b87cf2 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/ProfileCheckout.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/ProfileCheckout.kt@@ -3,15 +3,9 @@ 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" }-        )-     /** Every write carries the full saved profile, including the delivery address when one is saved. */     fun inputs(profile: ShopProfile, state: NativeCheckoutState): CheckoutInputs {         val inputs = profile.checkoutInputs()
shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt b/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.ktindex ca8296fdff..93dde907e0 100644--- a/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt+++ b/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt@@ -215,7 +215,3 @@ internal data class BackendRawResponse( )  internal fun String.encode(): String = URLEncoder.encode(this, "UTF-8")--/** Split cart lines by merchant: one server checkout session per shop. */-internal fun splitByShop(lines: List<CartLine>): Map<Pair<String, String>, List<CartLine>> =-    lines.groupBy { Pair(it.platformId, it.shopDomain) }
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 3548b05101..b384b768b3 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -20,7 +20,6 @@ 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.EmbeddedCheckout@@ -31,7 +30,6 @@ import com.vayunmathur.shop.domain.ProfileCheckout import com.vayunmathur.shop.network.ShopBackend import com.vayunmathur.shop.network.ShopBackendException import com.vayunmathur.shop.network.ShopHttpBackend-import com.vayunmathur.shop.network.splitByShop import kotlinx.coroutines.launch  /** Session catalog state plus persisted cart and pending checkout history. */@@ -63,26 +61,18 @@ class ShopViewModel(         private set     var cart by mutableStateOf<List<CartLine>>(emptyList())         private set-    var placingCheckout by mutableStateOf(false)-        private set-    var checkoutError by mutableStateOf<String?>(null)-        private set-    var browserCheckouts by mutableStateOf<List<UcpCheckout>>(emptyList())+    /** Store whose one-tap checkout is being prepared, as (platformId, shopDomain). */+    var startingCheckout by mutableStateOf<Pair<String, String>?>(null)         private set     var orders by mutableStateOf<List<PlacedOrder>>(emptyList())         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 }-    })+    private val nativeCheckout = NativeCheckoutCoordinator()      fun observeProfile(context: Context) {         if (profileRepository != null) return@@ -99,25 +89,40 @@ class ShopViewModel(     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)-    }--    fun refreshCheckoutExpiry() { nativeCheckout.refreshExpiry() }--    fun reconcileCheckout(platformId: String, shop: String) {-        viewModelScope.launch { nativeCheckout.reconcile(platformId, shop) }-    }--    fun prepareMerchantCheckout(platformId: String, shop: String, context: Context) {-        if (placingCheckout) return+    /**+     * One tap: a fresh merchant session from the saved profile, then the merchant's checkout+     * embedded in the app. A rejected create still carries the merchant's handoff URL.+     */+    fun checkoutStore(+        platformId: String,+        shop: String,+        context: Context,+        dark: Boolean,+        onReady: () -> Unit,+        onError: (String) -> Unit,+    ) {+        if (startingCheckout != null) return         val lines = cart.filter { it.platformId == platformId && it.shopDomain == shop }.toList()+        if (lines.isEmpty()) return+        startingCheckout = platformId to shop         val sink = PendingCheckoutSink { OrderStore.add(context, it) }         viewModelScope.launch {-            AppInit.awaitReady()-            submitFromProfile(platformId, shop, lines, sink)-            nativeCheckout.cartChanged(cart)-            orders = OrderStore.getAll(context)+            try {+                AppInit.awaitReady()+                // A handoff URL may be single-use, so every tap starts a new session.+                nativeCheckout.forget(platformId, shop)+                submitFromProfile(platformId, shop, lines, sink)+                val state = nativeCheckout.snapshot.firstOrNull { it.platformId == platformId && it.shopDomain == shop }+                val url = (state?.checkout?.continueUrl?.let(MerchantUrls::httpsUrl)) ?: state?.handoffUrl+                if (url != null && openEmbeddedCheckout(platformId, shop, url, dark)) {+                    onReady()+                } else {+                    onError(state?.message ?: "This store didn't return a checkout. Please try again.")+                }+                orders = OrderStore.getAll(context)+            } finally {+                startingCheckout = null+            }         }     } @@ -240,7 +245,6 @@ class ShopViewModel(                 storeName = variant.storeName.ifBlank { product.storeName },             )         }-        browserCheckouts = emptyList()         nativeCheckout.cartChanged(cart)         ShopCartStore.save(context, cart)     }@@ -249,32 +253,10 @@ class ShopViewModel(         cart = cart.filterNot {             it.variantId == line.variantId && it.platformId == line.platformId && it.shopDomain == line.shopDomain         }-        browserCheckouts = emptyList()         nativeCheckout.cartChanged(cart)         ShopCartStore.save(context, cart)     } -    /** Explicit session preparation only. Cart lines survive every pending session or failure. */-    fun placeCheckout(context: Context) {-        if (placingCheckout || cart.isEmpty()) return-        val snapshot = cart.toList()-        placingCheckout = true-        checkoutError = null-        viewModelScope.launch {-            try {-                AppInit.awaitReady()-                for ((key, lines) in splitByShop(snapshot)) {-                    nativeCheckout.submit(key.first, key.second, lines, PendingCheckoutSink { OrderStore.add(context, it) })-                    nativeCheckout.cartChanged(cart)-                }-                orders = OrderStore.getAll(context)-            } finally {-                placingCheckout = false-            }-        }-    }--    fun dismissCheckoutError() { checkoutError = null }     fun dismissSearchError() { searchError = null }      fun openEmbeddedCheckout(platformId: String, shop: String, continueUrl: String, dark: Boolean): Boolean {
shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.ktindex 2bee0f5304..0dc98e4895 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.kt@@ -4,6 +4,7 @@ import android.content.Context import android.net.Uri import androidx.browser.customtabs.CustomTabColorSchemeParams import androidx.browser.customtabs.CustomTabsIntent+import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -19,7 +20,6 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale@@ -47,23 +47,20 @@ import com.vayunmathur.shop.platform.ShopViewModel @Composable fun CartScreen(     viewModel: ShopViewModel,-    onCheckout: () -> Unit,+    onPayInApp: () -> Unit, ) {     val messenger = rememberMessenger()-    LaunchedEffect(viewModel.checkoutError) {-        viewModel.checkoutError?.let { error ->-            messenger.show(error)-            viewModel.dismissCheckoutError()-        }-    }     // Persistence context hoisted once: rows stay stateless and context-free.     val context = androidx.compose.ui.platform.LocalContext.current+    val dark = isSystemInDarkTheme()     AppScaffold(topBar = {}) { padding ->         CartContent(             cart = viewModel.cart,-            placing = viewModel.placingCheckout,+            startingStore = viewModel.startingCheckout,             onRemove = { viewModel.removeLine(it, context) },-            onCheckout = onCheckout,+            onCheckoutStore = { platformId, shop ->+                viewModel.checkoutStore(platformId, shop, context, dark, onReady = onPayInApp, onError = messenger::show)+            },             modifier = Modifier.fillMaxSize().padding(padding),         )     }@@ -77,9 +74,9 @@ fun CartScreen( internal fun CartContent(     cart: List<CartLine>,     modifier: Modifier = Modifier,-    placing: Boolean = false,+    startingStore: Pair<String, String>? = null,     onRemove: (CartLine) -> Unit = {},-    onCheckout: () -> Unit = {},+    onCheckoutStore: (platformId: String, shopDomain: String) -> Unit = { _, _ -> }, ) {     if (cart.isEmpty()) {         Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {@@ -105,9 +102,9 @@ internal fun CartContent(         ) {             // One section per store: each becomes its own checkout (UCP checkouts             // are single-merchant), so the grouping is load-bearing, not cosmetic.-            val byShop = cart.groupBy { it.shopDomain.ifBlank { "Unknown store" } }-            byShop.forEach { (shop, lines) ->-                item(key = "header-$shop") {+            val byShop = cart.groupBy { it.platformId to it.shopDomain }+            byShop.forEach { (store, lines) ->+                item(key = "header-${store.first}|${store.second}") {                     Text(                         lines.first().displayName.ifBlank { "Unknown store" },                         style = MaterialTheme.typography.titleSmall,@@ -117,13 +114,19 @@ internal fun CartContent(                 items(lines, key = { "${it.platformId}|${it.shopDomain}|${it.variantId}" }) { line ->                     CartRow(line = line, onRemove = { onRemove(line) })                 }+                item(key = "checkout-${store.first}|${store.second}") {+                    Button(+                        onClick = { onCheckoutStore(store.first, store.second) },+                        enabled = startingStore == null,+                        modifier = Modifier.fillMaxWidth(),+                    ) {+                        if (startingStore == store) CircularProgressIndicator(Modifier.size(20.dp))+                        else Text(if (byShop.size > 1) "Checkout with ${lines.first().displayName}" else stringResource(R.string.checkout))+                    }+                }             }         }-        CartFooter(-            cart = cart,-            placing = placing,-            onCheckout = onCheckout,-        )+        CartFooter(cart = cart)     } } @@ -164,7 +167,7 @@ private fun CartRow(line: CartLine, onRemove: () -> Unit) { }  @Composable-private fun CartFooter(cart: List<CartLine>, placing: Boolean, onCheckout: () -> Unit) {+private fun CartFooter(cart: List<CartLine>) {     val totals = cart.groupBy { it.unitPrice.currency }.map { (currency, lines) ->         com.vayunmathur.shop.data.Money(             lines.sumOf { it.unitPrice.amount * it.quantity }, currency,@@ -181,14 +184,6 @@ private fun CartFooter(cart: List<CartLine>, placing: Boolean, onCheckout: () ->                 Text(MoneyFormat.format(total), style = MaterialTheme.typography.titleLarge)             }         }-        Spacer(Modifier.width(12.dp))-        Button(onClick = onCheckout, enabled = !placing) {-            if (placing) {-                CircularProgressIndicator()-            } else {-                Text(stringResource(R.string.checkout))-            }-        }     } } 
shop/src/main/java/com/vayunmathur/shop/ui/CheckoutReviewContent.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutReviewContent.kt b/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutReviewContent.ktdeleted file mode 100644index 9c35d68ca6..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutReviewContent.kt+++ /dev/null@@ -1,68 +0,0 @@-package com.vayunmathur.shop.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.FilterChip-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton-import com.vayunmathur.shop.data.CheckoutInputs-import com.vayunmathur.shop.data.NativeCheckoutState-import com.vayunmathur.shop.domain.MoneyFormat--/** Pure session presentation shared by the live checkout and deterministic screenshot fixtures. */-@Composable-internal fun CheckoutReviewContent(-    state: NativeCheckoutState,-    editable: Boolean,-    onInputsChange: (CheckoutInputs) -> Unit,-    onOpenUrl: (String) -> Unit,-    onRefresh: () -> Unit,-    modifier: Modifier = Modifier,-) {-    val checkout = state.checkout ?: return-    Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) {-        state.submittedInputs?.let { buyer ->-            Text("Submitted buyer", style = MaterialTheme.typography.titleSmall)-            listOf("${buyer.firstName} ${buyer.lastName}".trim(), buyer.email, buyer.phone)-                .filter { it.isNotBlank() }.forEach { Text(it, style = MaterialTheme.typography.bodySmall) }-            if (buyer.hasAddress) {-                Text(listOf(buyer.street, buyer.extendedAddress).filter { it.isNotBlank() }.joinToString(", "), style = MaterialTheme.typography.bodySmall)-                Text(listOf(buyer.city, buyer.region, buyer.postalCode, buyer.country).filter { it.isNotBlank() }.joinToString(", "), style = MaterialTheme.typography.bodySmall)-            }-        }-        Text("Session: ${checkout.status} (${checkout.version})", style = MaterialTheme.typography.labelLarge)-        Text("Currency: ${checkout.currency}")-        checkout.totalEntries.forEach { Text("${it.label}: ${MoneyFormat.format(it.money)}") }-        checkout.messages.forEach { message ->-            Text(listOfNotNull(message.type.takeIf { it.isNotBlank() }, message.path, message.code, message.text).joinToString(": "))-        }-        Text(checkout.expiresAt?.let { "Expires: $it" } ?: "Expires 6 hours after creation, unless the merchant changes it.", style = MaterialTheme.typography.bodySmall)-        if (state.inputs != state.submittedInputs) Text("Inputs have changed. Update the session to obtain current merchant totals and shipping choices.")-        checkout.review.shipping.forEach { method ->-            method.groups.forEach { group ->-                Text("Shipping options", style = MaterialTheme.typography.titleSmall)-                group.options.forEach { option ->-                    val selectionKey = "${method.id}/${group.id}"-                    FilterChip(-                        selected = (state.inputs.options[selectionKey] ?: group.selectedOptionId) == option.id,-                        enabled = editable,-                        onClick = { onInputsChange(state.inputs.copy(options = state.inputs.options + (selectionKey to option.id))) },-                        label = { Text(option.title) },-                    )-                    if (option.description.isNotBlank()) Text(option.description, style = MaterialTheme.typography.bodySmall)-                    option.totals.forEach { Text("${it.label}: ${MoneyFormat.format(it.money)}", style = MaterialTheme.typography.bodySmall) }-                }-            }-        }-        if (checkout.status == "ready_for_complete") Text("The merchant reports payment readiness. Pay on its website to place the order.", style = MaterialTheme.typography.bodySmall)-        Text("Pending session only. Check purchase and payment status on the merchant website.", style = MaterialTheme.typography.bodySmall)-        checkout.review.links.forEach { link ->-            TextButton(onClick = { onOpenUrl(link.url) }) { Text(link.title.ifBlank { link.type }) }-        }-        TextButton(enabled = !state.busy, onClick = onRefresh) { Text("Refresh session (read only)") }-    }-}
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.ktdeleted file mode 100644index bd0e51d8dc..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt+++ /dev/null@@ -1,97 +0,0 @@-package com.vayunmathur.shop.ui--import androidx.compose.foundation.isSystemInDarkTheme-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.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.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.MaterialTheme-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.shop.R-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--/** Native session review only. Payment and purchase confirmation remain on the merchant website. */-@Composable-fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit, onPayInApp: () -> Unit) {-    val context = LocalContext.current-    val dark = isSystemInDarkTheme()-    LaunchedEffect(viewModel) {-        while (isActive) { viewModel.refreshCheckoutExpiry(); delay(1000) }-    }-    AppScaffold(title = stringResource(R.string.checkout), onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior()) { padding ->-        LazyColumn(-            modifier = Modifier.fillMaxSize().padding(padding),-            contentPadding = PaddingValues(16.dp),-            verticalArrangement = Arrangement.spacedBy(16.dp),-        ) {-            item {-                Text("Review a merchant checkout session. No order is placed or payment collected here.")-                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 }-                    ?: NativeCheckoutState(key.first, key.second)-                item(key = "merchant-${key.first}-${key.second}") {-                    DetailSection(lines.first().displayName.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)-                        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,-                                editable = editable,-                                onInputsChange = { viewModel.editCheckoutInputs(key.first, key.second, it) },-                                onOpenUrl = { openContinueUrl(context, it) },-                                onRefresh = { viewModel.reconcileCheckout(key.first, key.second) },-                            )-                        }-                        state.message?.let { Text(it) }-                        if (state.phase == CheckoutPhase.Expired) Text("Session expired. Native updates are disabled.")-                        Button(-                            modifier = Modifier.fillMaxWidth(),-                            enabled = editable && profileInputs != null && (checkout == null || profileInputs != state.submittedInputs),-                            onClick = { viewModel.prepareMerchantCheckout(key.first, key.second, context) },-                        ) {-                            if (state.busy) CircularProgressIndicator()-                            else Text(if (checkout == null) "Create review session" else "Update review session")-                        }-                        val checkoutUrl = (checkout?.continueUrl ?: state.handoffUrl)?.let(MerchantUrls::httpsUrl)-                        if (checkoutUrl != null) {-                            Button(-                                modifier = Modifier.fillMaxWidth(),-                                onClick = {-                                    if (viewModel.openEmbeddedCheckout(key.first, key.second, checkoutUrl, dark)) onPayInApp()-                                },-                            ) { Text("Pay in app") }-                        }-                    }-                }-            }-            if (viewModel.cart.isEmpty()) item { Text("Your cart is empty.") }-        }-    }-}
shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.ktindex 491e908fe2..3a398be163 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt@@ -1,5 +1,6 @@ package com.vayunmathur.shop.ui +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -10,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow@@ -61,9 +63,10 @@ fun ProductScreen(     platformId: String,     shopDomain: String,     onBack: () -> Unit,-    onCheckout: () -> Unit,+    onPayInApp: () -> Unit, ) {     val backend: ShopBackend = ShopHttpBackend+    val dark = isSystemInDarkTheme()     val context = LocalContext.current     val messenger = rememberMessenger()     var product by remember(variantId, platformId, shopDomain) {@@ -143,13 +146,14 @@ fun ProductScreen(      val verified = !loading && verifiedKey == refreshKey     val canAdd = verified && product?.checkoutEligible == true && selected?.available == true-    val addToCart: () -> Unit = {+    /** Returns the (platformId, shopDomain) the line was added under, or null. */+    val addToCart: () -> Pair<String, String>? = add@{         val current = product         val liveVariant = current?.variants?.firstOrNull { it.id == selectedVariant }-        if (canAdd && current != null && liveVariant != null) {-            val cartProduct = current.copy(shopDomain = liveVariant.shopDomain.takeIf { it.isNotBlank() } ?: current.shopDomain)-            viewModel.addToCart(cartProduct, selectedVariant, quantity, context)-        }+        if (!canAdd || current == null || liveVariant == null) return@add null+        val cartProduct = current.copy(shopDomain = liveVariant.shopDomain.takeIf { it.isNotBlank() } ?: current.shopDomain)+        viewModel.addToCart(cartProduct, selectedVariant, quantity, context)+        cartProduct.platformId to cartProduct.shopDomain     }     AppScaffold(         title = product?.title ?: stringResource(R.string.app_name),@@ -181,9 +185,14 @@ fun ProductScreen(                 onQuantityChange = { quantity = it },                 onRetry = { retry += 1 },                 onAddToCart = { if (canAdd) { addToCart(); messenger.show("Added to cart") } },-                onBuyNow = { if (canAdd) { addToCart(); onCheckout() } },+                onBuyNow = {+                    addToCart()?.let { (store, shop) ->+                        viewModel.checkoutStore(store, shop, context, dark, onReady = onPayInApp, onError = messenger::show)+                    }+                },                 onOpenUrl = { url -> MerchantUrls.httpsUrl(url)?.let { openContinueUrl(context, it) } },                 modifier = Modifier.fillMaxSize().padding(padding),+                startingCheckout = viewModel.startingCheckout != null,             )         }     }@@ -205,6 +214,7 @@ internal fun ProductDetailContent(     onBuyNow: () -> Unit,     onOpenUrl: (String) -> Unit,     modifier: Modifier = Modifier,+    startingCheckout: Boolean = false, ) {     val variant = product.variants.firstOrNull { it.id == selectedVariantId }     val storeDomain = variant?.shopDomain?.takeIf { it.isNotBlank() } ?: product.shopDomain@@ -277,8 +287,9 @@ internal fun ProductDetailContent(                     Button(onClick = onAddToCart, enabled = canAdd, modifier = Modifier.weight(1f)) {                         Text(stringResource(R.string.add_to_cart))                     }-                    Button(onClick = onBuyNow, enabled = canAdd, modifier = Modifier.weight(1f)) {-                        Text(stringResource(R.string.buy_now))+                    Button(onClick = onBuyNow, enabled = canAdd && !startingCheckout, modifier = Modifier.weight(1f)) {+                        if (startingCheckout) CircularProgressIndicator(Modifier.size(20.dp))+                        else Text(stringResource(R.string.buy_now))                     }                 }                 if ((!product.checkoutEligible || !verified && !loading) && MerchantUrls.httpsUrl(product.url) != null) {
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 e653a6c21f..ea7a737cb1 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt@@ -16,7 +16,7 @@ import com.vayunmathur.shop.R import com.vayunmathur.shop.platform.ShopViewModel  @Composable-fun ShopTabs(viewModel: ShopViewModel, onProductClick: (String, String, String) -> Unit, onCheckout: () -> Unit) {+fun ShopTabs(viewModel: ShopViewModel, onProductClick: (String, String, String) -> Unit, onPayInApp: () -> Unit) {     val context = LocalContext.current     LaunchedEffect(Unit) {         viewModel.loadCart(context)@@ -32,7 +32,7 @@ fun ShopTabs(viewModel: ShopViewModel, onProductClick: (String, String, String)             SearchScreen(viewModel, onProductClick)         },         PagerTab(stringResource(R.string.cart), { IconShoppingCart() }) {-            CartScreen(viewModel, onCheckout = onCheckout)+            CartScreen(viewModel, onPayInApp = onPayInApp)         },         PagerTab(stringResource(R.string.orders), { IconReceipt() }) {             OrdersScreen(viewModel)
shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.kt
diff --git a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.kt b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.ktdeleted file mode 100644index 669c2a9a51..0000000000--- a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.kt+++ /dev/null@@ -1,74 +0,0 @@-package com.vayunmathur.shop.ui--import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.tooling.preview.Preview-import androidx.compose.ui.unit.dp-import com.android.tools.screenshot.PreviewTest-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.shop.data.CheckoutInputs-import com.vayunmathur.shop.data.CheckoutLegalLink-import com.vayunmathur.shop.data.CheckoutReview-import com.vayunmathur.shop.data.CheckoutShippingGroup-import com.vayunmathur.shop.data.CheckoutShippingMethod-import com.vayunmathur.shop.data.CheckoutShippingOption-import com.vayunmathur.shop.data.Money-import com.vayunmathur.shop.data.NativeCheckoutState-import com.vayunmathur.shop.data.UcpCheckout-import com.vayunmathur.shop.data.UcpTotalEntry-import com.vayunmathur.shop.data.UcpTotals--/** Synthetic, immutable review data. No ViewModel, initialization, gateway or network is used. */-class CheckoutMetadataPreviews {-    private val buyer = CheckoutInputs(-        firstName = "Alex", lastName = "Example", email = "[email protected]", phone = "+12025550123",-        street = "123 Example Street", city = "San Francisco", region = "CA", country = "US", postalCode = "94107",-        options = mapOf("fixture-shipping/fixture-group" to "fixture-standard"),-    )-    private val totals = listOf(-        UcpTotalEntry("subtotal", "Items", Money(12999, "USD")),-        UcpTotalEntry("fulfillment", "Shipping", Money(500, "USD")),-        UcpTotalEntry("tax", "Tax", Money(1080, "USD")),-        UcpTotalEntry("total", "Total", Money(14579, "USD")),-    )-    private val state = NativeCheckoutState(-        platformId = "generic", shopDomain = "trail.example", inputs = buyer, submittedInputs = buyer,-        checkout = UcpCheckout(-            checkoutId = "fixture-checkout", status = "ready_for_complete", currency = "USD",-            totals = UcpTotals(subtotal = totals.first().money, shipping = totals[1].money, tax = totals[2].money, total = totals.last().money),-            totalEntries = totals, expiresAt = "2026-10-27T00:00:00Z", continueUrl = "https://trail.example/checkout",-            review = CheckoutReview(-                shipping = listOf(CheckoutShippingMethod("fixture-shipping", listOf(-                    CheckoutShippingGroup("fixture-group", "fixture-standard", listOf(-                        CheckoutShippingOption("fixture-standard", "Standard shipping", "Arrives in 3-5 business days", listOf(totals[1])),-                    )),-                ))),-                links = listOf(CheckoutLegalLink("terms_of_service", "Merchant terms", "https://trail.example/terms")),-            ),-        ),-    )--    @PreviewTest-    @Preview(name = "3-checkout", group = "phone", widthDp = 360, heightDp = 780)-    @Composable-    fun Preview3Checkout() {-        DynamicTheme(darkTheme = false) {-            AppScaffold(title = "Checkout review", scrollBehavior = appBarScrollBehavior()) { padding ->-                CheckoutReviewContent(-                    state = state,-                    editable = true,-                    onInputsChange = {},-                    onOpenUrl = {},-                    onRefresh = {},-                    modifier = Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(16.dp),-                )-            }-        }-    }-}
shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt
diff --git a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.ktindex bfd49a2c5f..c6d28153db 100644--- a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt+++ b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt@@ -48,9 +48,9 @@ class ProductMetadataPreviews {     )      @PreviewTest-    @Preview(name = "4-product", group = "phone", widthDp = 360, heightDp = 780)+    @Preview(name = "3-product", group = "phone", widthDp = 360, heightDp = 780)     @Composable-    fun Preview4Product() {+    fun Preview3Product() {         DynamicTheme(darkTheme = false) {             AppScaffold(title = product.title, scrollBehavior = appBarScrollBehavior()) { padding ->                 ProductDetailContent(
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.ktindex ccefb22ec2..f915030770 100644--- a/shop/src/test/java/com/vayunmathur/shop/domain/ProfileCheckoutTest.kt+++ b/shop/src/test/java/com/vayunmathur/shop/domain/ProfileCheckoutTest.kt@@ -41,7 +41,6 @@ class ProfileCheckoutTest {         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)@@ -50,7 +49,6 @@ class ProfileCheckoutTest {      @Test fun noAddressSentWhenProfileHasNone() {         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)
shop/src/test/java/com/vayunmathur/shop/network/ShopBackendTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/network/ShopBackendTest.kt b/shop/src/test/java/com/vayunmathur/shop/network/ShopBackendTest.ktindex b012eb4d63..ff6c42df2f 100644--- a/shop/src/test/java/com/vayunmathur/shop/network/ShopBackendTest.kt+++ b/shop/src/test/java/com/vayunmathur/shop/network/ShopBackendTest.kt@@ -140,16 +140,4 @@ class ShopBackendTest {         assertEquals(60_000L, limited?.retryAfterMs)         return@runBlocking     }--    @Test fun splitByShopGroupsPerMerchant() {-        val lines = listOf(-            CartLine(variantId = "a", platformId = "shopify", shopDomain = "one.example", quantity = 1),-            CartLine(variantId = "b", platformId = "shopify", shopDomain = "one.example", quantity = 2),-            CartLine(variantId = "c", platformId = "generic", shopDomain = "two.example", quantity = 1),-        )-        val grouped = splitByShop(lines)-        assertEquals(2, grouped.size)-        assertEquals(2, grouped[Pair("shopify", "one.example")]?.size)-        assertEquals(1, grouped[Pair("generic", "two.example")]?.size)-    } }