Modern Apps git

← Modern-Apps.git

fooddelivery: checkout re-prices when the cart changes under it

Commit
7059c401e11c170ec3beb24db3d794913631ccf0
Author
Vayun Mathur <[email protected]>
When
2026-12-01 09:21 UTC (5 days ago)
Parents
620d9b4
CheckoutPricingEffect is the only place a checkout (draft
order + PaymentIntent) is created, but its LaunchedEffect
was keyed on neither the cart nor the merchant: on a
two-pane layout the Cart tab stays interactive beside the
Checkout detail sharing the same snapshot list, so
removing/editing a line recomposed checkout without
re-pricing; at entry the saved cart could equally land after
checkout first composed. Burger 9.99 priced once; adding
Fries 3.50 (subtotal 13.49) produced no second checkout —
Place Order kept presenting the intent priced for 9.99 of
food — and emptying the cart left a priced 'Place Order ·
10.00' presentable for a 0 cart.

The CheckoutCartItem mapping now happens in composition so
a mutated cart yields a structurally new key, and the
effect keys include cartItems, merchantId and canFetch;
on !canFetch the effect clears the stale priced response,
so a priced checkout can never outlive the cart that priced
it (the re-price reuses the same draft uuid — asserted).
Two regression tests failed pre-fix. Order tracking, cart
totals and the address store were audited and cleared.
Verified: :fooddelivery:testDevUnitTest 171 tests pass;
lint errors are pre-existing on untouched files.

Diff

fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutPricingEffect.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutPricingEffect.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutPricingEffect.ktindex 46d45daf4d..e005fcdc5a 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutPricingEffect.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutPricingEffect.kt@@ -35,30 +35,45 @@ fun CheckoutPricingEffect(     onFetchingPricesChange: (Boolean) -> Unit,     onLastOrderUuidChange: (String?) -> Unit, ) {+    // The cart lines are mapped in composition (not inside the effect) so a mutated+    // snapshot cart recomposes this effect with a structurally new key. Modifiers+    // already carry their group id, price and quantity from selection time, so they+    // go over the wire exactly as the reference cart stores them.+    val cartItems = items.map { item ->+        CheckoutCartItem(+            itemId = item.menuItem.id,+            quantity = item.quantity,+            specialInstructions = item.specialInstructions,+            modifiers = item.selectedModifiers,+        )+    }     // Every input baked into the request below must be a key: deliveryInstructions     // is not a pricing input, but this effect is the only place the checkout (and     // its draft order / PaymentIntent) is created, so without it as a key, typing     // instructions after the first pricing pass silently never reaches the server.+    // The cart lines and merchant are pricing inputs proper: without them, changing+    // the cart while checkout is composed (or the saved cart landing after entry)+    // never re-prices, and Place Order keeps presenting the stale PaymentIntent+    // while the on-screen subtotal follows the new cart.     LaunchedEffect(+        cartItems, merchantId, canFetch,         isPickup, tipCents, selectedAddress?.id, promoCode, customer?.uuid, selectedDealId,         deliveryInstructions,     ) {-        if (!canFetch || orderSuccess) return@LaunchedEffect+        if (!canFetch) {+            // No priced checkout may outlive the cart/address that priced it:+            // emptying the cart must drop the old total and its PaymentIntent+            // instead of leaving them presentable.+            onCheckoutResponseChange(null)+            onFetchingPricesChange(false)+            return@LaunchedEffect+        }+        if (orderSuccess) return@LaunchedEffect         AppInit.awaitReady()         onCheckoutResponseChange(null)         onErrorChange(null)         onFetchingPricesChange(true)         delay(400)-        // Modifiers already carry their group id, price and quantity from selection time,-        // so they go over the wire exactly as the reference cart stores them.-        val cartItems = items.map { item ->-            CheckoutCartItem(-                itemId = item.menuItem.id,-                quantity = item.quantity,-                specialInstructions = item.specialInstructions,-                modifiers = item.selectedModifiers,-            )-        }         val addr = if (!isPickup) selectedAddress?.let { a ->             CheckoutAddress(                 addressStreet = a.addressStreet,
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/CheckoutCartChangeTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/CheckoutCartChangeTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/CheckoutCartChangeTest.ktnew file mode 100644index 0000000000..95c11d9b6a--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/ui/CheckoutCartChangeTest.kt@@ -0,0 +1,165 @@+package com.vayunmathur.fooddelivery.ui++import android.app.Application+import android.content.Context+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.data.AddressStore+import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.CheckoutDraftStore+import com.vayunmathur.fooddelivery.data.MenuItem+import com.vayunmathur.fooddelivery.data.SavedAddress+import com.vayunmathur.fooddelivery.network.BitesAuth+import com.vayunmathur.fooddelivery.network.BitesCore+import com.vayunmathur.fooddelivery.platform.AppInit+import com.vayunmathur.library.network.SimpleResponse+import java.util.concurrent.CopyOnWriteArrayList+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Regression: the cart itself is a pricing input. [CheckoutPricingEffect] baked+ * the cart lines (and the merchant they belong to) into the checkout request but+ * keyed its effect on neither, so changing the cart while checkout was composed+ * — editing/removing a line in the two-pane cart pane, or the saved cart+ * landing after entry — never re-priced: the screen subtotal followed the new+ * cart while Place Order kept presenting the PaymentIntent priced for the old+ * one ($9.99 Burger alone vs $13.49 Burger + Fries below).+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class CheckoutCartChangeTest {+    @get:Rule val rule = createComposeRule()+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val realTransport = BitesCore.transport+    private val checkoutBodies = CopyOnWriteArrayList<String>()++    @org.junit.After fun restore() {+        BitesCore.transport = realTransport+        BitesAuth.clearToken()+    }++    private fun installFake() {+        checkoutBodies.clear()+        BitesCore.transport = { url, _, _, body ->+            when {+                url.contains("/checkout") -> {+                    if (body != null) checkoutBodies.add(body)+                    SimpleResponse(+                        200, "",+                        """{"serviceable":{"ok":true},"clientSecret":"pi_test_secret_abc",""" ++                            """"order":{"id":9,"uuid":"u9","foodTotal":1000,"orderTotal":1000}}""",+                        emptyMap(), url,+                    )+                }+                url.contains("/orders/past/all") ->+                    SimpleResponse(200, "", """{"data":[]}""", emptyMap(), url)+                url.contains("/customers/me") -> SimpleResponse(+                    200, "",+                    """{"data":{"id":5,"firstName":"Ann","lastName":"Lee","email":"[email protected]","uuid":"cust-uuid"}}""",+                    emptyMap(), url,+                )+                else -> SimpleResponse(404, "", "{}", emptyMap(), url)+            }+        }+        AppInit.start(ctx)+    }++    private fun awaitTrue(description: String, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 15_000+        var ok = false+        while (System.currentTimeMillis() < deadline) {+            rule.mainClock.autoAdvance = false+            rule.mainClock.advanceTimeBy(600L)+            rule.mainClock.autoAdvance = true+            org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper())+                .idleFor(300, java.util.concurrent.TimeUnit.MILLISECONDS)+            rule.waitForIdle()+            ok = condition()+            if (ok) break+            Thread.sleep(50)+        }+        assertTrue(ok, description)+    }++    private suspend fun seedAddress() {+        CheckoutDraftStore.clear(ctx)+        AddressStore.save(+            ctx,+            SavedAddress(+                id = "home", label = "Home", addressStreet = "1 Main",+                latitude = 37.5, longitude = -122.3, isDefault = true,+            ),+        )+    }++    private fun burger() = CartItem(+        menuItem = MenuItem(id = 10, name = "Burger", price = 999),+        quantity = 1, merchantId = 1,+    )++    private fun fries() = CartItem(+        menuItem = MenuItem(id = 20, name = "Fries", price = 350),+        quantity = 1, merchantId = 1,+    )++    @Test fun addingItemWhileInCheckoutRepricesWithIt() { runBlocking {+        installFake()+        seedAddress()+        val items = mutableStateOf(listOf(burger()))+        rule.setContent { CheckoutScreen(items.value, {}, {}) }+        awaitTrue("initial checkout request never fired") { checkoutBodies.isNotEmpty() }+        awaitTrue("Place Order never appeared") {+            try {+                rule.onNodeWithText("Place Order", substring = true).fetchSemanticsNode() != null+            } catch (_: AssertionError) { false }+        }+        val bodiesBeforeChange = checkoutBodies.size++        // Burger $9.99 alone becomes Burger + Fries $3.50 = $13.49 of food.+        rule.runOnIdle { items.value = listOf(burger(), fries()) }++        awaitTrue(+            "changing the cart fired no follow-up checkout; " ++                "bodies before=$bodiesBeforeChange after=${checkoutBodies.size}: $checkoutBodies",+        ) {+            checkoutBodies.size > bodiesBeforeChange &&+                checkoutBodies.last().contains("\"itemId\":20")+        }+        // The follow-up must UPDATE the priced draft, not create a second order.+        assertTrue(+            checkoutBodies.last().contains("\"uuid\":\"u9\""),+            "follow-up checkout did not reuse the draft order uuid: ${checkoutBodies.last()}",+        )+    } }++    @Test fun emptyingCartWhileInCheckoutDropsPricedCheckout() { runBlocking {+        installFake()+        seedAddress()+        val items = mutableStateOf(listOf(burger()))+        rule.setContent { CheckoutScreen(items.value, {}, {}) }+        awaitTrue("initial checkout request never fired") { checkoutBodies.isNotEmpty() }+        awaitTrue("priced Place Order never appeared") {+            try {+                rule.onNodeWithText("Place Order ·", substring = true).fetchSemanticsNode() != null+            } catch (_: AssertionError) { false }+        }++        rule.runOnIdle { items.value = emptyList() }++        // No priced checkout may survive an empty cart: the stale total and its+        // PaymentIntent must stop being presentable.+        awaitTrue("emptying the cart left the priced Place Order in place") {+            try {+                rule.onNodeWithText("Place Order ·", substring = true).fetchSemanticsNode() == null+            } catch (_: AssertionError) { true }+        }+    } }+}