Modern Apps git

← Modern-Apps.git

fooddelivery: assistant provider intents + checkout deep link (#assistant)

Commit
5fa25a71a462ac0dc4879e92fc1064ede8632c8e
Author
Vayun Mathur <[email protected]>
When
2026-11-16 22:54 UTC (19 days ago)
Parents
7b295b4
Add the P4 provider side of the OpenAssistant food tools so a
co-signed assistant can browse restaurants and menus, read and
replace the provider-owned cart, price an order, and read past
orders -- without ever creating an order or touching Stripe.

library.intents.fooddelivery (FoodDeliveryData.kt, all fields
defaulted for wire compatibility): FindRestaurants/RestaurantData,
GetMenu/MenuData with modifier-group summaries, GetCart/CartData,
SetCart, PrepareOrder/OrderSummaryData, GetOrders/OrderData.

fooddelivery/intents: FindRestaurantsIntent, GetMenuIntent,
GetCartIntent, SetCartIntent, PrepareOrderIntent and
GetOrdersIntent as NoDisplay AssistantIntent activities behind the
existing ACCESS_ORDERS signature permission (manifest reuses it;
no new permission). Provider logic lives behind a
FoodAssistantBackend seam (real BitesMerchants/BitesOrders/
CartStore/AddressStore; test seam mirroring communicate).

SetCart revalidates every line against the live menu before
writing: item exists and is available/in stock, modifier ids
belong to the item, required and min/max group selection rules,
and quantity bounds 1-99. Any failure returns the previous cart
with a stable error code and writes nothing; success is a single
CartStore save, so the replacement is atomic. The cart stays
single-merchant: writing another merchant's items replaces the
cart wholesale, as documented on the DTO, and an empty write
clears it.

PrepareOrder creates no order and calls no checkout endpoint.
There is no server checkout-preview path -- the only pricing call
creates an order plus a Stripe client secret -- so totals are
computed host-side from the cart: subtotal + tip (+ 0 delivery fee
for pickup), with taxesCents and deliveryFeeCents null when
unknowable and the promo echoed unvalued, all documented on
OrderSummaryData. The assistant hands off via the new
fooddelivery://checkout deep link (manifest filter, MainActivity
state, Route.Checkout), where the existing Stripe PaymentSheet
flow remains the payment confirmation.

Tests: fooddelivery intents AssistantIntentsTest on the existing
Bites fake-transport harness with real CartStore/AddressStore
under Robolectric -- find/menu/orders mapping, validated cart
write and read-back, cross-merchant replacement and clear, every
validation failure leaving the cart untouched, prepare totals
with an assertion that no /checkout URL was ever requested,
checkout deep-link parsing, and DTO default decoding.

Verified: :fooddelivery:testDevUnitTest (full suite, 160 tests)
and :fooddelivery:compileDevKotlin pass; the new intent tests are
10/10. No pushes, per instructions.

Diff

fooddelivery/src/main/AndroidManifest.xml
diff --git a/fooddelivery/src/main/AndroidManifest.xml b/fooddelivery/src/main/AndroidManifest.xmlindex 592a726def..1cabe055a4 100644--- a/fooddelivery/src/main/AndroidManifest.xml+++ b/fooddelivery/src/main/AndroidManifest.xml@@ -42,6 +42,12 @@                 <category android:name="android.intent.category.BROWSABLE" />                 <data android:scheme="fooddelivery" android:host="restaurant" />             </intent-filter>+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data android:scheme="fooddelivery" android:host="checkout" />+            </intent-filter>             <!-- Email verification links, in both forms the official Bites app accepts: the                  custom scheme the withbites.com verify page hands off to, and the web link in                  the email itself. Not autoVerify — we can't serve assetlinks on withbites.com,@@ -69,6 +75,40 @@             android:theme="@android:style/Theme.NoDisplay"             android:permission="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" /> +        <!-- Assistant provider intents (P4): same ACCESS_ORDERS signature+             permission as OrderLookupIntent. The assistant never creates+             orders; checkout happens in-app via fooddelivery://checkout. -->+        <activity+            android:name=".intents.FindRestaurantsIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" />+        <activity+            android:name=".intents.GetMenuIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" />+        <activity+            android:name=".intents.GetCartIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" />+        <activity+            android:name=".intents.SetCartIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" />+        <activity+            android:name=".intents.PrepareOrderIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" />+        <activity+            android:name=".intents.GetOrdersIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" />+         <service             android:name=".notifications.OrderTrackingService"             android:exported="false"
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.ktindex 94da5ca64b..cc4cf20977 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt@@ -120,6 +120,10 @@ class MainActivity : MaActivity() {     // onNewIntent can re-deep-link into the running UI.     private val openRestaurantId = mutableStateOf<Int?>(null) +    // fooddelivery://checkout — the assistant handoff: the cart was prepared+    // provider-side, and the user places/pays for the order here in-app.+    private val openCheckout = mutableStateOf(false)+     private val verifyEmail = mutableStateOf<Route.EmailVerification?>(null)      private val requestNotificationPermission =@@ -137,6 +141,7 @@ class MainActivity : MaActivity() {         AppInit.start(this)         trackOrderId.value = intent.trackOrderIdOrNull()         openRestaurantId.value = intent.restaurantIdOrNull()+        openCheckout.value = intent.isCheckoutDeepLink()         verifyEmail.value = intent.emailVerificationOrNull()         requestNotificationPermissionIfNeeded()         // The TLS trust bundle and the saved auth token are warmed up off the main thread by@@ -150,7 +155,7 @@ class MainActivity : MaActivity() {      @Composable     override fun Content() {-        FoodDeliveryApp(trackOrderId, openRestaurantId, verifyEmail)+        FoodDeliveryApp(trackOrderId, openRestaurantId, openCheckout, verifyEmail)     }      override fun onNewIntent(intent: Intent) {@@ -158,6 +163,7 @@ class MainActivity : MaActivity() {         setIntent(intent)         intent.trackOrderIdOrNull()?.let { trackOrderId.value = it }         intent.restaurantIdOrNull()?.let { openRestaurantId.value = it }+        if (intent.isCheckoutDeepLink()) openCheckout.value = true         intent.emailVerificationOrNull()?.let { verifyEmail.value = it }     } @@ -181,6 +187,14 @@ private fun Intent.restaurantIdOrNull(): Int? {     return uri.lastPathSegment?.toIntOrNull()?.takeIf { it > 0 } } +// fooddelivery://checkout — opens Route.Checkout for the current cart (the+// assistant's order handoff; payment still happens in-app via Stripe).+internal fun Intent.isCheckoutDeepLink(): Boolean {+    val uri = data ?: return false+    return uri.scheme == OrderLookupContract.DEEP_LINK_SCHEME &&+        uri.host == OrderLookupContract.DEEP_LINK_CHECKOUT_HOST+}+ private const val EMAIL_VERIFICATION = "email-verification"  // Both segments end up in an API path, so only plain id characters are let through.@@ -208,6 +222,7 @@ private fun Intent.emailVerificationOrNull(): Route.EmailVerification? { private fun FoodDeliveryApp(     trackOrderId: MutableState<Int?>,     openRestaurantId: MutableState<Int?>,+    openCheckout: MutableState<Boolean>,     verifyEmail: MutableState<Route.EmailVerification?>, ) {     val context = LocalContext.current@@ -227,6 +242,13 @@ private fun FoodDeliveryApp(         openRestaurantId.value = null     } +    // A fooddelivery://checkout deep link opens checkout for the current cart.+    LaunchedEffect(openCheckout.value) {+        if (!openCheckout.value) return@LaunchedEffect+        backStack.add(Route.Checkout)+        openCheckout.value = false+    }+     LaunchedEffect(verifyEmail.value) {         val route = verifyEmail.value ?: return@LaunchedEffect         backStack.add(route)
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/FindRestaurantsIntent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/FindRestaurantsIntent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/FindRestaurantsIntent.ktnew file mode 100644index 0000000000..b7f249e933--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/FindRestaurantsIntent.kt@@ -0,0 +1,15 @@+package com.vayunmathur.fooddelivery.intents++import com.vayunmathur.library.intents.fooddelivery.FindRestaurants+import com.vayunmathur.library.intents.fooddelivery.RestaurantData+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.ListSerializer++/** Assistant tool `find_restaurants`: merchants near a point, name/tag filtered. */+class FindRestaurantsIntent : AssistantIntent<FindRestaurants, List<RestaurantData>>(+    FindRestaurants.serializer(),+    ListSerializer(RestaurantData.serializer()),+) {+    override suspend fun performCalculation(input: FindRestaurants): List<RestaurantData> =+        findRestaurants(this, input, foodAssistantBackend())+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/FoodAssistantBackend.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/FoodAssistantBackend.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/FoodAssistantBackend.ktnew file mode 100644index 0000000000..e8bea45773--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/FoodAssistantBackend.kt@@ -0,0 +1,366 @@+package com.vayunmathur.fooddelivery.intents++import android.content.Context+import com.vayunmathur.fooddelivery.api.BitesMerchants+import com.vayunmathur.fooddelivery.api.BitesOrders+import com.vayunmathur.fooddelivery.data.AddressStore+import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.CartStore+import com.vayunmathur.fooddelivery.data.Merchant+import com.vayunmathur.fooddelivery.data.MerchantDetail+import com.vayunmathur.fooddelivery.data.Order+import com.vayunmathur.fooddelivery.data.SavedAddress+import com.vayunmathur.fooddelivery.data.SelectedModifier+import com.vayunmathur.fooddelivery.platform.AppInit+import com.vayunmathur.library.intents.fooddelivery.CartData+import com.vayunmathur.library.intents.fooddelivery.CartItemData+import com.vayunmathur.library.intents.fooddelivery.FindRestaurants+import com.vayunmathur.library.intents.fooddelivery.GetMenu+import com.vayunmathur.library.intents.fooddelivery.MenuCategoryData+import com.vayunmathur.library.intents.fooddelivery.MenuData+import com.vayunmathur.library.intents.fooddelivery.MenuItemData+import com.vayunmathur.library.intents.fooddelivery.MenuModifierData+import com.vayunmathur.library.intents.fooddelivery.MenuModifierGroupData+import com.vayunmathur.library.intents.fooddelivery.OrderData+import com.vayunmathur.library.intents.fooddelivery.OrderSummaryData+import com.vayunmathur.library.intents.fooddelivery.PrepareOrder+import com.vayunmathur.library.intents.fooddelivery.RestaurantData+import com.vayunmathur.library.intents.fooddelivery.SetCart++/** Typed failure codes returned in `error` fields (never thrown across the wire). */+internal const val ERROR_INVALID_MERCHANT = "INVALID_MERCHANT"+internal const val ERROR_MERCHANT_NOT_FOUND = "MERCHANT_NOT_FOUND"+internal const val ERROR_MERCHANT_MISMATCH = "MERCHANT_MISMATCH"+internal const val ERROR_ITEM_NOT_FOUND = "ITEM_NOT_FOUND"+internal const val ERROR_ITEM_UNAVAILABLE = "ITEM_UNAVAILABLE"+internal const val ERROR_UNKNOWN_MODIFIER = "UNKNOWN_MODIFIER"+internal const val ERROR_MODIFIER_REQUIRED = "MODIFIER_REQUIRED"+internal const val ERROR_MODIFIER_SELECTIONS = "MODIFIER_SELECTIONS_OUT_OF_RANGE"+internal const val ERROR_INVALID_QUANTITY = "INVALID_QUANTITY"+internal const val ERROR_INVALID_TIP = "INVALID_TIP"+internal const val ERROR_UNKNOWN_ADDRESS = "UNKNOWN_ADDRESS"+internal const val ERROR_EMPTY_CART = "EMPTY_CART"++internal const val MIN_CART_QTY = 1+internal const val MAX_CART_QTY = 99+internal const val DEFAULT_RESTAURANT_LIMIT = 5+internal const val MAX_RESTAURANT_LIMIT = 50++internal const val CHECKOUT_DEEP_LINK = "fooddelivery://checkout"++/**+ * Backend seam behind the fooddelivery assistant intents. Production delegates+ * to the Bites API objects, [CartStore] and [AddressStore]; tests install a+ * fake (or the Bites fake transport under the real backend) so provider logic+ * — filtering, cart/modifier validation, totals — is asserted without a+ * device. No method here ever calls `BitesOrders.checkout`: the assistant+ * prepares carts and prices them host-side, and the order itself is placed+ * and paid for in-app via the `fooddelivery://checkout` deep link.+ */+internal interface FoodAssistantBackend {+    /** Cold-process warm-up (trust bundle + saved token); no-op in tests. */+    suspend fun warmUp(context: Context)+    suspend fun getMerchants(lat: Double, lng: Double): List<Merchant>+    suspend fun getMerchantDetail(merchantId: Int): MerchantDetail?+    suspend fun getOrders(): List<Order>+    suspend fun getCart(context: Context): List<CartItem>+    suspend fun saveCart(context: Context, items: List<CartItem>)+    suspend fun getAddresses(context: Context): List<SavedAddress>+}++internal object RealFoodAssistantBackend : FoodAssistantBackend {+    override suspend fun warmUp(context: Context) {+        // These intents can run in a cold fooddelivery process; AppInit is+        // idempotent. An unattached test context has no applicationContext —+        // skip warm-up there (the Bites fake transport needs none).+        val appContext = runCatching { context.applicationContext }.getOrNull() ?: return+        AppInit.start(appContext)+        AppInit.awaitReady()+    }++    override suspend fun getMerchants(lat: Double, lng: Double): List<Merchant> =+        BitesMerchants.getMerchants(lat, lng)++    override suspend fun getMerchantDetail(merchantId: Int): MerchantDetail? =+        BitesMerchants.getMerchantDetail(merchantId)++    override suspend fun getOrders(): List<Order> = BitesOrders.getOrders()++    override suspend fun getCart(context: Context): List<CartItem> = CartStore.getAll(context)++    override suspend fun saveCart(context: Context, items: List<CartItem>) {+        // One save = one SharedPreferences write of the whole cart JSON, so a+        // validated replacement lands atomically (never line-by-line).+        CartStore.save(context, items)+    }++    override suspend fun getAddresses(context: Context): List<SavedAddress> =+        AddressStore.getAll(context)+}++/** Test seam, mirroring communicate's `communicateAssistantBackendForTest`. */+internal var foodAssistantBackendForTest: FoodAssistantBackend? = null++internal fun foodAssistantBackend(): FoodAssistantBackend =+    foodAssistantBackendForTest ?: RealFoodAssistantBackend++// --- DTO mapping ---++internal fun Merchant.toRestaurantData(): RestaurantData = RestaurantData(+    id = id,+    name = name,+    address = address,+    isOpen = isOpen,+    isDeliveryEnabled = isDeliveryEnabled,+    isPickupEnabled = isPickupEnabled,+    rating = averageRating,+    totalRatings = totalRatings,+    distance = distance,+    tags = merchantTags,+    imageUrl = displayImage,+)++internal fun MerchantDetail.toMenuData(): MenuData = MenuData(+    merchantId = id,+    merchantName = name,+    categories = categories.map { MenuCategoryData(it.id, it.name, it.itemIds) },+    items = items.map { item ->+        MenuItemData(+            id = item.id,+            name = item.name,+            priceCents = item.price,+            available = item.isAvailable && item.isInStock,+            category = item.category,+            modifierGroups = item.modifierGroups.map { group ->+                MenuModifierGroupData(+                    id = group.id,+                    name = group.name,+                    required = group.required,+                    minSelections = group.minSelections,+                    maxSelections = group.maxSelections,+                    modifiers = group.modifiers.map {+                        MenuModifierData(it.id, it.name, it.price)+                    },+                )+            },+        )+    },+)++/** Line total in cents: (item + modifier unit prices) × quantity. */+internal fun CartItem.lineTotalCents(): Int =+    (menuItem.price + selectedModifiers.sumOf { it.price * it.quantity }) * quantity++internal fun CartItem.toCartItemData(): CartItemData = CartItemData(+    itemId = menuItem.id,+    name = menuItem.name,+    qty = quantity,+    modifierIds = selectedModifiers.map { it.modifierId },+    lineTotalCents = lineTotalCents(),+)++internal fun List<CartItem>.toCartData(error: String? = null): CartData = CartData(+    merchantId = firstOrNull()?.merchantId ?: 0,+    merchantName = firstOrNull()?.merchantName ?: "",+    items = map { it.toCartItemData() },+    totalCents = sumOf { it.lineTotalCents() },+    error = error,+)++internal fun Order.toOrderData(): OrderData = OrderData(+    id = id,+    uuid = uuid,+    merchantId = merchant?.id ?: 0,+    merchantName = merchant?.name ?: "",+    status = displayStatus,+    // orderTotal is the server-authoritative total when present; otherwise+    // fall back to the component sum, matching Order.displayTotal.+    totalCents = orderTotal ?: (foodTotal + (fees ?: 0) + taxes + deliveryFee + tips),+    itemCount = orderItems.sumOf { it.quantity },+    createdAt = createdAt,+    isDelivery = isDelivery,+    isDone = isDone,+)++// --- Intent logic (context is only used by the real backend's stores) ---++internal suspend fun findRestaurants(+    context: Context,+    input: FindRestaurants,+    backend: FoodAssistantBackend,+): List<RestaurantData> {+    backend.warmUp(context)+    val merchants = runCatching { backend.getMerchants(input.lat, input.lng) }+        .getOrDefault(emptyList())+    val query = input.query?.trim().orEmpty()+    val filtered = if (query.isEmpty()) {+        merchants+    } else {+        merchants.filter { merchant ->+            merchant.name.contains(query, ignoreCase = true) ||+                merchant.merchantTags.any { it.contains(query, ignoreCase = true) }+        }+    }+    val limit = if (input.limit <= 0) {+        DEFAULT_RESTAURANT_LIMIT+    } else {+        input.limit.coerceAtMost(MAX_RESTAURANT_LIMIT)+    }+    return filtered.take(limit).map { it.toRestaurantData() }+}++internal suspend fun getMenu(+    context: Context,+    input: GetMenu,+    backend: FoodAssistantBackend,+): MenuData {+    if (input.merchantId <= 0) {+        return MenuData(merchantId = input.merchantId, error = ERROR_INVALID_MERCHANT)+    }+    backend.warmUp(context)+    val detail = runCatching { backend.getMerchantDetail(input.merchantId) }.getOrNull()+        ?: return MenuData(merchantId = input.merchantId, error = ERROR_MERCHANT_NOT_FOUND)+    return detail.toMenuData()+}++internal suspend fun getCart(+    context: Context,+    backend: FoodAssistantBackend,+): CartData {+    backend.warmUp(context)+    return runCatching { backend.getCart(context) }.getOrDefault(emptyList()).toCartData()+}++/**+ * Validate [input] against the live menu for its merchant. Returns the built+ * cart lines, or null with [errorOut] set. Nothing is written here — the+ * caller writes the returned lines in a single [FoodAssistantBackend.saveCart]+ * call, so a rejected cart leaves the stored cart untouched.+ */+internal fun buildValidatedCart(+    detail: MerchantDetail,+    input: SetCart,+): Pair<List<CartItem>?, String?> {+    val itemsById = detail.items.associateBy { it.id }+    val built = mutableListOf<CartItem>()+    for (line in input.items) {+        if (line.qty !in MIN_CART_QTY..MAX_CART_QTY) return null to ERROR_INVALID_QUANTITY+        val item = itemsById[line.itemId] ?: return null to ERROR_ITEM_NOT_FOUND+        if (!item.isAvailable || !item.isInStock) return null to ERROR_ITEM_UNAVAILABLE+        val selected = mutableListOf<SelectedModifier>()+        for (group in item.modifierGroups) {+            val inGroup = group.modifiers.associateBy { it.id }+            val chosen = line.modifierIds.filter { it in inGroup }+            val effectiveMin = if (group.required) {+                maxOf(group.minSelections, 1)+            } else {+                group.minSelections+            }+            if (chosen.size < effectiveMin) {+                return null to if (group.required) {+                    ERROR_MODIFIER_REQUIRED+                } else {+                    ERROR_MODIFIER_SELECTIONS+                }+            }+            if (chosen.size > group.maxSelections) return null to ERROR_MODIFIER_SELECTIONS+            chosen.mapTo(selected) { modifierId ->+                val modifier = inGroup.getValue(modifierId)+                SelectedModifier(+                    modifierGroupId = group.id,+                    modifierId = modifier.id,+                    name = modifier.name,+                    price = modifier.price,+                )+            }+        }+        val knownModifierIds = item.modifierGroups+            .flatMap { group -> group.modifiers.map { it.id } }+            .toSet()+        if (line.modifierIds.any { it !in knownModifierIds }) {+            return null to ERROR_UNKNOWN_MODIFIER+        }+        built += CartItem(+            menuItem = item,+            quantity = line.qty,+            selectedModifiers = selected,+            merchantId = detail.id,+            merchantName = detail.name,+        )+    }+    return built to null+}++internal suspend fun setCart(+    context: Context,+    input: SetCart,+    backend: FoodAssistantBackend,+): CartData {+    backend.warmUp(context)+    val current = runCatching { backend.getCart(context) }.getOrDefault(emptyList())+    if (input.merchantId <= 0) return current.toCartData(error = ERROR_INVALID_MERCHANT)+    if (input.items.isEmpty()) {+        // Replacing with nothing clears the cart (single atomic write).+        backend.saveCart(context, emptyList())+        return CartData(merchantId = 0, error = null)+    }+    val detail = runCatching { backend.getMerchantDetail(input.merchantId) }.getOrNull()+        ?: return current.toCartData(error = ERROR_MERCHANT_NOT_FOUND)+    val (built, error) = buildValidatedCart(detail, input)+    if (error != null || built == null) {+        return current.toCartData(error = error ?: ERROR_ITEM_NOT_FOUND)+    }+    // Single-merchant rule: this one save replaces any previous cart, even+    // one from a different merchant — exactly the in-app "start a new cart".+    backend.saveCart(context, built)+    return built.toCartData()+}++internal suspend fun prepareOrder(+    context: Context,+    input: PrepareOrder,+    backend: FoodAssistantBackend,+): OrderSummaryData {+    backend.warmUp(context)+    val cart = runCatching { backend.getCart(context) }.getOrDefault(emptyList())+    val cartData = cart.toCartData()+    fun summary(error: String?) = OrderSummaryData(+        merchantId = cartData.merchantId,+        merchantName = cartData.merchantName,+        isPickup = input.isPickup,+        addressId = input.addressId,+        items = cartData.items,+        subtotalCents = cartData.totalCents,+        deliveryFeeCents = if (input.isPickup) 0 else null,+        taxesCents = null,+        tipCents = input.tipCents.coerceAtLeast(0),+        promo = input.promo?.trim()?.ifBlank { null },+        // Known parts only: subtotal + tip (+ 0 delivery fee for pickup).+        totalCents = cartData.totalCents + input.tipCents.coerceAtLeast(0),+        checkoutDeepLink = CHECKOUT_DEEP_LINK,+        error = error,+    )+    if (cart.isEmpty()) return summary(ERROR_EMPTY_CART)+    if (input.tipCents < 0) return summary(ERROR_INVALID_TIP)+    if (input.merchantId != 0 && input.merchantId != cartData.merchantId) {+        return summary(ERROR_MERCHANT_MISMATCH)+    }+    val addressId = input.addressId?.trim()?.ifBlank { null }+    if (addressId != null) {+        val addresses = runCatching { backend.getAddresses(context) }.getOrDefault(emptyList())+        if (addresses.none { it.id == addressId }) return summary(ERROR_UNKNOWN_ADDRESS)+    }+    // No order is created and no checkout call is made: there is no server+    // checkout-preview endpoint, so taxes / delivery fee stay null (unknown)+    // and totalCents sums only the known parts. See OrderSummaryData.+    return summary(error = null).copy(addressId = addressId)+}++internal suspend fun getOrders(+    context: Context,+    backend: FoodAssistantBackend,+): List<OrderData> {+    backend.warmUp(context)+    return runCatching { backend.getOrders() }.getOrDefault(emptyList())+        .map { it.toOrderData() }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetCartIntent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetCartIntent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetCartIntent.ktnew file mode 100644index 0000000000..bef2d5d68f--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetCartIntent.kt@@ -0,0 +1,14 @@+package com.vayunmathur.fooddelivery.intents++import com.vayunmathur.library.intents.fooddelivery.CartData+import com.vayunmathur.library.intents.fooddelivery.GetCart+import com.vayunmathur.library.util.AssistantIntent++/** Assistant tool `food_get_cart`: reads the provider-owned [com.vayunmathur.fooddelivery.data.CartStore]. */+class GetCartIntent : AssistantIntent<GetCart, CartData>(+    GetCart.serializer(),+    CartData.serializer(),+) {+    override suspend fun performCalculation(input: GetCart): CartData =+        getCart(this, foodAssistantBackend())+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetMenuIntent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetMenuIntent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetMenuIntent.ktnew file mode 100644index 0000000000..6ac73b45ef--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetMenuIntent.kt@@ -0,0 +1,14 @@+package com.vayunmathur.fooddelivery.intents++import com.vayunmathur.library.intents.fooddelivery.GetMenu+import com.vayunmathur.library.intents.fooddelivery.MenuData+import com.vayunmathur.library.util.AssistantIntent++/** Assistant tool `get_restaurant_menu`: categories + items with modifier summaries. */+class GetMenuIntent : AssistantIntent<GetMenu, MenuData>(+    GetMenu.serializer(),+    MenuData.serializer(),+) {+    override suspend fun performCalculation(input: GetMenu): MenuData =+        getMenu(this, input, foodAssistantBackend())+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetOrdersIntent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetOrdersIntent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetOrdersIntent.ktnew file mode 100644index 0000000000..89546afe14--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/GetOrdersIntent.kt@@ -0,0 +1,15 @@+package com.vayunmathur.fooddelivery.intents++import com.vayunmathur.library.intents.fooddelivery.GetOrders+import com.vayunmathur.library.intents.fooddelivery.OrderData+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.ListSerializer++/** Assistant tool `get_food_orders`: the signed-in customer's past orders. */+class GetOrdersIntent : AssistantIntent<GetOrders, List<OrderData>>(+    GetOrders.serializer(),+    ListSerializer(OrderData.serializer()),+) {+    override suspend fun performCalculation(input: GetOrders): List<OrderData> =+        getOrders(this, foodAssistantBackend())+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/PrepareOrderIntent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/PrepareOrderIntent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/PrepareOrderIntent.ktnew file mode 100644index 0000000000..8767dbd041--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/PrepareOrderIntent.kt@@ -0,0 +1,18 @@+package com.vayunmathur.fooddelivery.intents++import com.vayunmathur.library.intents.fooddelivery.OrderSummaryData+import com.vayunmathur.library.intents.fooddelivery.PrepareOrder+import com.vayunmathur.library.util.AssistantIntent++/**+ * Assistant tool `food_prepare_order`: prices the provider cart host-side+ * WITHOUT creating an order (no checkout call, no client secret). The user+ * places/pays in-app via the returned `fooddelivery://checkout` deep link.+ */+class PrepareOrderIntent : AssistantIntent<PrepareOrder, OrderSummaryData>(+    PrepareOrder.serializer(),+    OrderSummaryData.serializer(),+) {+    override suspend fun performCalculation(input: PrepareOrder): OrderSummaryData =+        prepareOrder(this, input, foodAssistantBackend())+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/SetCartIntent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/SetCartIntent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/SetCartIntent.ktnew file mode 100644index 0000000000..00bada3ba3--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/SetCartIntent.kt@@ -0,0 +1,19 @@+package com.vayunmathur.fooddelivery.intents++import com.vayunmathur.library.intents.fooddelivery.CartData+import com.vayunmathur.library.intents.fooddelivery.SetCart+import com.vayunmathur.library.util.AssistantIntent++/**+ * Assistant tool `food_set_cart` (provider side): re-validates every line+ * against the live menu, then replaces the provider cart in one atomic+ * [com.vayunmathur.fooddelivery.data.CartStore] write. A different merchant+ * replaces the previous cart (single-merchant rule). Never creates an order.+ */+class SetCartIntent : AssistantIntent<SetCart, CartData>(+    SetCart.serializer(),+    CartData.serializer(),+) {+    override suspend fun performCalculation(input: SetCart): CartData =+        setCart(this, input, foodAssistantBackend())+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.ktindex b9f5c7690a..ef6377bf15 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.kt@@ -18,4 +18,10 @@ object OrderLookupContract {      /** Build the deep link that opens merchant [id]'s order page. */     fun deepLink(id: Int): String = "$DEEP_LINK_SCHEME://$DEEP_LINK_HOST/$id"++    // ---- deep link (open checkout for the current cart, assistant handoff) ----+    const val DEEP_LINK_CHECKOUT_HOST = "checkout"++    /** Build the deep link that opens checkout for the current cart. */+    fun checkoutDeepLink(): String = "$DEEP_LINK_SCHEME://$DEEP_LINK_CHECKOUT_HOST" }
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/intents/AssistantIntentsTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/intents/AssistantIntentsTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/intents/AssistantIntentsTest.ktnew file mode 100644index 0000000000..9f75c7b8bb--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/intents/AssistantIntentsTest.kt@@ -0,0 +1,367 @@+package com.vayunmathur.fooddelivery.intents++import android.app.Application+import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.api.BitesAuth+import com.vayunmathur.fooddelivery.api.BitesCore+import com.vayunmathur.fooddelivery.data.AddressStore+import com.vayunmathur.fooddelivery.data.AuthToken+import com.vayunmathur.fooddelivery.data.CartStore+import com.vayunmathur.fooddelivery.data.SavedAddress+import com.vayunmathur.fooddelivery.isCheckoutDeepLink+import com.vayunmathur.fooddelivery.platform.AppInit+import com.vayunmathur.library.intents.fooddelivery.FindRestaurants+import com.vayunmathur.library.intents.fooddelivery.GetCart+import com.vayunmathur.library.intents.fooddelivery.GetMenu+import com.vayunmathur.library.intents.fooddelivery.GetOrders+import com.vayunmathur.library.intents.fooddelivery.PrepareOrder+import com.vayunmathur.library.intents.fooddelivery.SetCart+import com.vayunmathur.library.intents.fooddelivery.SetCartItem+import com.vayunmathur.library.network.SimpleResponse+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.After+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Assistant provider intents ([FindRestaurantsIntent] … [GetOrdersIntent])+ * against the existing Bites fake-transport harness (see+ * `BitesApiFakeTransportTest`): canned envelopes per URL, recorded requests,+ * the real [CartStore]/[AddressStore] under Robolectric. Validation failures+ * are asserted to leave the stored cart untouched, and no test — in+ * particular [PrepareOrderIntent] — may ever hit a checkout endpoint.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class, sdk = [34])+class AssistantIntentsTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val realTransport = BitesCore.transport+    private val requestedUrls = mutableListOf<String>()++    private fun resp(url: String, body: String) = SimpleResponse(200, "", body, emptyMap(), url)++    @Before+    fun installFakeTransport() {+        requestedUrls.clear()+        BitesCore.transport = { url, _, _, _ ->+            requestedUrls += url+            when {+                url.contains("/merchants/all/stores") -> resp(+                    url,+                    """{"data":{"merchants":[+                      {"id":7,"name":"Joe's Cafe","latitude":37.0,"longitude":-122.0,+                       "isOpen":true,"merchantTags":["burgers","cafe"]},+                      {"id":8,"name":"Sushi Place","latitude":37.01,"longitude":-122.0,+                       "isOpen":true,"merchantTags":["sushi"]}+                    ]}}""",+                )+                url.contains("/merchants/7") -> resp(+                    url,+                    """{"data":{"id":7,"name":"Joe's Cafe",+                      "categories":[{"id":1,"name":"Mains","itemIds":[10,11]}],+                      "items":[+                        {"id":10,"name":"Burger","price":1000,"isAvailable":true,"isInStock":true,+                         "modifierGroups":[+                           {"id":1,"name":"Size","required":true,"minSelections":1,"maxSelections":1,+                            "modifiers":[{"id":101,"name":"Small","price":0},+                                         {"id":102,"name":"Large","price":200}]},+                           {"id":2,"name":"Extras","required":false,"minSelections":0,"maxSelections":2,+                            "modifiers":[{"id":201,"name":"Cheese","price":100},+                                         {"id":202,"name":"Bacon","price":150},+                                         {"id":203,"name":"Avocado","price":120}]}+                         ]},+                        {"id":11,"name":"Salad","price":800,"isAvailable":true,"isInStock":true},+                        {"id":12,"name":"Sold Out Soup","price":600,"isAvailable":false,"isInStock":true}+                      ]}}""",+                )+                url.contains("/merchants/8") -> resp(+                    url,+                    """{"data":{"id":8,"name":"Sushi Place","categories":[],+                      "items":[{"id":20,"name":"Roll","price":1200,"isAvailable":true,"isInStock":true}]}}""",+                )+                url.contains("/orders/past/all") -> resp(+                    url,+                    """{"data":[{"id":9,"uuid":"u9","foodTotal":1000,"deliveryFee":200,+                      "taxes":80,"tips":100,"orderTotal":1380,+                      "merchant":{"id":7,"name":"Joe's Cafe"},+                      "orderItems":[{"id":1,"name":"Burger","quantity":1,"price":1000}],+                      "channel":"ORDER_CHANNEL_STOREFRONT_DELIVERY",+                      "deliveredAt":"2024-01-01T00:00:00Z"}]}""",+                )+                else -> SimpleResponse(404, "", "{}", emptyMap(), url)+            }+        }+        BitesAuth.setToken(AuthToken("acc", "ref", "Bearer", 3600))+        AppInit.start(ctx)+        runBlocking {+            CartStore.clear(ctx)+            awaitCart { it.isEmpty() }+        }+    }++    @After+    fun restore() {+        BitesCore.transport = realTransport+        BitesAuth.clearToken()+        foodAssistantBackendForTest = null+    }++    /** CartStore writes are async; poll the store until [predicate] holds. */+    private suspend fun awaitCart(predicate: (List<com.vayunmathur.fooddelivery.data.CartItem>) -> Boolean) {+        repeat(100) {+            if (predicate(CartStore.getAll(ctx))) return+            Thread.sleep(20)+        }+        assertTrue(predicate(CartStore.getAll(ctx)), "cart did not reach expected state")+    }++    private fun <T : com.vayunmathur.library.util.AssistantIntent<*, *>> activity(type: Class<T>): T =+        Robolectric.buildActivity(type).create().get()++    // --- FindRestaurants / GetMenu / GetOrders over the fake transport ---++    @Test+    fun findRestaurantsFiltersByQueryAndCapsLimit() = runBlocking {+        val intent = activity(FindRestaurantsIntent::class.java)+        val all = intent.performCalculation(FindRestaurants(lat = 37.0, lng = -122.0))+        assertEquals(listOf(7, 8), all.map { it.id })+        assertEquals("Joe's Cafe", all[0].name)+        assertTrue(all[0].isOpen)+        val byName = intent.performCalculation(FindRestaurants(query = "sushi", lat = 37.0, lng = -122.0))+        assertEquals(listOf(8), byName.map { it.id })+        val byTag = intent.performCalculation(FindRestaurants(query = "BURGERS", lat = 37.0, lng = -122.0))+        assertEquals(listOf(7), byTag.map { it.id })+        assertEquals(1, intent.performCalculation(FindRestaurants(lat = 37.0, lng = -122.0, limit = 1)).size)+        // limit <= 0 falls back to the default window.+        assertEquals(2, intent.performCalculation(FindRestaurants(lat = 37.0, lng = -122.0, limit = 0)).size)+    }++    @Test+    fun getMenuMapsCategoriesItemsAndModifierSummaries() = runBlocking {+        val intent = activity(GetMenuIntent::class.java)+        val menu = intent.performCalculation(GetMenu(merchantId = 7))+        assertNull(menu.error)+        assertEquals("Joe's Cafe", menu.merchantName)+        assertEquals(listOf(10, 11), menu.categories.single().itemIds)+        val burger = menu.items.first { it.id == 10 }+        assertEquals(1000, burger.priceCents)+        assertTrue(burger.available)+        val size = burger.modifierGroups.first { it.id == 1 }+        assertTrue(size.required)+        assertEquals(1, size.minSelections)+        assertEquals(1, size.maxSelections)+        assertEquals(listOf(101, 102), size.modifiers.map { it.id })+        assertFalse(menu.items.first { it.id == 12 }.available)+        assertEquals(ERROR_INVALID_MERCHANT, intent.performCalculation(GetMenu(merchantId = 0)).error)+        assertEquals(ERROR_MERCHANT_NOT_FOUND, intent.performCalculation(GetMenu(merchantId = 99)).error)+    }++    @Test+    fun getOrdersMapsPastOrders() = runBlocking {+        val orders = activity(GetOrdersIntent::class.java).performCalculation(GetOrders())+        val order = orders.single()+        assertEquals(9, order.id)+        assertEquals("Joe's Cafe", order.merchantName)+        assertEquals(1380, order.totalCents)+        assertEquals(1, order.itemCount)+        assertTrue(order.isDelivery)+        assertTrue(order.isDone)+    }++    // --- Cart: validated atomic replacement ---++    private suspend fun seedValidCart() {+        val result = activity(SetCartIntent::class.java).performCalculation(+            SetCart(+                merchantId = 7,+                items = listOf(SetCartItem(itemId = 10, qty = 2, modifierIds = listOf(102, 201))),+            ),+        )+        assertNull(result.error, "seed cart rejected: $result")+        // (1000 + 200 + 100) * 2+        assertEquals(2600, result.totalCents)+        awaitCart { it.size == 1 && it[0].quantity == 2 }+    }++    @Test+    fun setCartWritesValidatedCartAndGetCartReadsItBack() = runBlocking {+        seedValidCart()+        val cart = activity(GetCartIntent::class.java).performCalculation(GetCart())+        assertNull(cart.error)+        assertEquals(7, cart.merchantId)+        assertEquals("Joe's Cafe", cart.merchantName)+        val line = cart.items.single()+        assertEquals(10, line.itemId)+        assertEquals("Burger", line.name)+        assertEquals(2, line.qty)+        assertEquals(listOf(102, 201), line.modifierIds)+        assertEquals(2600, line.lineTotalCents)+        assertEquals(2600, cart.totalCents)+    }++    @Test+    fun setCartDifferentMerchantReplacesAndEmptyClears() = runBlocking {+        seedValidCart()+        // Single-merchant rule: writing a different merchant's items replaces+        // the previous cart wholesale (documented on SetCart), never merges.+        val replaced = activity(SetCartIntent::class.java).performCalculation(+            SetCart(merchantId = 8, items = listOf(SetCartItem(itemId = 20, qty = 1))),+        )+        assertNull(replaced.error)+        assertEquals(8, replaced.merchantId)+        assertEquals(listOf(20), replaced.items.map { it.itemId })+        awaitCart { it.size == 1 && it[0].merchantId == 8 && it[0].menuItem.id == 20 }+        val cleared = activity(SetCartIntent::class.java).performCalculation(+            SetCart(merchantId = 7, items = emptyList()),+        )+        assertNull(cleared.error)+        assertEquals(0, cleared.merchantId)+        assertTrue(cleared.items.isEmpty())+        awaitCart { it.isEmpty() }+    }++    @Test+    fun setCartValidationFailuresLeaveCartUntouched() = runBlocking {+        seedValidCart()+        val intent = activity(SetCartIntent::class.java)+        fun rejected(input: SetCart) = runBlocking { intent.performCalculation(input) }++        assertEquals(+            ERROR_ITEM_NOT_FOUND,+            rejected(SetCart(7, listOf(SetCartItem(itemId = 999, qty = 1)))).error,+        )+        assertEquals(+            ERROR_ITEM_UNAVAILABLE,+            rejected(SetCart(7, listOf(SetCartItem(itemId = 12, qty = 1)))).error,+        )+        assertEquals(+            ERROR_INVALID_QUANTITY,+            rejected(SetCart(7, listOf(SetCartItem(itemId = 11, qty = 0)))).error,+        )+        assertEquals(+            ERROR_INVALID_QUANTITY,+            rejected(SetCart(7, listOf(SetCartItem(itemId = 11, qty = 100)))).error,+        )+        assertEquals(+            ERROR_UNKNOWN_MODIFIER,+            rejected(SetCart(7, listOf(SetCartItem(itemId = 10, qty = 1, modifierIds = listOf(101, 999))))).error,+        )+        // Required "Size" group with no selection.+        assertEquals(+            ERROR_MODIFIER_REQUIRED,+            rejected(SetCart(7, listOf(SetCartItem(itemId = 10, qty = 1)))).error,+        )+        // Two selections in the max-1 "Size" group.+        assertEquals(+            ERROR_MODIFIER_SELECTIONS,+            rejected(SetCart(7, listOf(SetCartItem(itemId = 10, qty = 1, modifierIds = listOf(101, 102))))).error,+        )+        // Three selections in the max-2 "Extras" group.+        assertEquals(+            ERROR_MODIFIER_SELECTIONS,+            rejected(+                SetCart(7, listOf(SetCartItem(itemId = 10, qty = 1, modifierIds = listOf(101, 201, 202, 203)))),+            ).error,+        )+        assertEquals(+            ERROR_INVALID_MERCHANT,+            rejected(SetCart(0, listOf(SetCartItem(itemId = 11, qty = 1)))).error,+        )+        assertEquals(+            ERROR_MERCHANT_NOT_FOUND,+            rejected(SetCart(99, listOf(SetCartItem(itemId = 11, qty = 1)))).error,+        )+        // Every rejection returned the untouched cart and wrote nothing.+        val cart = activity(GetCartIntent::class.java).performCalculation(GetCart())+        assertEquals(2600, cart.totalCents)+        assertEquals(listOf(10), cart.items.map { it.itemId })+        awaitCart { it.size == 1 && it[0].menuItem.id == 10 && it[0].quantity == 2 }+    }++    // --- PrepareOrder: totals only, never an order ---++    @Test+    fun prepareOrderComputesKnownTotalsWithoutCheckoutCall() = runBlocking {+        seedValidCart()+        AddressStore.save(ctx, SavedAddress(id = "addr1", addressStreet = "1 Main St"))+        val intent = activity(PrepareOrderIntent::class.java)++        val pickup = intent.performCalculation(+            PrepareOrder(merchantId = 7, isPickup = true, tipCents = 300),+        )+        assertNull(pickup.error)+        assertEquals(2600, pickup.subtotalCents)+        assertEquals(0, pickup.deliveryFeeCents)+        assertNull(pickup.taxesCents)+        assertEquals(2900, pickup.totalCents)+        assertEquals("fooddelivery://checkout", pickup.checkoutDeepLink)++        val delivery = intent.performCalculation(+            PrepareOrder(merchantId = 7, isPickup = false, addressId = "addr1", tipCents = 300, promo = " SAVE "),+        )+        assertNull(delivery.error)+        // No checkout-preview endpoint exists: delivery fee / taxes unknown.+        assertNull(delivery.deliveryFeeCents)+        assertNull(delivery.taxesCents)+        assertEquals("SAVE", delivery.promo)+        assertEquals(2900, delivery.totalCents)++        assertEquals(+            ERROR_MERCHANT_MISMATCH,+            intent.performCalculation(PrepareOrder(merchantId = 8, isPickup = true)).error,+        )+        assertEquals(+            ERROR_INVALID_TIP,+            intent.performCalculation(PrepareOrder(merchantId = 7, isPickup = true, tipCents = -1)).error,+        )+        assertEquals(+            ERROR_UNKNOWN_ADDRESS,+            intent.performCalculation(PrepareOrder(merchantId = 7, addressId = "nope")).error,+        )+        // The assistant NEVER creates an order.+        assertTrue(requestedUrls.none { it.contains("/checkout") }, "checkout called: $requestedUrls")+    }++    @Test+    fun prepareOrderEmptyCartErrorsWithoutCheckoutCall() = runBlocking {+        val summary = activity(PrepareOrderIntent::class.java)+            .performCalculation(PrepareOrder(merchantId = 7, isPickup = true))+        assertEquals(ERROR_EMPTY_CART, summary.error)+        assertTrue(requestedUrls.none { it.contains("/checkout") })+    }++    // --- Deep link + DTO compat ---++    @Test+    fun checkoutDeepLinkParsesOnlyFooddeliveryCheckout() {+        fun intent(uri: String?) = Intent(ctx, com.vayunmathur.fooddelivery.MainActivity::class.java)+            .apply { if (uri != null) data = Uri.parse(uri) }+        assertTrue(intent("fooddelivery://checkout").isCheckoutDeepLink())+        assertFalse(intent("fooddelivery://restaurant/7").isCheckoutDeepLink())+        assertFalse(intent("https://example.com/checkout").isCheckoutDeepLink())+        assertFalse(intent(null).isCheckoutDeepLink())+    }++    @Test+    fun dtoDefaultsDecodeFromEmptyJson() {+        assertEquals(FindRestaurants(), Json.decodeFromString(FindRestaurants.serializer(), "{}"))+        assertEquals(GetMenu(), Json.decodeFromString(GetMenu.serializer(), "{}"))+        assertEquals(GetCart(), Json.decodeFromString(GetCart.serializer(), "{}"))+        assertEquals(SetCart(), Json.decodeFromString(SetCart.serializer(), "{}"))+        assertEquals(PrepareOrder(), Json.decodeFromString(PrepareOrder.serializer(), "{}"))+        assertEquals(GetOrders(), Json.decodeFromString(GetOrders.serializer(), "{}"))+    }+}
library/src/main/java/com/vayunmathur/library/intents/fooddelivery/FoodDeliveryData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/fooddelivery/FoodDeliveryData.kt b/library/src/main/java/com/vayunmathur/library/intents/fooddelivery/FoodDeliveryData.ktnew file mode 100644index 0000000000..0a1f0633c6--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/fooddelivery/FoodDeliveryData.kt@@ -0,0 +1,222 @@+package com.vayunmathur.library.intents.fooddelivery++import kotlinx.serialization.Serializable++/**+ * Shared wire DTOs for fooddelivery's cross-app assistant intents+ * ([com.vayunmathur.library.util.AssistantIntent]): `FindRestaurantsIntent`,+ * `GetMenuIntent`, `GetCartIntent`, `SetCartIntent`, `PrepareOrderIntent` and+ * `GetOrdersIntent` in `com.vayunmathur.fooddelivery.intents`, answered only for+ * a co-signed caller behind+ * `com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS`.+ *+ * Thin and UI-free by design; all money is integer cents. Every field has a+ * default so older/newer callers can omit fields without breaking decode+ * (library DTO-compat rule).+ *+ * The assistant never creates an order: there is deliberately no checkout /+ * place-order DTO here. [PrepareOrder] only prices the provider-owned cart;+ * the user places the order in the fooddelivery app itself, opened via the+ * `fooddelivery://checkout` deep link ([OrderSummaryData.checkoutDeepLink]).+ */++/** Find restaurants near ([lat], [lng]); [query] optionally filters name/tags. */+@Serializable+data class FindRestaurants(+    val query: String? = null,+    val lat: Double = 0.0,+    val lng: Double = 0.0,+    val limit: Int = 5,+)++/** One restaurant as the assistant sees it. */+@Serializable+data class RestaurantData(+    val id: Int = 0,+    val name: String = "",+    val address: String = "",+    val isOpen: Boolean = false,+    val isDeliveryEnabled: Boolean = false,+    val isPickupEnabled: Boolean = false,+    val rating: Double? = null,+    val totalRatings: Int? = null,+    val distance: Double? = null,+    val tags: List<String> = emptyList(),+    val imageUrl: String = "",+)++/** Read the menu of merchant [merchantId]. */+@Serializable+data class GetMenu(+    val merchantId: Int = 0,+)++/** One modifier option on a menu item, priced in cents. */+@Serializable+data class MenuModifierData(+    val id: Int = 0,+    val name: String = "",+    val priceCents: Int = 0,+)++/**+ * Summary of one modifier group: enough for the assistant to pick valid+ * modifier ids and for the provider to re-validate required/min/max rules.+ */+@Serializable+data class MenuModifierGroupData(+    val id: Int = 0,+    val name: String = "",+    val required: Boolean = false,+    val minSelections: Int = 0,+    val maxSelections: Int = 0,+    val modifiers: List<MenuModifierData> = emptyList(),+)++/** One menu item; [available] is false when unavailable or out of stock. */+@Serializable+data class MenuItemData(+    val id: Int = 0,+    val name: String = "",+    val priceCents: Int = 0,+    val available: Boolean = false,+    val category: String = "",+    val modifierGroups: List<MenuModifierGroupData> = emptyList(),+)++/** One menu category, grouping items by [itemIds]. */+@Serializable+data class MenuCategoryData(+    val id: Int = 0,+    val name: String = "",+    val itemIds: List<Int> = emptyList(),+)++/** A merchant's menu. [error] is a stable code when the menu could not load. */+@Serializable+data class MenuData(+    val merchantId: Int = 0,+    val merchantName: String = "",+    val categories: List<MenuCategoryData> = emptyList(),+    val items: List<MenuItemData> = emptyList(),+    val error: String? = null,+)++/** Read the provider-owned cart. No fields; present for wire symmetry. */+@Serializable+data class GetCart(+    val unused: Boolean = false,+)++/** One cart line as the assistant sees it. [lineTotalCents] includes modifiers. */+@Serializable+data class CartItemData(+    val itemId: Int = 0,+    val name: String = "",+    val qty: Int = 0,+    val modifierIds: List<Int> = emptyList(),+    val lineTotalCents: Int = 0,+)++/**+ * The provider-owned cart (single merchant). [error] is a stable+ * machine-readable code when a preceding [SetCart] was rejected; a rejected+ * write leaves the previous cart untouched.+ */+@Serializable+data class CartData(+    val merchantId: Int = 0,+    val merchantName: String = "",+    val items: List<CartItemData> = emptyList(),+    val totalCents: Int = 0,+    val error: String? = null,+)++/** One line the assistant wants in the cart: menu [itemId], [qty], [modifierIds]. */+@Serializable+data class SetCartItem(+    val itemId: Int = 0,+    val qty: Int = 0,+    val modifierIds: List<Int> = emptyList(),+)++/**+ * Replace the provider cart atomically with [items] from [merchantId].+ *+ * The cart holds a single merchant: writing items for a different merchant+ * replaces the previous cart wholesale (mirroring the in-app "start a new+ * cart" rule). An empty [items] clears the cart. Every line is re-validated+ * provider-side against the live menu (item exists and is available,+ * modifier ids belong to the item, required/min/max selection rules,+ * quantity bounds) before anything is written; on any failure nothing is+ * written and the returned [CartData] carries the error code.+ */+@Serializable+data class SetCart(+    val merchantId: Int = 0,+    val items: List<SetCartItem> = emptyList(),+)++/**+ * Price the current cart for merchant [merchantId] without creating an order.+ * [addressId] refers to a provider-saved address by id (contents never cross+ * the wire); [tipCents] and [promo] are echoed into the summary.+ */+@Serializable+data class PrepareOrder(+    val merchantId: Int = 0,+    val isPickup: Boolean = false,+    val addressId: String? = null,+    val tipCents: Int = 0,+    val promo: String? = null,+)++/**+ * Totals for the current cart, computed provider-side WITHOUT creating an+ * order. There is no server checkout-preview endpoint — the only pricing+ * call (`POST /merchants/{id}/checkout`) creates an order and a Stripe+ * client secret, which the assistant must never touch — so taxes and the+ * delivery fee cannot be known here: [taxesCents] / [deliveryFeeCents] are+ * null when unknown (delivery fee is exactly 0 for pickup), [promo] is+ * echoed but not valued, and [totalCents] is the sum of the known parts+ * (subtotal + tip + known delivery fee). The authoritative total is shown+ * in-app at `fooddelivery://checkout` ([checkoutDeepLink]), where the user+ * places and pays for the order.+ */+@Serializable+data class OrderSummaryData(+    val merchantId: Int = 0,+    val merchantName: String = "",+    val isPickup: Boolean = false,+    val addressId: String? = null,+    val items: List<CartItemData> = emptyList(),+    val subtotalCents: Int = 0,+    val deliveryFeeCents: Int? = null,+    val taxesCents: Int? = null,+    val tipCents: Int = 0,+    val promo: String? = null,+    val totalCents: Int = 0,+    val checkoutDeepLink: String = "fooddelivery://checkout",+    val error: String? = null,+)++/** Read the signed-in customer's past orders. No fields. */+@Serializable+data class GetOrders(+    val unused: Boolean = false,+)++/** One past order as the assistant sees it. */+@Serializable+data class OrderData(+    val id: Int = 0,+    val uuid: String? = null,+    val merchantId: Int = 0,+    val merchantName: String = "",+    val status: String = "",+    val totalCents: Int = 0,+    val itemCount: Int = 0,+    val createdAt: String? = null,+    val isDelivery: Boolean = false,+    val isDone: Boolean = false,+)