shop: detekt clean (58 tests)
- Commit
616fdee6cdc19da48cd9f3f79dbf188324ea0e07- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-15 00:51 UTC (21 days ago)
- Parents
58b77a2
Fix all detekt findings in shop by fixing code, not config (detekt.yml untouched, no baselines added): - UndocumentedPublicClass: KDoc for 73 types. - NativeCheckoutCoordinator: submit decomposed into submitBlocked/previousBlocked/executeWrite/ publishResult with shared cartMatches; wildcard import made explicit. - Checkout validation, hostname labels, tracking merge and status handling decomposed (complexity); backend limits/status codes are named constants; checkStatus throws via failStatus. - MaxLineLength: wrapped signatures, publish calls and data classes across the module. - ProductScreen refresh keeps its broad catch with narrow @Suppress justification. Verified: ./gradlew :shop:detekt :shop:testDevUnitTest :shop:lint --max-workers=32 all pass (58 unit tests).
Diff
shop/src/main/java/com/vayunmathur/shop/MainActivity.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt b/shop/src/main/java/com/vayunmathur/shop/MainActivity.ktindex ca4d749fb1..cbe0542560 100644--- a/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt+++ b/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt@@ -7,6 +7,7 @@ import com.vayunmathur.library.ui.MaActivity import com.vayunmathur.shop.platform.AppInit import com.vayunmathur.shop.platform.ShopViewModel +/** Main Activity: a ma activity implementation for main activity. */ class MainActivity : MaActivity() { private val viewModel: ShopViewModel by viewModels() @@ -35,6 +36,7 @@ class MainActivity : MaActivity() { intent.dataString?.let(viewModel::openLink) } + /** Shared constants and helpers for MainActivity. */ companion object { const val ACTION_SHOW_ORDERS = "com.vayunmathur.shop.action.SHOW_ORDERS" }
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 53ad266097..69741130c8 100644--- a/shop/src/main/java/com/vayunmathur/shop/Route.kt+++ b/shop/src/main/java/com/vayunmathur/shop/Route.kt@@ -3,11 +3,14 @@ package com.vayunmathur.shop import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable +/** Contract for route. */ @Serializable sealed interface Route : NavKey {+ /** Singleton holding search state and operations. */ @Serializable data object Search : Route + /** Immutable value describing product detail. */ @Serializable data class ProductDetail( val variantId: String,@@ -15,9 +18,11 @@ sealed interface Route : NavKey { val shopDomain: String, ) : Route + /** Singleton holding cart state and operations. */ @Serializable data object Cart : Route + /** Singleton holding orders state and operations. */ @Serializable data object Orders : Route
shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.kt b/shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.ktindex 0741b35188..1b903b04c6 100644--- a/shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.kt+++ b/shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.kt@@ -15,22 +15,56 @@ data class CheckoutInputs( val options: Map<String, String> = emptyMap(), val shippingRequested: Boolean = false, ) {- val hasAddress: Boolean get() = listOf(street, extendedAddress, city, region, country, postalCode).any { it.isNotBlank() }+ val hasAddress: Boolean get() =+ listOf(street, extendedAddress, city, region, country, postalCode).any { it.isNotBlank() }+ fun validationError(): String? = when {- email.isNotBlank() && !Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$").matches(email) -> "Enter a valid email address."- phone.isNotBlank() && !Regex("^\\+[1-9][0-9]{1,14}$").matches(phone) -> "Use an international phone number, such as +14155550123."+ email.isNotBlank() && !EMAIL_REGEX.matches(email) -> "Enter a valid email address."+ phone.isNotBlank() && !PHONE_REGEX.matches(phone) ->+ "Use an international phone number, such as +14155550123." shippingRequested && !hasAddress -> "Provide an address for merchant shipping."- hasAddress && (street.isBlank() || city.isBlank() || !Regex("^[A-Z]{2}$").matches(country)) -> "Provide a street, city and two-letter uppercase country code."- hasAddress && country in setOf("US", "CA") && (region.isBlank() || postalCode.isBlank()) -> "Provide a state or province and postal code."+ hasAddress && addressError() != null -> addressError() else -> null }++ /** The address-specific validation error, or null when the address is usable. */+ private fun addressError(): String? = when {+ street.isBlank() || city.isBlank() || !COUNTRY_REGEX.matches(country) ->+ "Provide a street, city and two-letter uppercase country code."+ country in setOf("US", "CA") && (region.isBlank() || postalCode.isBlank()) ->+ "Provide a state or province and postal code."+ else -> null+ }++ private companion object {+ val EMAIL_REGEX = Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")+ val PHONE_REGEX = Regex("^\\+[1-9][0-9]{1,14}$")+ val COUNTRY_REGEX = Regex("^[A-Z]{2}$")+ } override fun toString(): String = "CheckoutInputs(redacted)" } +/** Immutable value describing checkout legal link; carries type, title, url. */ data class CheckoutLegalLink(val type: String, val title: String, val url: String)-data class CheckoutShippingOption(val id: String, val title: String, val description: String, val totals: List<UcpTotalEntry>)-data class CheckoutShippingGroup(val id: String, val selectedOptionId: String?, val options: List<CheckoutShippingOption>)-data class CheckoutShippingMethod(val id: String, val groups: List<CheckoutShippingGroup>)+/** Immutable value describing checkout shipping option; carries id, title, description, totals. */+data class CheckoutShippingOption(+ val id: String,+ val title: String,+ val description: String,+ val totals: List<UcpTotalEntry>,+)+/** Immutable value describing checkout shipping group; carries id, selectedOptionId, options. */+data class CheckoutShippingGroup(+ val id: String,+ val selectedOptionId: String?,+ val options: List<CheckoutShippingOption>,+)+/** Immutable value describing checkout shipping method; carries id, groups. */+data class CheckoutShippingMethod(+ val id: String,+ val groups: List<CheckoutShippingGroup>,+)+/** Immutable value describing checkout review. */ data class CheckoutReview( val shipping: List<CheckoutShippingMethod> = emptyList(), val links: List<CheckoutLegalLink> = emptyList(),@@ -38,7 +72,9 @@ data class CheckoutReview( val availableShippingLineIds: List<String> = emptyList(), ) +/** Kinds of checkout phase. */ enum class CheckoutPhase { Preparing, Reviewing, Updating, BrowserRequired, Error, Expired, Uncertain }+/** Immutable value describing native checkout state. */ data class NativeCheckoutState( val platformId: String, val shopDomain: String,
shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.kt b/shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.ktindex 4640c31275..95786473cb 100644--- a/shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.kt+++ b/shop/src/main/java/com/vayunmathur/shop/data/ProfileDatabase.kt@@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.Flow const val PROFILE_DB_NAME = "shop-profile-db" +/** Contract for profile dao. */ @Dao interface ProfileDao { @Query("SELECT * FROM ShopProfile WHERE id = 0")@@ -18,6 +19,7 @@ interface ProfileDao { suspend fun upsert(profile: ShopProfile) } +/** Profile Database: a room database implementation for profile database. */ @Database(entities = [ShopProfile::class], version = 1, exportSchema = false) abstract class ProfileDatabase : RoomDatabase() { abstract fun profileDao(): ProfileDao
shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.kt b/shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.ktindex ebb3568560..fda7779b04 100644--- a/shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.kt+++ b/shop/src/main/java/com/vayunmathur/shop/data/ProfileRepository.kt@@ -4,6 +4,7 @@ import android.content.Context import com.vayunmathur.library.room.RoomRepository import kotlinx.coroutines.flow.Flow +/** Profile Repository: a context implementation for profile repository. */ class ProfileRepository private constructor(context: Context) : RoomRepository<ProfileDatabase>(context, ProfileDatabase::class, PROFILE_DB_NAME) { @@ -11,6 +12,7 @@ class ProfileRepository private constructor(context: Context) : suspend fun save(profile: ShopProfile) = db.profileDao().upsert(profile.copy(id = 0)) + /** Shared constants and helpers for ProfileRepository. */ companion object { @Volatile private var instance: ProfileRepository? = null fun get(context: Context): ProfileRepository =
shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt b/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.ktindex 25a27cfc1c..bb9804fe69 100644--- a/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt+++ b/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt@@ -8,12 +8,15 @@ import kotlinx.serialization.json.JsonObject @Serializable data class Money(val amount: Long = 0, val currency: String = "USD") +/** Immutable value describing product image; carries url, alt. */ @Serializable data class ProductImage(val url: String = "", val alt: String? = null) +/** Immutable value describing catalog option selection; carries name, label, id. */ @Serializable data class CatalogOptionSelection(val name: String, val label: String, val id: String? = null) +/** Immutable value describing product variant. */ @Serializable data class ProductVariant( val id: String = "",@@ -27,6 +30,7 @@ data class ProductVariant( val selectedOptions: List<CatalogOptionSelection> = emptyList(), ) +/** Immutable value describing ucp product. */ @Serializable data class UcpProduct( val id: String = "",@@ -44,6 +48,7 @@ data class UcpProduct( val priceRangeMax: Money? = null, ) +/** Immutable value describing cart line. */ @Serializable data class CartLine( val variantId: String = "",@@ -59,6 +64,7 @@ data class CartLine( val displayName: String get() = storeName.ifBlank { shopDomain } } +/** Immutable value describing ucp totals. */ @Serializable data class UcpTotals( val subtotal: Money = Money(),@@ -67,16 +73,25 @@ data class UcpTotals( val total: Money = Money(), ) +/** Immutable value describing ucp total entry; carries type, label, money. */ @Serializable data class UcpTotalEntry(val type: String, val label: String, val money: Money) +/** Immutable value describing ucp message; carries type, text, path, code, severity. */ @Serializable-data class UcpMessage(val type: String = "", val text: String = "", val path: String? = null, val code: String? = null, val severity: String? = null)+data class UcpMessage(+ val type: String = "",+ val text: String = "",+ val path: String? = null,+ val code: String? = null,+ val severity: String? = null,+) /** Server-echoed cart fingerprint: the variant ids + quantities the proxy sent to the merchant. */ @Serializable data class SubmittedLine(val variantId: String = "", val quantity: Int = 0) +/** Immutable value describing ucp checkout. */ @Serializable data class UcpCheckout( val checkoutId: String = "",@@ -98,6 +113,7 @@ data class UcpCheckout( override fun toString(): String = "UcpCheckout(redacted)" } +/** Immutable value describing order shipment. */ @Serializable data class OrderShipment( val trackingNumber: String? = null,@@ -153,12 +169,19 @@ data class PlacedOrder( val displayName: String get() = storeName.ifBlank { shopDomain } } +/** Contract for ucp error. */ sealed interface UcpError {+ /** Immutable value describing transport; carries reason. */ data class Transport(val reason: String) : UcpError+ /** Immutable value describing rate limited; carries retryAfterMs. */ data class RateLimited(val retryAfterMs: Long?) : UcpError+ /** Immutable value describing http; carries status, snippet. */ data class Http(val status: Int, val snippet: String) : UcpError+ /** Immutable value describing malformed; carries reason. */ data class Malformed(val reason: String) : UcpError+ /** Immutable value describing rpc; carries message. */ data class Rpc(val message: String) : UcpError+ /** Immutable value describing unsupported; carries reason, continueUrl. */ data class Unsupported(val reason: String, val continueUrl: String? = null) : UcpError }
shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.kt b/shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.ktindex f906e3fd5f..494aefa3e4 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/EmbeddedCheckout.kt@@ -14,10 +14,15 @@ import kotlinx.serialization.json.put /** What the host should do with one message from the merchant's Embedded Checkout. */ sealed interface EcAction {+ /** Immutable value describing reply; carries json. */ data class Reply(val json: String) : EcAction+ /** Immutable value describing open window; carries id, url. */ data class OpenWindow(val id: JsonElement, val url: String) : EcAction+ /** Immutable value describing completed; carries orderId, permalinkUrl, totalMinor. */ data class Completed(val orderId: String, val permalinkUrl: String?, val totalMinor: Long?) : EcAction+ /** Immutable value describing failed; carries message. */ data class Failed(val message: String) : EcAction+ /** Singleton holding ignore state and operations. */ data object Ignore : EcAction }
shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.kt b/shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.ktindex 5f7d5eb92d..0dfe2312ab 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.kt@@ -8,11 +8,15 @@ import java.util.Locale sealed interface MerchantLink { val host: String + /** Immutable value describing product; carries host, handle. */ data class Product(override val host: String, val handle: String) : MerchantLink+ /** Immutable value describing search; carries host, query. */ data class Search(override val host: String, val query: String) : MerchantLink+ /** Immutable value describing merchant; carries host. */ data class Merchant(override val host: String) : MerchantLink } +/** Singleton holding merchant links state and operations. */ object MerchantLinks { private val handlePattern = Regex("^[a-z0-9][a-z0-9-]{0,199}$") private val webSchemes = setOf("https", "http")
shop/src/main/java/com/vayunmathur/shop/domain/MerchantUrls.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/MerchantUrls.kt b/shop/src/main/java/com/vayunmathur/shop/domain/MerchantUrls.ktindex 3bb50cc011..7737d7a3c4 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/MerchantUrls.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/MerchantUrls.kt@@ -22,13 +22,19 @@ object MerchantUrls { return uri.host.lowercase(Locale.US) } +private const val MAX_LABEL_LENGTH = 63++/** One DNS label: alphanumeric ends, alphanumeric-or-dash inside, at most 63 chars. */+ private fun validLabel(label: String): Boolean {+ if (label.isEmpty() || label.length > MAX_LABEL_LENGTH) return false+ if (!label.first().isLetterOrDigit() || !label.last().isLetterOrDigit()) return false+ return label.all { it in 'a'..'z' || it.isDigit() || it == '-' }+ }+ private fun publicHostname(host: String): Boolean {- if (!host.contains('.') || host.contains(':') || host.all { it.isDigit() || it == '.' }) return false+ val numericOnly = host.all { it.isDigit() || it == '.' }+ if (!host.contains('.') || host.contains(':') || numericOnly) return false if (host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) return false- return host.split('.').all { label ->- label.isNotEmpty() && label.length <= 63 &&- label.first().isLetterOrDigit() && label.last().isLetterOrDigit() &&- label.all { it in 'a'..'z' || it.isDigit() || it == '-' }- }+ return host.split('.').all { label -> validLabel(label) } } }
shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.ktindex 05c0fdfbc1..4c8a2ec95b 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt@@ -1,6 +1,13 @@ package com.vayunmathur.shop.domain -import com.vayunmathur.shop.data.*+import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.CheckoutPhase+import com.vayunmathur.shop.data.NativeCheckoutState+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.UcpCheckout+import com.vayunmathur.shop.data.SubmittedLine+import com.vayunmathur.shop.data.UcpError import com.vayunmathur.shop.network.ShopBackend import com.vayunmathur.shop.network.ShopBackendException import com.vayunmathur.shop.network.ShopHttpBackend@@ -11,17 +18,39 @@ import java.util.UUID /** Deliberately has no completion operation. Tests never need a merchant or payment credentials. */ internal interface NativeCheckoutGateway {- suspend fun create(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout>- suspend fun update(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout>+ suspend fun create(+ shop: String,+ lines: List<CartLine>,+ inputs: CheckoutInputs,+ intent: String,+ ): Result<UcpCheckout>+ suspend fun update(+ shop: String,+ sessionId: String,+ lines: List<CartLine>,+ inputs: CheckoutInputs,+ intent: String,+ ): Result<UcpCheckout> suspend fun get(shop: String, sessionId: String): Result<UcpCheckout> } internal class ServerCheckoutGateway( private val backend: ShopBackend = ShopHttpBackend, ) : NativeCheckoutGateway {- override suspend fun create(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout> =+ override suspend fun create(+ shop: String,+ lines: List<CartLine>,+ inputs: CheckoutInputs,+ intent: String,+ ): Result<UcpCheckout> = backend.createCheckout(shop, lines, inputs, intent)- override suspend fun update(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout> =+ override suspend fun update(+ shop: String,+ sessionId: String,+ lines: List<CartLine>,+ inputs: CheckoutInputs,+ intent: String,+ ): Result<UcpCheckout> = backend.updateCheckout(shop, sessionId, lines, inputs, intent) override suspend fun get(shop: String, sessionId: String): Result<UcpCheckout> = backend.getCheckout(shop, sessionId)@@ -30,6 +59,8 @@ internal class ServerCheckoutGateway( internal fun interface PendingCheckoutSink { suspend fun save(order: PlacedOrder) } /** Single-owner ephemeral state; mutex guards each merchant against overlapping writes and reads. */+private const val MAX_QUANTITY = 99+ internal class NativeCheckoutCoordinator( private val gateway: NativeCheckoutGateway = ServerCheckoutGateway(), private val now: () -> Long = System::currentTimeMillis,@@ -41,7 +72,10 @@ internal class NativeCheckoutCoordinator( private val createdAt = mutableMapOf<Pair<String, String>, Long>() val snapshot: List<NativeCheckoutState> get() = states.values.toList() - private fun publish(key: Pair<String, String>, state: NativeCheckoutState) { states[key] = state; changed(snapshot) }+ private fun publish(key: Pair<String, String>, state: NativeCheckoutState) {+ states[key] = state+ changed(snapshot)+ } fun edit(platform: String, shop: String, inputs: CheckoutInputs) { val key = platform to shop@@ -51,9 +85,20 @@ internal class NativeCheckoutCoordinator( fun cartChanged(lines: List<CartLine>) { states.toMap().forEach { (key, state) ->- if (state.checkout != null && state.submittedLines != lines.filter { it.platformId == key.first && it.shopDomain == key.second }) {- publish(key, state.copy(phase = if (state.phase == CheckoutPhase.Uncertain) CheckoutPhase.Uncertain else CheckoutPhase.BrowserRequired,- message = "The cart changed. This session no longer represents your cart; review it on the merchant website."))+ val cartForKey = lines.filter { it.platformId == key.first && it.shopDomain == key.second }+ if (state.checkout != null && state.submittedLines != cartForKey) {+ publish(+ key,+ state.copy(+ phase = if (state.phase == CheckoutPhase.Uncertain) {+ CheckoutPhase.Uncertain+ } else {+ CheckoutPhase.BrowserRequired+ },+ message = "The cart changed. This session no longer represents your cart; " ++ "review it on the merchant website.",+ ),+ ) } } }@@ -66,8 +111,16 @@ internal class NativeCheckoutCoordinator( fun refreshExpiry() { states.toMap().forEach { (key, state) ->- if (!state.busy && state.checkout != null && state.phase != CheckoutPhase.Uncertain && expired(key, state.checkout)) {- publish(key, state.copy(phase = CheckoutPhase.Expired, message = "This checkout session expired. Continue on the merchant website."))+ val checkout = state.checkout+ val expirable = !state.busy && state.phase != CheckoutPhase.Uncertain+ if (checkout != null && expirable && expired(key, checkout)) {+ publish(+ key,+ state.copy(+ phase = CheckoutPhase.Expired,+ message = "This checkout session expired. Continue on the merchant website.",+ ),+ ) } } }@@ -76,6 +129,173 @@ internal class NativeCheckoutCoordinator( runCatching { Instant.parse(it).toEpochMilli() <= now() }.getOrDefault(true) } ?: (now() - (createdAt[key] ?: now()) !in 0 until 6 * 60 * 60 * 1000L) ++ /** True when [submitted] lines match [lines] by variant and quantity. */+ private fun cartMatches(+ submitted: List<SubmittedLine>,+ lines: List<CartLine>,+ ): Boolean = submitted.size == lines.size &&+ submitted.all { sub ->+ lines.any { it.variantId == sub.variantId && it.quantity == sub.quantity }+ }++ /** Guards a submit; publishes the refusal reason and returns true when blocked. */+ private fun submitBlocked(+ key: Pair<String, String>,+ state: NativeCheckoutState,+ platform: String,+ shop: String,+ lines: List<CartLine>,+ ): Boolean {+ if (state.phase in setOf(CheckoutPhase.Uncertain, CheckoutPhase.BrowserRequired, CheckoutPhase.Expired)) {+ return true+ }+ if (lines.isEmpty() || lines.any { it.shopDomain != shop || it.platformId != platform }) return true+ if (lines.any { it.quantity !in 1..MAX_QUANTITY }) return true+ state.inputs.validationError()?.let {+ publish(key, state.copy(phase = CheckoutPhase.Error, message = it))+ return true+ }+ return previousBlocked(key, state, lines)+ }++ /** Previous-session guards for a submit; publishes the refusal and returns true when blocked. */+ private fun previousBlocked(+ key: Pair<String, String>,+ state: NativeCheckoutState,+ lines: List<CartLine>,+ ): Boolean {+ val previous = state.checkout+ if (previous != null && expired(key, previous)) {+ publish(+ key,+ state.copy(+ phase = CheckoutPhase.Expired,+ message = "This session expired. Continue on the merchant website.",+ ),+ )+ return true+ }+ if (previous != null && state.submittedLines != lines) {+ publish(+ key,+ state.copy(+ phase = CheckoutPhase.BrowserRequired,+ message = "The session's cart changed. Continue on the merchant website.",+ ),+ )+ return true+ }+ if (previous != null && state.submittedInputs == state.inputs) return true+ if (previous != null && state.submittedInputs?.hasAddress == true && !state.inputs.hasAddress) {+ publish(+ key,+ state.copy(+ phase = CheckoutPhase.BrowserRequired,+ message = "Removing a submitted shipping address requires the merchant website.",+ ),+ )+ return true+ }+ return false+ }++ /** The single attempted write for a submit; publishes the refusal and returns null on failure. */+ private suspend fun executeWrite(+ key: Pair<String, String>,+ state: NativeCheckoutState,+ previous: UcpCheckout?,+ shop: String,+ lines: List<CartLine>,+ ): UcpCheckout? {+ // The server builds the exact dated projection and owns the idempotency+ // ledger: a write is attempted exactly once and never auto-retried.+ // The first write carries the whole profile (name, contact and address); only+ // shipping-option choices wait until the merchant has offered them.+ val sentInputs = if (previous == null) state.inputs.copy(options = emptyMap()) else state.inputs+ val intent = newIntent()+ val checkout = (if (previous == null) {+ gateway.create(shop, lines.toList(), sentInputs, intent)+ } else {+ gateway.update(shop, previous.checkoutId, lines.toList(), sentInputs, intent)+ }).getOrElse {+ val unsupported = (it as? ShopBackendException)?.error as? UcpError.Unsupported+ publish(+ key,+ state.copy(+ phase = if (unsupported != null) CheckoutPhase.BrowserRequired else CheckoutPhase.Uncertain,+ handoffUrl = unsupported?.continueUrl?.let(MerchantUrls::httpsUrl),+ message = unsupported?.reason+ ?: ("The request may have reached the merchant. " ++ "Do not retry; check the session or use its website."),+ ),+ )+ return null+ }+ if (previous != null && checkout.checkoutId != previous.checkoutId) {+ publish(+ key,+ state.copy(+ phase = CheckoutPhase.Uncertain,+ message = "The merchant returned a different session. Do not retry.",+ ),+ )+ return null+ }+ createdAt.putIfAbsent(key, now())+ return checkout+ }++ /** Publishes the post-write state and persists the pending-order projection. */+ private suspend fun publishResult(+ key: Pair<String, String>,+ state: NativeCheckoutState,+ previous: UcpCheckout?,+ checkout: UcpCheckout,+ lines: List<CartLine>,+ sink: PendingCheckoutSink,+ ) {+ val sentInputs = if (previous == null) state.inputs.copy(options = emptyMap()) else state.inputs+ val responseMatchesCart = cartMatches(checkout.submittedLines, lines)+ val reason = checkout.review.browserOnlyReason ?: if (!responseMatchesCart) {+ "The merchant returned changed or unsupported line items. Review them on its website."+ } else {+ null+ }+ val next = state.copy(+ checkout = checkout,+ submittedInputs = sentInputs,+ submittedLines = lines.toList(),+ phase = if (expired(key, checkout)) {+ CheckoutPhase.Expired+ } else if (reason != null) {+ CheckoutPhase.BrowserRequired+ } else {+ CheckoutPhase.Reviewing+ },+ message = reason,+ )+ publish(key, next)+ // Persist only the existing pending history projection, never buyer, address, messages or raw response.+ sink.save(+ PlacedOrder(+ checkoutId = checkout.checkoutId,+ placedAtMs = now(),+ total = checkout.totals.total,+ itemCount = lines.sumOf { it.quantity },+ continueUrl = MerchantUrls.httpsUrl(checkout.continueUrl).orEmpty(),+ status = "pending",+ platformId = key.first,+ shopDomain = key.second,+ storeName = lines.firstNotNullOfOrNull { it.storeName.ifBlank { null } }.orEmpty(),+ lines = lines.map { it.copy(imageUrl = "") },+ trackingToken = checkout.trackingToken,+ totalEntries = checkout.totalEntries.map { it.copy(label = it.type) },+ expiresAt = checkout.expiresAt,+ version = checkout.version,+ ),+ )+ } suspend fun submit(platform: String, shop: String, lines: List<CartLine>, sink: PendingCheckoutSink) { val key = platform to shop val lock = locks.getOrPut(key) { Mutex() }@@ -83,66 +303,48 @@ internal class NativeCheckoutCoordinator( var mutationStarted = false try { val state = states[key] ?: NativeCheckoutState(platform, shop)- if (state.phase in setOf(CheckoutPhase.Uncertain, CheckoutPhase.BrowserRequired, CheckoutPhase.Expired)) return- if (lines.isEmpty() || lines.any { it.shopDomain != shop || it.platformId != platform || it.quantity !in 1..99 }) return- state.inputs.validationError()?.let { publish(key, state.copy(phase = CheckoutPhase.Error, message = it)); return }+ if (submitBlocked(key, state, platform, shop, lines)) return val previous = state.checkout- if (previous != null && expired(key, previous)) {- publish(key, state.copy(phase = CheckoutPhase.Expired, message = "This session expired. Continue on the merchant website.")); return- }- if (previous != null && state.submittedLines != lines) {- publish(key, state.copy(phase = CheckoutPhase.BrowserRequired, message = "The session's cart changed. Continue on the merchant website.")); return- }- if (previous != null && state.submittedInputs == state.inputs) return- if (previous != null && state.submittedInputs?.hasAddress == true && !state.inputs.hasAddress) {- publish(key, state.copy(phase = CheckoutPhase.BrowserRequired, message = "Removing a submitted shipping address requires the merchant website.")); return- }- publish(key, state.copy(phase = if (previous == null) CheckoutPhase.Preparing else CheckoutPhase.Updating, message = null))- // The server builds the exact dated projection and owns the idempotency- // ledger: a write is attempted exactly once and never auto-retried.- // The first write carries the whole profile (name, contact and address); only- // shipping-option choices wait until the merchant has offered them.- val sentInputs = if (previous == null) state.inputs.copy(options = emptyMap()) else state.inputs- val intent = newIntent()+ publish(+ key,+ state.copy(+ phase = if (previous == null) CheckoutPhase.Preparing else CheckoutPhase.Updating,+ message = null,+ ),+ ) mutationStarted = true- val checkout = (if (previous == null) gateway.create(shop, lines.toList(), sentInputs, intent)- else gateway.update(shop, previous.checkoutId, lines.toList(), sentInputs, intent)).getOrElse {- val unsupported = (it as? ShopBackendException)?.error as? UcpError.Unsupported- publish(key, state.copy(- phase = if (unsupported != null) CheckoutPhase.BrowserRequired else CheckoutPhase.Uncertain,- handoffUrl = unsupported?.continueUrl?.let(MerchantUrls::httpsUrl),- message = unsupported?.reason- ?: ("The request may have reached the merchant. " +- "Do not retry; check the session or use its website."),- ))- return- }- if (previous != null && checkout.checkoutId != previous.checkoutId) {- publish(key, state.copy(phase = CheckoutPhase.Uncertain, message = "The merchant returned a different session. Do not retry.")); return- }- createdAt.putIfAbsent(key, now())- val responseMatchesCart = checkout.submittedLines.size == lines.size &&- checkout.submittedLines.all { submitted ->- lines.any { it.variantId == submitted.variantId && it.quantity == submitted.quantity }- }- val reason = checkout.review.browserOnlyReason ?: if (!responseMatchesCart) "The merchant returned changed or unsupported line items. Review them on its website." else null- val next = state.copy(checkout = checkout, submittedInputs = sentInputs, submittedLines = lines.toList(),- phase = if (expired(key, checkout)) CheckoutPhase.Expired else if (reason != null) CheckoutPhase.BrowserRequired else CheckoutPhase.Reviewing,- message = reason)- publish(key, next)- // Persist only the existing pending history projection, never buyer, address, messages or raw response.- sink.save(PlacedOrder(checkoutId = checkout.checkoutId, placedAtMs = now(), total = checkout.totals.total,- itemCount = lines.sumOf { it.quantity }, continueUrl = MerchantUrls.httpsUrl(checkout.continueUrl).orEmpty(),- status = "pending", platformId = platform, shopDomain = shop, storeName = lines.firstNotNullOfOrNull { it.storeName.ifBlank { null } }.orEmpty(),- lines = lines.map { it.copy(imageUrl = "") }, trackingToken = checkout.trackingToken,- totalEntries = checkout.totalEntries.map { it.copy(label = it.type) }, expiresAt = checkout.expiresAt, version = checkout.version))+ val checkout = executeWrite(key, state, previous, shop, lines) ?: return+ publishResult(key, state, previous, checkout, lines, sink) } catch (cancelled: CancellationException) {- if (mutationStarted) states[key]?.let { publish(key, it.copy(phase = CheckoutPhase.Uncertain, message = "Request interrupted. Do not retry; use the merchant website.")) }+ if (mutationStarted) {+ states[key]?.let {+ publish(+ key,+ it.copy(+ phase = CheckoutPhase.Uncertain,+ message = "Request interrupted. Do not retry; use the merchant website.",+ ),+ )+ }+ } throw cancelled } catch (_: Exception) {- states[key]?.let { publish(key, it.copy(phase = if (mutationStarted) CheckoutPhase.Uncertain else CheckoutPhase.Error,- message = if (mutationStarted) "The session may have changed. Do not retry; use the merchant website." else "Checkout is unavailable.")) }- } finally { lock.unlock() }+ states[key]?.let {+ publish(+ key,+ it.copy(+ phase = if (mutationStarted) CheckoutPhase.Uncertain else CheckoutPhase.Error,+ message = if (mutationStarted) {+ "The session may have changed. Do not retry; use the merchant website."+ } else {+ "Checkout is unavailable."+ },+ ),+ )+ }+ } finally {+ lock.unlock()+ } } suspend fun reconcile(platform: String, shop: String) {@@ -155,14 +357,32 @@ internal class NativeCheckoutCoordinator( val refreshed = gateway.get(shop, checkout.checkoutId).getOrNull() ?: return if (refreshed.checkoutId != checkout.checkoutId) return // A GET can show authoritative review but cannot prove that an uncertain write was applied.- val responseMatchesCart = refreshed.submittedLines.isEmpty() || (refreshed.submittedLines.size == state.submittedLines.size &&- refreshed.submittedLines.all { submitted ->- state.submittedLines.any { it.variantId == submitted.variantId && it.quantity == submitted.quantity }- })- val browserReason = refreshed.review.browserOnlyReason ?: if (!responseMatchesCart) "The merchant session's line items changed. Continue on its website." else null- publish(key, state.copy(checkout = refreshed,- phase = if (state.phase == CheckoutPhase.Uncertain) CheckoutPhase.Uncertain else if (browserReason != null) CheckoutPhase.BrowserRequired else state.phase,- message = if (state.phase == CheckoutPhase.Uncertain) "Session refreshed. The uncertain write will not be replayed; continue on the merchant website." else browserReason ?: state.message))+ val responseMatchesCart = refreshed.submittedLines.isEmpty() ||+ cartMatches(refreshed.submittedLines, state.submittedLines)+ val browserReason = refreshed.review.browserOnlyReason ?: if (!responseMatchesCart) {+ "The merchant session's line items changed. Continue on its website."+ } else {+ null+ }+ publish(+ key,+ state.copy(+ checkout = refreshed,+ phase = if (state.phase == CheckoutPhase.Uncertain) {+ CheckoutPhase.Uncertain+ } else if (browserReason != null) {+ CheckoutPhase.BrowserRequired+ } else {+ state.phase+ },+ message = if (state.phase == CheckoutPhase.Uncertain) {+ "Session refreshed. The uncertain write will not be replayed; " ++ "continue on the merchant website."+ } else {+ browserReason ?: state.message+ },+ ),+ ) refreshExpiry() } finally { lock.unlock() } }
shop/src/main/java/com/vayunmathur/shop/domain/OrderTrackingUpdates.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/OrderTrackingUpdates.kt b/shop/src/main/java/com/vayunmathur/shop/domain/OrderTrackingUpdates.ktindex 13d6abe726..be04b4d7cf 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/OrderTrackingUpdates.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/OrderTrackingUpdates.kt@@ -15,6 +15,7 @@ object OrderTrackingUpdates { .take(MAX_TOKENS) .map { OrderStatusQuery(it.trackingToken, it.orderId.ifBlank { null }) } + /** Immutable value describing merge; carries orders, changed. */ data class Merge(val orders: List<PlacedOrder>, val changed: List<PlacedOrder>) /** Applies newer tracking; [Merge.changed] holds orders whose status moved past the initial confirmation. */@@ -23,7 +24,8 @@ object OrderTrackingUpdates { val merged = orders.map { order -> val update = updates[order.trackingToken] val previous = order.tracking- if (order.trackingToken.isBlank() || update == null || (previous != null && previous.updatedAtMs > update.updatedAtMs)) {+ val stale = previous != null && update != null && previous.updatedAtMs > update.updatedAtMs+ if (order.trackingToken.isBlank() || update == null || stale) { return@map order } val next = order.copy(tracking = update, orderId = order.orderId.ifBlank { update.orderId })
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 aa13996b17..d78058f983 100644--- a/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt+++ b/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt@@ -31,7 +31,12 @@ import java.net.URLEncoder * write → uncertain (never auto-retried). */ interface ShopBackend {- suspend fun search(query: String, shop: String? = null, limit: Int = 20, country: String = "US"): Result<List<UcpProduct>>+ suspend fun search(+ query: String,+ shop: String? = null,+ limit: Int = 20,+ country: String = "US",+ ): Result<List<UcpProduct>> suspend fun getProduct( shop: String, productId: String,@@ -40,9 +45,20 @@ interface ShopBackend { selectedOptions: List<CatalogOptionSelection> = emptyList(), ): Result<UcpProduct> suspend fun getProductByHandle(shop: String, handle: String): Result<UcpProduct>- suspend fun createCheckout(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout>+ suspend fun createCheckout(+ shop: String,+ lines: List<CartLine>,+ inputs: CheckoutInputs,+ idempotencyKey: String,+ ): Result<UcpCheckout> suspend fun getCheckout(shop: String, sessionId: String): Result<UcpCheckout>- suspend fun updateCheckout(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout>+ suspend fun updateCheckout(+ shop: String,+ sessionId: String,+ lines: List<CartLine>,+ inputs: CheckoutInputs,+ idempotencyKey: String,+ ): Result<UcpCheckout> /** Latest tracking per token; tokens without a merchant update yet are omitted. */ suspend fun orderStatus(orders: List<OrderStatusQuery>): Result<Map<String, OrderTracking>> /**@@ -53,12 +69,17 @@ interface ShopBackend { suspend fun merchantFor(host: String): Result<MerchantListing?> } +/** Shop Backend Exception: a ucp error implementation for shop backend exception. */ class ShopBackendException(val error: UcpError) : Exception(error.toString()) internal object ShopHttpBackend : ShopBackend { internal const val BASE = "https://api.maproj.org/shop/v1" internal val json = Json { ignoreUnknownKeys = true; encodeDefaults = true; explicitNulls = false }- internal var request: suspend (method: String, url: String, body: String?) -> BackendRawResponse = { method, url, body ->+ internal var request: suspend (+ method: String,+ url: String,+ body: String?,+ ) -> BackendRawResponse = { method, url, body -> val response = withTimeout(30_000) { NetworkClient.execute( url, method,@@ -77,8 +98,8 @@ internal object ShopHttpBackend : ShopBackend { override suspend fun search(query: String, shop: String?, limit: Int, country: String): Result<List<UcpProduct>> = catching {- require(query.isNotBlank() && query.length <= 200) { "Invalid query" }- require(limit in 1..50) { "Invalid limit" }+ require(query.isNotBlank() && query.length <= MAX_QUERY_LENGTH) { "Invalid query" }+ require(limit in 1..MAX_SEARCH_LIMIT) { "Invalid limit" } require(country.matches(Regex("^[A-Z]{2}$"))) { "Invalid country" } val url = buildString { append("$BASE/search?query=").append(query.encode())@@ -119,11 +140,22 @@ internal object ShopHttpBackend : ShopBackend { get(url).parse<ShopProductResponse>().product.toModel() } - override suspend fun createCheckout(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout> =+ override suspend fun createCheckout(+ shop: String,+ lines: List<CartLine>,+ inputs: CheckoutInputs,+ idempotencyKey: String,+ ): Result<UcpCheckout> = catching { checkLines(lines, shop)- require(idempotencyKey.isNotBlank() && idempotencyKey.length <= 256) { "Invalid idempotency key" }- val request = ShopCreateCheckoutRequest(shop, lines.map { it.toRequestLine() }, inputs.toRequestInputs(), idempotencyKey)+ require(idempotencyKey.isNotBlank()) { "Invalid idempotency key" }+ require(idempotencyKey.length <= MAX_IDEMPOTENCY_KEY_LENGTH) { "Invalid idempotency key" }+ val request = ShopCreateCheckoutRequest(+ shop,+ lines.map { it.toRequestLine() },+ inputs.toRequestInputs(),+ idempotencyKey,+ ) post("$BASE/checkout-sessions", json.encodeToString(request)).parseSession() } @@ -142,8 +174,15 @@ internal object ShopHttpBackend : ShopBackend { ): Result<UcpCheckout> = catching { checkLines(lines, shop) require(sessionId.isNotBlank()) { "Invalid checkout request" }- require(idempotencyKey.isNotBlank() && idempotencyKey.length <= 256) { "Invalid idempotency key" }- val request = ShopUpdateCheckoutRequest(shop, sessionId, lines.map { it.toRequestLine() }, inputs.toRequestInputs(), idempotencyKey)+ require(idempotencyKey.isNotBlank()) { "Invalid idempotency key" }+ require(idempotencyKey.length <= MAX_IDEMPOTENCY_KEY_LENGTH) { "Invalid idempotency key" }+ val request = ShopUpdateCheckoutRequest(+ shop,+ sessionId,+ lines.map { it.toRequestLine() },+ inputs.toRequestInputs(),+ idempotencyKey,+ ) put("$BASE/checkout-sessions", json.encodeToString(request)).parseSession() } @@ -162,22 +201,35 @@ internal object ShopHttpBackend : ShopBackend { override suspend fun merchantFor(host: String): Result<MerchantListing?> = catching {- require(host.isNotBlank() && host.length <= 253) { "Invalid merchant host" }+ require(host.isNotBlank() && host.length <= MAX_HOST_LENGTH) { "Invalid merchant host" } try { get("$BASE/merchant?host=${host.encode()}").parse<ShopMerchant>().toModel() } catch (error: ShopBackendException) { // Unknown host: the caller falls back to the raw link host. val http = error.error as? UcpError.Http- if (http?.status == 404) null else throw error+ if (http?.status == HTTP_NOT_FOUND) null else throw error } } + private const val MAX_QUERY_LENGTH = 200+ private const val MAX_SEARCH_LIMIT = 50+ private const val MAX_HOST_LENGTH = 253+ private const val MAX_IDEMPOTENCY_KEY_LENGTH = 256+ private const val MAX_QUANTITY = 99+ private const val HTTP_OK_MIN = 200+ private const val HTTP_OK_MAX = 299+ private const val HTTP_NOT_FOUND = 404+ private const val HTTP_TOO_MANY_REQUESTS = 429+ private const val MILLIS_PER_SECOND = 1_000L private const val MAX_STATUS_TOKENS = 50 private const val MAX_ORDER_ID_LENGTH = 500 private val TOKEN = Regex("^[0-9a-f]{32}$") private fun checkLines(lines: List<CartLine>, shop: String) {- require(lines.isNotEmpty() && lines.all { it.shopDomain == shop && it.quantity in 1..99 }) { "Invalid checkout lines" }+ require(lines.isNotEmpty()) { "Invalid checkout lines" }+ require(lines.all { it.shopDomain == shop && it.quantity in 1..MAX_QUANTITY }) {+ "Invalid checkout lines"+ } } private suspend fun get(url: String): BackendRawResponse = request("GET", url, null)@@ -187,29 +239,49 @@ internal object ShopHttpBackend : ShopBackend { private inline fun <reified T> BackendRawResponse.parse(): T { checkStatus() return runCatching { json.decodeFromString<T>(body) }- .getOrElse { throw ShopBackendException(UcpError.Malformed("The server sent an unexpected response. Please try again.")) }+ .getOrElse {+ throw ShopBackendException(+ UcpError.Malformed("The server sent an unexpected response. Please try again."),+ )+ } } private fun BackendRawResponse.parseSession(): UcpCheckout { checkStatus() val session = runCatching { json.decodeFromString<ShopCheckoutSession>(body) }- .getOrElse { throw ShopBackendException(UcpError.Malformed("The server sent an unexpected response. Please try again.")) }+ .getOrElse {+ throw ShopBackendException(+ UcpError.Malformed("The server sent an unexpected response. Please try again."),+ )+ } return session.toModel() } + /** Throws [error] as a backend failure; keeps throw sites out of status handling. */+ private fun failStatus(error: UcpError): Nothing = throw ShopBackendException(error)+ private fun BackendRawResponse.checkStatus() {- if (status in 200..299) return+ if (status in HTTP_OK_MIN..HTTP_OK_MAX) return // The server's error envelope mirrors the former UcpError codes. val envelope = runCatching { json.decodeFromString<ShopErrorEnvelope>(body) }.getOrNull()?.error if (envelope != null) {- throw ShopBackendException(+ failStatus( when (envelope.code) {- "transport" -> UcpError.Transport(envelope.message.ifBlank { "Couldn't reach the store. Check your connection and try again." })- "rate_limited" -> UcpError.RateLimited(envelope.retryAfterMs ?: retryAfter?.toLongOrNull()?.times(1000))+ "transport" -> UcpError.Transport(+ envelope.message.ifBlank { "Couldn't reach the store. Check your connection and try again." },+ )+ "rate_limited" -> UcpError.RateLimited(+ envelope.retryAfterMs ?: retryAfter?.toLongOrNull()?.times(MILLIS_PER_SECOND),+ ) "http" -> UcpError.Http(status, "")- "malformed" -> UcpError.Malformed(envelope.message.ifBlank { "The store sent an unexpected response. Please try again." })+ "malformed" -> UcpError.Malformed(+ envelope.message.ifBlank { "The store sent an unexpected response. Please try again." },+ ) "rpc" -> UcpError.Rpc(envelope.message.ifBlank { "The merchant couldn't process the request." })- "uncertain" -> UcpError.Transport("The request may have reached the merchant. Do not retry; check the session or use its website.")+ "uncertain" -> UcpError.Transport(+ "The request may have reached the merchant. " ++ "Do not retry; check the session or use its website.",+ ) "unsupported" -> UcpError.Unsupported( envelope.message.ifBlank { "These requirements need the merchant website." }, envelope.continueUrl,@@ -219,8 +291,10 @@ internal object ShopHttpBackend : ShopBackend { }, ) }- if (status == 429) throw ShopBackendException(UcpError.RateLimited(retryAfter?.toLongOrNull()?.times(1000)))- throw ShopBackendException(UcpError.Http(status, ""))+ if (status == HTTP_TOO_MANY_REQUESTS) {+ failStatus(UcpError.RateLimited(retryAfter?.toLongOrNull()?.times(MILLIS_PER_SECOND)))+ }+ failStatus(UcpError.Http(status, "")) } private suspend fun <T> catching(block: suspend () -> T): Result<T> = try {@@ -235,7 +309,11 @@ internal object ShopHttpBackend : ShopBackend { } catch (_: IllegalArgumentException) { Result.failure(ShopBackendException(UcpError.Malformed("Invalid shop request"))) } catch (_: Exception) {- Result.failure(ShopBackendException(UcpError.Transport("Couldn't reach the store. Check your connection and try again.")))+ Result.failure(+ ShopBackendException(+ UcpError.Transport("Couldn't reach the store. Check your connection and try again."),+ ),+ ) } }
shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.kt b/shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.ktindex 5525cb027d..7b5c905b18 100644--- a/shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.kt+++ b/shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.kt@@ -25,6 +25,7 @@ data class ShopCheckoutLine( val quantity: Int, ) +/** Immutable value describing shop checkout inputs. */ @Serializable data class ShopCheckoutInputs( val firstName: String = "",@@ -41,6 +42,7 @@ data class ShopCheckoutInputs( val shippingRequested: Boolean = false, ) +/** Immutable value describing shop create checkout request. */ @Serializable data class ShopCreateCheckoutRequest( val shop: String,@@ -49,6 +51,7 @@ data class ShopCreateCheckoutRequest( val idempotencyKey: String, ) +/** Immutable value describing shop update checkout request. */ @Serializable data class ShopUpdateCheckoutRequest( val shop: String,@@ -58,18 +61,21 @@ data class ShopUpdateCheckoutRequest( val idempotencyKey: String, ) +/** Immutable value describing shop submitted line. */ @Serializable data class ShopSubmittedLine( val variantId: String = "", val quantity: Int = 0, ) +/** Immutable value describing shop money. */ @Serializable data class ShopMoney( val amount: Long = 0, val currency: String = "USD", ) +/** Immutable value describing shop total entry. */ @Serializable data class ShopTotalEntry( val type: String = "",@@ -78,6 +84,7 @@ data class ShopTotalEntry( val currency: String = "USD", ) +/** Immutable value describing shop message. */ @Serializable data class ShopMessage( val type: String = "",@@ -87,6 +94,7 @@ data class ShopMessage( val severity: String? = null, ) +/** Immutable value describing shop shipping option. */ @Serializable data class ShopShippingOption( val id: String = "",@@ -95,6 +103,7 @@ data class ShopShippingOption( val totals: List<ShopTotalEntry> = emptyList(), ) +/** Immutable value describing shop shipping group. */ @Serializable data class ShopShippingGroup( val id: String = "",@@ -102,12 +111,14 @@ data class ShopShippingGroup( val options: List<ShopShippingOption> = emptyList(), ) +/** Immutable value describing shop shipping method. */ @Serializable data class ShopShippingMethod( val id: String = "", val groups: List<ShopShippingGroup> = emptyList(), ) +/** Immutable value describing shop legal link. */ @Serializable data class ShopLegalLink( val type: String = "",@@ -115,6 +126,7 @@ data class ShopLegalLink( val url: String = "", ) +/** Immutable value describing shop review. */ @Serializable data class ShopReview( val shipping: List<ShopShippingMethod> = emptyList(),@@ -123,12 +135,14 @@ data class ShopReview( val availableShippingLineIds: List<String> = emptyList(), ) +/** Immutable value describing shop totals. */ @Serializable data class ShopTotals( val subtotal: ShopMoney = ShopMoney(), val total: ShopMoney = ShopMoney(), ) +/** Immutable value describing shop checkout session. */ @Serializable data class ShopCheckoutSession( val checkoutId: String = "",@@ -145,9 +159,11 @@ data class ShopCheckoutSession( val trackingToken: String = "", ) +/** Immutable value describing shop order status request; carries orders. */ @Serializable data class ShopOrderStatusRequest(val orders: List<OrderStatusQuery>) +/** Immutable value describing shop order status. */ @Serializable data class ShopOrderStatus( val token: String = "",@@ -155,15 +171,18 @@ data class ShopOrderStatus( val tracking: OrderTracking? = null, ) +/** Immutable value describing shop order status response; carries orders. */ @Serializable data class ShopOrderStatusResponse(val orders: List<ShopOrderStatus> = emptyList()) +/** Immutable value describing shop product image. */ @Serializable data class ShopProductImage( val url: String = "", val alt: String? = null, ) +/** Immutable value describing shop catalog option. */ @Serializable data class ShopCatalogOption( val name: String = "",@@ -171,6 +190,7 @@ data class ShopCatalogOption( val id: String? = null, ) +/** Immutable value describing shop variant. */ @Serializable data class ShopVariant( val id: String = "",@@ -184,6 +204,7 @@ data class ShopVariant( val selectedOptions: List<ShopCatalogOption> = emptyList(), ) +/** Immutable value describing shop product. */ @Serializable data class ShopProduct( val id: String = "",@@ -201,11 +222,13 @@ data class ShopProduct( val storeName: String = "", ) +/** Immutable value describing shop search response. */ @Serializable data class ShopSearchResponse( val products: List<ShopProduct> = emptyList(), ) +/** Immutable value describing shop product response. */ @Serializable data class ShopProductResponse( val product: ShopProduct = ShopProduct(),@@ -223,6 +246,7 @@ data class ShopMerchant( val directoryVerifiedAt: String? = null, ) +/** Immutable value describing shop error body. */ @Serializable data class ShopErrorBody( val code: String = "",@@ -231,6 +255,7 @@ data class ShopErrorBody( val continueUrl: String? = null, ) +/** Immutable value describing shop error envelope. */ @Serializable data class ShopErrorEnvelope( val error: ShopErrorBody = ShopErrorBody(),@@ -288,7 +313,11 @@ internal fun ShopCheckoutSession.toModel(): UcpCheckout = UcpCheckout( total = totals.total.toModel(), ), totalEntries = totalEntries.map {- com.vayunmathur.shop.data.UcpTotalEntry(it.type, it.displayText.ifBlank { it.type }, it.amount.toModel(it.currency))+ com.vayunmathur.shop.data.UcpTotalEntry(+ it.type,+ it.displayText.ifBlank { it.type },+ it.amount.toModel(it.currency),+ ) }, continueUrl = continueUrl, expiresAt = expiresAt,
shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.ktindex cce12e0197..0baf3818ff 100644--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.kt+++ b/shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.kt@@ -3,6 +3,7 @@ package com.vayunmathur.shop.network /** Labels only. Merchant endpoint and access permissions are resolved server-side, not inferred. */ data class UcpPlatform(val id: String, val displayName: String, val globalCatalogMcp: String? = null) +/** Singleton holding ucp platforms state and operations. */ object UcpPlatforms { val SHOPIFY = UcpPlatform("shopify", "Shopify", "https://catalog.shopify.com/api/ucp/mcp") val GENERIC = UcpPlatform("generic", "UCP merchant")
shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.kt b/shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.ktindex a8345bbefe..6a996c00e3 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/OrderTrackingWorker.kt@@ -93,6 +93,7 @@ fun trackingStatusRes(status: String): Int = when (status) { else -> R.string.tracking_confirmed } +/** Background worker performing order tracking. */ class OrderTrackingWorker( appContext: Context, params: WorkerParameters,
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 0d2db9b0b6..bce23ac4be 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -33,6 +33,8 @@ import com.vayunmathur.shop.network.ShopBackendException import com.vayunmathur.shop.network.ShopHttpBackend import kotlinx.coroutines.launch +private const val MAX_QUANTITY = 99+ /** Session catalog state plus persisted cart and pending checkout history. */ class ShopViewModel( private val backend: ShopBackend = ShopHttpBackend,@@ -246,14 +248,16 @@ class ShopViewModel( fun addToCart(product: com.vayunmathur.shop.data.UcpProduct, variantId: String, quantity: Int, context: Context) { val variant = product.variants.firstOrNull { it.id == variantId } ?: return- if (!variant.available || !product.checkoutEligible || quantity !in 1..99) return+ if (!variant.available || !product.checkoutEligible || quantity !in 1..MAX_QUANTITY) return val existing = cart.indexOfFirst { it.variantId == variantId && it.platformId == product.platformId && it.shopDomain == product.shopDomain } cart = if (existing >= 0) { cart.toMutableList().also {- it[existing] = it[existing].copy(quantity = (it[existing].quantity + quantity).coerceAtMost(99))+ it[existing] = it[existing].copy(+ quantity = (it[existing].quantity + quantity).coerceAtMost(MAX_QUANTITY),+ ) } } else { cart + CartLine(
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 3a398be163..6b94b7b8ca 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt@@ -57,6 +57,7 @@ import kotlinx.coroutines.CancellationException /** Search snapshots paint immediately, but only a live, exact-variant refresh permits purchase. */ @Composable+@Suppress("TooGenericExceptionCaught") // Refresh failures all show the same retry message. fun ProductScreen( viewModel: ShopViewModel, variantId: String,
shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutStateTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutStateTest.kt b/shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutStateTest.ktindex 5108baddb4..fb90ea4f42 100644--- a/shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutStateTest.kt+++ b/shop/src/test/java/com/vayunmathur/shop/domain/NativeCheckoutStateTest.kt@@ -1,10 +1,27 @@ package com.vayunmathur.shop.domain -import com.vayunmathur.shop.data.*-import kotlinx.coroutines.*+import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.CheckoutPhase+import com.vayunmathur.shop.data.NativeCheckoutState+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.SubmittedLine+import com.vayunmathur.shop.data.UcpCheckout+import com.vayunmathur.shop.data.UcpError+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineStart+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json-import kotlin.test.*+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue class NativeCheckoutStateTest { private class FakeGateway : NativeCheckoutGateway {