shop: a checkout session prepared from a stale cart is never opened
- Commit
a69a3d9714f8c7eca2dfeaae7b2d96e3f28707a6- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 09:26 UTC (5 days ago)
- Parents
4801c74
cartChanged could only flag a session whose checkout was already set, but during create/reconcile the checkout is null until the write returns — a mid-flight cart change was invisible to it. Remove stays enabled during preparation: cart v1 120.00 + v2 30.00 = 150.00, tap Checkout, remove v2 in flight, and the returned 150.00 session opened for payment anyway. Adding a line mid-create was worse: the completion computed itemCount/total from the current cart while the order record kept the pending lines, so an order could count an item never in the paid session. ShopViewModel now compares the session's submitted variant/quantity projection against the current cart after a fresh submit and after restored-session reconcile; on mismatch the session is not opened and the user is told the cart changed during preparation, the stale session and its in-flight intent record are discarded (so the next tap creates fresh instead of restoring-and-blocking), and the pending order record is preserved. Regression test with a gated fake transport removes the 30.00 line during create and asserts no checkout opens (failed pre-fix). Cart math, order merge and variant routing were audited and cleared. Verified: :shop:testDevUnitTest 160 tests pass; lint errors are pre-existing on untouched files.
Diff
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 33c87cffc0..762cbb91a3 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -145,6 +145,15 @@ class ShopViewModel( nativeCheckout.reconcile(platformId, shop) val restored = nativeCheckout.snapshot .firstOrNull { it.platformId == platformId && it.shopDomain == shop }+ if (sessionCartChanged(restored, platformId, shop)) {+ discardStaleSession(context, platformId, shop)+ onError(+ "The cart changed while this checkout was being prepared. " ++ "Review your cart and try again.",+ )+ orders = OrderStore.getAll(context)+ return@launch+ } val restoredUrl = restored?.checkout?.continueUrl?.let(MerchantUrls::httpsUrl) ?: restored?.handoffUrl if (restoredUrl != null && openEmbeddedCheckout(platformId, shop, restoredUrl, dark)) {@@ -159,6 +168,15 @@ class ShopViewModel( nativeCheckout.forget(platformId, shop) submitFromProfile(platformId, shop, lines, sink) val state = nativeCheckout.snapshot.firstOrNull { it.platformId == platformId && it.shopDomain == shop }+ if (sessionCartChanged(state, platformId, shop)) {+ discardStaleSession(context, platformId, shop)+ onError(+ "The cart changed while this checkout was being prepared. " ++ "Review your cart and try again.",+ )+ orders = OrderStore.getAll(context)+ return@launch+ } val url = (state?.checkout?.continueUrl?.let(MerchantUrls::httpsUrl)) ?: state?.handoffUrl if (url != null && openEmbeddedCheckout(platformId, shop, url, dark)) { onReady()@@ -185,6 +203,35 @@ class ShopViewModel( nativeCheckout.submit(platformId, shop, lines, sink) } + /**+ * True when a created/restored session no longer represents the cart. The+ * cart stays editable while a create/reconcile is in flight, and the+ * coordinator only learns the session's lines once the write returns, so+ * a mid-flight change is invisible to it. Such a session must not open+ * for payment; the caller discards it (pending OrderStore record aside)+ * so the next tap re-creates a session from the current cart.+ */+ private fun sessionCartChanged(state: NativeCheckoutState?, platformId: String, shop: String): Boolean {+ if (state?.checkout == null || state.submittedLines.isEmpty()) return false+ val current = cart.filter { it.platformId == platformId && it.shopDomain == shop }+ return state.submittedLines.variantQuantities() != current.variantQuantities()+ }++ /** Variant/quantity projection: the only cart facts a merchant session represents. */+ private fun List<CartLine>.variantQuantities(): Map<String, Int> =+ groupBy { it.variantId }.mapValues { (_, group) -> group.sumOf { it.quantity } }++ /**+ * Drops a stale session and its in-flight record. The pending record in+ * OrderStore is untouched (cart lines are preserved through handoffs);+ * without this, the next tap would restore the same stale session and+ * block again instead of creating a fresh one.+ */+ private suspend fun discardStaleSession(context: Context, platformId: String, shop: String) {+ CheckoutIntentStore.clear(context, platformId, shop)+ nativeCheckout.forget(platformId, shop)+ }+ fun updateQuery(value: String) { query = value } fun clearScope() {
shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelCoverage2Test.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelCoverage2Test.kt b/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelCoverage2Test.ktindex 9614ad37fa..7ddf2e75c0 100644--- a/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelCoverage2Test.kt+++ b/shop/src/test/java/com/vayunmathur/shop/platform/ShopViewModelCoverage2Test.kt@@ -20,8 +20,10 @@ import com.vayunmathur.shop.network.ShopBackend import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue+import kotlinx.coroutines.CompletableDeferred import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows@@ -105,6 +107,47 @@ class ShopViewModelCoverage2Test { assertNull(vm.startingCheckout) } + @Test fun checkoutStore_cartChangedDuringCreateDoesNotOpenStaleSession() {+ // Isolate from any in-flight record a sibling test persisted.+ context.getSharedPreferences("shop_checkout_intent", Context.MODE_PRIVATE).edit().clear().commit()+ val createStarted = CompletableDeferred<Unit>()+ val createGate = CompletableDeferred<Unit>()+ com.vayunmathur.shop.network.ShopHttpBackend.request = { _, _, _ ->+ createStarted.complete(Unit)+ createGate.await()+ com.vayunmathur.shop.network.BackendRawResponse(200, """+ {"checkoutId":"chk-stale","status":"incomplete","currency":"USD",+ "totals":{"subtotal":{"amount":15000,"currency":"USD"},"total":{"amount":15000,"currency":"USD"}},+ "totalEntries":[],"continueUrl":"https://cool.example/checkout/stale","expiresAt":null,"messages":[],+ "version":"2026-08-25","review":{"shipping":[],"links":[],"browserOnlyReason":null,"availableShippingLineIds":[]},+ "submittedLines":[{"variantId":"v1","quantity":1},{"variantId":"v2","quantity":1}],"trackingToken":"tokstale"}+ """.trimIndent(), emptyMap(), null)+ }+ vm.addToCart(product(), "v1", 1, context)+ vm.addToCart(+ UcpProduct(id="p2", title="Trail Socks", platformId="shopify", shopDomain="cool.example",+ checkoutEligible=true, storeName="Cool Store", priceRange=Money(3000,"USD"),+ variants=listOf(ProductVariant("v2","D",Money(3000,"USD"),true,storeName="Cool Store",shopDomain="cool.example"))),+ "v2", 1, context,+ )+ assertEquals(listOf("v1", "v2"), vm.cart.map { it.variantId })+ var ready = false; var error: String? = null+ vm.checkoutStore("shopify","cool.example",context,dark=false,onReady={ ready=true },onError={ error=it })+ await { createStarted.isCompleted }+ // The Remove button stays enabled while the create is in flight: the+ // $30.00 socks leave the cart after the session's lines were captured.+ vm.removeLine(vm.cart.first { it.variantId == "v2" }, context)+ assertEquals(listOf("v1"), vm.cart.map { it.variantId })+ createGate.complete(Unit)+ await { (ready || error != null) && vm.startingCheckout == null }+ // The created session covers v1+v2 ($150.00); it no longer represents+ // the cart (v1 only, $120.00), so it must not open for payment.+ assertFalse(ready, "stale session opened for payment; error=$error")+ assertNull(vm.embeddedCheckout)+ assertTrue(error!!.contains("cart changed", ignoreCase = true), "error=$error")+ assertEquals(listOf("v1"), vm.cart.map { it.variantId })+ }+ @Test fun checkoutStore_backendFailureSurfacesUncertainMessage() { com.vayunmathur.shop.network.ShopHttpBackend.request = { _, _, _ -> com.vayunmathur.shop.network.BackendRawResponse(500, "down", emptyMap(), null)