shop: ui fixes
- Commit
27448b515143f38a4dc328b19b5cb228ccd93e84- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 20:07 UTC (1 month ago)
- Parents
f3e2c21
Diff
metadata_data/photos/shop/phone/1.png
diff --git a/metadata_data/photos/shop/phone/1.png b/metadata_data/photos/shop/phone/1.pngindex d6800e4b40..b06ce1f18b 100644Binary files a/metadata_data/photos/shop/phone/1.png and b/metadata_data/photos/shop/phone/1.png differ
metadata_data/photos/shop/phone/5.png
diff --git a/metadata_data/photos/shop/phone/5.png b/metadata_data/photos/shop/phone/5.pngnew file mode 100644index 0000000000..ecf44fd489Binary files /dev/null and b/metadata_data/photos/shop/phone/5.png differ
shop/AGENTS.md
diff --git a/shop/AGENTS.md b/shop/AGENTS.mdindex 6a4f1cc891..a3b304f9d8 100644--- a/shop/AGENTS.md+++ b/shop/AGENTS.md@@ -17,7 +17,9 @@ Entry types: MainActivity, Route, Navigation. Navigation remains a root-only gra - Checkout writes require explicit user action and a stable idempotency key per intent. Never replay an uncertain mutation automatically. - Preserve cart lines through partial failures and browser handoffs. A session or browser return is not a paid order. - No raw card entry, wallet tokenization, completion or authenticated order-read integration while provider authorization is unavailable.-- Only supported integer quantities can be added. Product refresh must succeed before cart actions.+- Only supported integer quantities can be added. Detail refresh sends the product ID and selected options, and must confirm the exact variant before cart actions. If a valid detail response returns only another featured option, one fresh advertised merchant search may confirm the exact SKU. Cached snapshots and empty lookup responses are not verification; denied/rate-limited calls are never retried automatically.+- Use variant seller identity for Global Catalog routing, not the shop.app product-page host. Display the publishing store name when provided and its domain otherwise.+- Product HTML is converted to inert styled text without a WebView; only validated public HTTPS description links may open externally. - Product responses remain session-scoped; persisted cart snapshots omit remote image URLs. - Merchant image hosts and cdn.shopify.com are allowed; other image hosts are dropped. - Await AppInit readiness before network operations so the standard trust bundle is initialized.
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 d8bdcc4226..fcd8d1467c 100644--- a/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt+++ b/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt@@ -11,6 +11,9 @@ data class Money(val amount: Long = 0, val currency: String = "USD") @Serializable data class ProductImage(val url: String = "", val alt: String? = null) +@Serializable+data class CatalogOptionSelection(val name: String, val label: String, val id: String? = null)+ @Serializable data class ProductVariant( val id: String = "",@@ -19,6 +22,9 @@ data class ProductVariant( val available: Boolean = false, val optionValues: List<String> = emptyList(), val sku: String? = null,+ val storeName: String = "",+ val shopDomain: String = "",+ val selectedOptions: List<CatalogOptionSelection> = emptyList(), ) @Serializable@@ -33,6 +39,9 @@ data class UcpProduct( val images: List<ProductImage> = emptyList(), val variants: List<ProductVariant> = emptyList(), val checkoutEligible: Boolean = false,+ val descriptionHtml: String = "",+ val storeName: String = "",+ val priceRangeMax: Money? = null, ) @Serializable
shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.kt b/shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.ktindex ef1e5b57bb..1b3f1ad75f 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.kt@@ -18,6 +18,12 @@ object MoneyFormat { fun majorUnits(money: Money): Double = decimalAmount(money).toDouble() + fun formatRange(min: Money, max: Money?, locale: Locale = Locale.US): String {+ val minimum = format(min, locale)+ if (max == null || max.currency != min.currency || max.amount < min.amount) return "From $minimum"+ return if (min.amount == max.amount) minimum else "$minimum - ${format(max, locale)}"+ }+ fun format(money: Money, locale: Locale = Locale.US): String { val currency = currency(money) ?: return "${money.currency.uppercase(Locale.US)} ${decimalAmount(money).toPlainString()}"
shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.ktindex db50a7a369..8d81d97238 100644--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.kt+++ b/shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.kt@@ -1,5 +1,6 @@ package com.vayunmathur.shop.network +import com.vayunmathur.shop.data.CatalogOptionSelection import com.vayunmathur.shop.data.Money import com.vayunmathur.shop.data.ProductImage import com.vayunmathur.shop.data.ProductVariant@@ -40,15 +41,55 @@ object UcpCatalog { .mapCatching { parseProducts(it, platform.id, shopDomain, service.version) } } - suspend fun getProduct(platform: UcpPlatform, shopDomain: String, id: String): Result<UcpProduct> {+ suspend fun getProduct(+ platform: UcpPlatform, shopDomain: String, id: String,+ selectedOptions: List<CatalogOptionSelection> = emptyList(),+ ): Result<UcpProduct> { val service = UcpDiscovery.resolve(shopDomain, "dev.ucp.shopping.catalog.lookup") .getOrElse { return Result.failure(it) }- val arguments = buildJsonObject { putJsonObject("catalog") { put("id", id) } }+ val arguments = buildJsonObject {+ putJsonObject("catalog") {+ put("id", id)+ putJsonObject("context") { put("address_country", "US") }+ if (selectedOptions.isNotEmpty()) {+ putJsonArray("selected") {+ selectedOptions.forEach { selection ->+ add(buildJsonObject {+ put("name", selection.name)+ put("label", selection.label)+ selection.id?.let { put("id", it) }+ })+ }+ }+ }+ }+ } return UcpApi.serviceCall(service, "get_product", arguments).mapCatching { parseProductResponse(it, platform.id, shopDomain, service.version) } } + /** Confirm the exact SKU using a fresh merchant response, not the cached search snapshot. */+ suspend fun refreshProduct(+ platform: UcpPlatform, shopDomain: String, variantId: String, productId: String? = null,+ selectedOptions: List<CatalogOptionSelection> = emptyList(), productTitle: String? = null,+ ): Result<UcpProduct> {+ val detail = getProduct(platform, shopDomain, productId?.takeIf { it.isNotBlank() } ?: variantId, selectedOptions)+ if (detail.isFailure || detail.getOrThrow().variants.any { it.id == variantId }) return detail+ // Some detail services return only their featured option, ignoring the requested selection.+ // A separate advertised merchant search can confirm the exact SKU; never retry denied/limited requests.+ if (!productTitle.isNullOrBlank()) {+ return searchStore(platform, shopDomain, productTitle, limit = 10).mapCatching { products ->+ val matched = products.firstOrNull { product -> product.variants.any { it.id == variantId } }+ ?: throw UcpHttpException(UcpError.Unsupported("The store did not return a live price for this option."))+ val alternatives = detail.getOrThrow().takeIf { it.id == matched.id }?.variants.orEmpty()+ .filter { option -> option.price.currency == matched.priceRange.currency && matched.variants.none { it.id == option.id } }+ matched.copy(variants = matched.variants + alternatives)+ }+ }+ return Result.failure(UcpHttpException(UcpError.Unsupported("The store did not return a live price for this option.")))+ }+ internal fun searchArguments(query: String, country: String, limit: Int): JsonObject = searchArguments(query, country, limit, UcpApi.VERSION) @@ -158,12 +199,12 @@ object UcpCatalog { o["description"].asObject() == null || o["price"].asObject() == null) malformed("Invalid dated variant") } - private fun priceRange(o: JsonObject, money: (JsonObject) -> Money): Money {+ private fun priceRange(o: JsonObject, money: (JsonObject) -> Money): Pair<Money, Money> { val range = o["price_range"].asObject() ?: malformed("Missing price range") val min = money(range["min"].asObject() ?: malformed("Missing minimum price")) val max = money(range["max"].asObject() ?: malformed("Missing maximum price")) if (min.currency != max.currency || min.amount > max.amount) malformed("Invalid price range")- return min+ return min to max } private fun augustQuantity(o: JsonObject): Boolean {@@ -181,14 +222,19 @@ object UcpCatalog { available = o["availability"].asObject()?.get("available") == JsonPrimitive(true) && supportedQuantity, optionValues = o["options"].asArray()?.mapNotNull { string(it.asObject(), "label") }.orEmpty(), sku = string(o, "sku"),+ storeName = sellerName(o),+ shopDomain = sellerDomain(o),+ selectedOptions = parseSelectedOptions(o), ) private fun projectProduct(- o: JsonObject, platformId: String, defaultShop: String, price: Money, variants: List<ProductVariant>,+ o: JsonObject, platformId: String, defaultShop: String, price: Pair<Money, Money>, variants: List<ProductVariant>, ): UcpProduct { val url = string(o, "url")?.let(MerchantUrls::httpsUrl).orEmpty()- val shop = MerchantUrls.domain(defaultShop) ?: string(o, "shop_domain")?.let(MerchantUrls::domain)- ?: url.takeIf { it.isNotBlank() }?.let { URI(it).host.lowercase() }.orEmpty()+ val shop = MerchantUrls.domain(defaultShop)+ ?: variants.firstOrNull()?.shopDomain?.takeIf { it.isNotBlank() }+ ?: string(o, "shop_domain")?.let(MerchantUrls::domain)+ ?: merchantDomainFromUrl(url) val images = o["media"].asArray()?.mapNotNull { item -> val media = item.asObject() ?: return@mapNotNull null if (string(media, "type") != "image") return@mapNotNull null@@ -200,12 +246,37 @@ object UcpCatalog { return UcpProduct( id = string(o, "id")!!, title = string(o, "title")!!, description = string(o["description"].asObject(), "plain").orEmpty(),- priceRange = price, url = url, platformId = platformId, shopDomain = shop,+ priceRange = price.first, priceRangeMax = price.second,+ url = url, platformId = platformId, shopDomain = shop, images = images, variants = variants,+ descriptionHtml = string(o["description"].asObject(), "html").orEmpty(),+ storeName = variants.firstOrNull { it.shopDomain.isBlank() || it.shopDomain == shop }?.storeName.orEmpty(), checkoutEligible = shop.isNotBlank() && variants.isNotEmpty() && o["native_commerce"] != JsonPrimitive(false), ) } + private fun parseSelectedOptions(variant: JsonObject): List<CatalogOptionSelection> =+ variant["options"].asArray()?.mapNotNull { element ->+ val option = element.asObject() ?: return@mapNotNull null+ val name = string(option, "name") ?: return@mapNotNull null+ val label = string(option, "label") ?: return@mapNotNull null+ CatalogOptionSelection(name, label, string(option, "id"))+ }.orEmpty()++ private fun sellerName(variant: JsonObject): String =+ string(variant["seller"].asObject(), "name")?.trim()?.take(200).orEmpty()++ private fun sellerDomain(variant: JsonObject): String {+ val seller = variant["seller"].asObject()+ return string(seller, "domain")?.let(MerchantUrls::domain)+ ?: string(seller, "url")?.let(MerchantUrls::httpsUrl)?.let { MerchantUrls.domain(URI(it).host) }+ ?: ""+ }++ private fun merchantDomainFromUrl(url: String): String =+ url.takeIf { it.isNotBlank() }?.let { URI(it).host.lowercase() }+ ?.takeUnless { it == "shop.app" || it.endsWith(".shop.app") || it == "catalog.shopify.com" }.orEmpty()+ private fun string(o: JsonObject?, key: String): String? = (o?.get(key) as? JsonPrimitive)?.takeIf { it.isString }?.content @@ -226,9 +297,10 @@ object UcpCatalog { val variants = o["variants"].asArray()?.mapNotNull { it.asObject()?.let(::parseVariant) }.orEmpty() val range = o["price_range"].asObject() val url = o.text("url").orEmpty()- val shop = if (defaultShop.isNotBlank()) defaultShop- else o.text("shop_domain")?.let(MerchantUrls::domain)- ?: MerchantUrls.httpsUrl(url)?.let { URI(it).host }.orEmpty()+ val shop = MerchantUrls.domain(defaultShop)+ ?: variants.firstOrNull()?.shopDomain?.takeIf { it.isNotBlank() }+ ?: o.text("shop_domain")?.let(MerchantUrls::domain)+ ?: MerchantUrls.httpsUrl(url)?.let(::merchantDomainFromUrl).orEmpty() val images = o["media"].asArray()?.mapNotNull { item -> val media = item.asObject() ?: return@mapNotNull null if (media.text("type") != "image") return@mapNotNull null@@ -241,7 +313,10 @@ object UcpCatalog { id = id, title = o.text("title").orEmpty(), description = o["description"].asObject()?.text("plain") ?: o.text("description").orEmpty(),+ descriptionHtml = o["description"].asObject()?.text("html").orEmpty(),+ storeName = variants.firstOrNull { it.shopDomain.isBlank() || it.shopDomain == shop }?.storeName.orEmpty(), priceRange = range?.get("min").asObject()?.let(::parseMoney) ?: variants.firstOrNull()?.price ?: Money(),+ priceRangeMax = range?.get("max").asObject()?.let(::parseMoney), url = url, platformId = platformId, shopDomain = shop,@@ -265,6 +340,9 @@ object UcpCatalog { available = (o["availability"].asObject()?.get("available").isTruthy() == true) && supportedQuantity, optionValues = o["options"].asArray()?.mapNotNull { it.asObject()?.text("label") }.orEmpty(), sku = o.text("sku"),+ storeName = sellerName(o),+ shopDomain = sellerDomain(o),+ selectedOptions = parseSelectedOptions(o), ) }
shop/src/main/java/com/vayunmathur/shop/ui/ProductQuantityRow.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/ProductQuantityRow.kt b/shop/src/main/java/com/vayunmathur/shop/ui/ProductQuantityRow.ktnew file mode 100644index 0000000000..9d17ee1afc--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ProductQuantityRow.kt@@ -0,0 +1,54 @@+package com.vayunmathur.shop.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.disabled+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SegmentedButton+import com.vayunmathur.library.ui.SegmentedButtonDefaults+import com.vayunmathur.library.ui.SingleChoiceSegmentedButtonRow+import com.vayunmathur.library.ui.Text++@Composable+internal fun ProductQuantityRow(quantity: Int, onChange: (Int) -> Unit) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {+ SegmentedButton(+ selected = false,+ onClick = { onChange((quantity - 1).coerceAtLeast(1)) },+ enabled = quantity > 1,+ shape = SegmentedButtonDefaults.itemShape(index = 0, count = 3),+ modifier = Modifier.semantics { contentDescription = "Decrease quantity"; role = Role.Button },+ label = { Text("-") },+ )+ SegmentedButton(+ selected = false,+ onClick = {},+ enabled = false,+ shape = SegmentedButtonDefaults.itemShape(index = 1, count = 3),+ modifier = Modifier.clearAndSetSemantics {+ contentDescription = "Quantity: $quantity"+ disabled()+ },+ label = { Text("$quantity", color = MaterialTheme.colorScheme.onSurface, style = MaterialTheme.typography.titleMedium) },+ )+ SegmentedButton(+ selected = false,+ onClick = { onChange((quantity + 1).coerceAtMost(99)) },+ enabled = quantity < 99,+ shape = SegmentedButtonDefaults.itemShape(index = 2, count = 3),+ modifier = Modifier.semantics { contentDescription = "Increase quantity"; role = Role.Button },+ label = { Text("+") },+ )+ }+ }+}
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 628c419741..f19421c7db 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt@@ -25,31 +25,34 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.LinkAnnotation+import androidx.compose.ui.text.LinkInteractionListener+import androidx.compose.ui.text.fromHtml import androidx.compose.ui.unit.dp import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.DetailSection import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.shop.R+import com.vayunmathur.shop.data.ProductVariant import com.vayunmathur.shop.data.UcpProduct import com.vayunmathur.shop.data.message+import com.vayunmathur.shop.domain.MerchantUrls import com.vayunmathur.shop.domain.MoneyFormat import com.vayunmathur.shop.network.UcpCatalog import com.vayunmathur.shop.network.UcpCheckoutApi import com.vayunmathur.shop.network.UcpHttpException-import com.vayunmathur.shop.platform.ShopViewModel import com.vayunmathur.shop.platform.AppInit+import com.vayunmathur.shop.platform.ShopViewModel+import kotlinx.coroutines.CancellationException -/**- * Product detail: gallery, variant picker, add-to-cart. Price/availability are re-checked- * live against the store on entry — search results may be stale and must never be trusted- * for the buy decision.- */+/** Search snapshots paint immediately, but only a live, exact-variant refresh permits purchase. */ @Composable fun ProductScreen( viewModel: ShopViewModel,@@ -61,154 +64,225 @@ fun ProductScreen( ) { val context = LocalContext.current val messenger = rememberMessenger()- var product by remember(variantId, platformId, shopDomain) { mutableStateOf<UcpProduct?>(null) }- var loading by remember(variantId, platformId, shopDomain) { mutableStateOf(true) }- var refreshed by remember(variantId, platformId, shopDomain) { mutableStateOf(false) }+ var product by remember(variantId, platformId, shopDomain) {+ mutableStateOf(viewModel.results.firstOrNull { candidate ->+ candidate.platformId == platformId && candidate.variants.any {+ it.id == variantId && (candidate.shopDomain == shopDomain || it.shopDomain == shopDomain)+ }+ })+ } var selectedVariant by remember(variantId, platformId, shopDomain) { mutableStateOf(variantId) } var quantity by remember(variantId, platformId, shopDomain) { mutableStateOf(1) }+ var retry by remember(variantId, platformId, shopDomain) { mutableStateOf(0) }+ var refreshing by remember(variantId, platformId, shopDomain) { mutableStateOf(true) }+ var activeKey by remember(variantId, platformId, shopDomain) { mutableStateOf<Pair<String, String>?>(null) }+ var verifiedKey by remember(variantId, platformId, shopDomain) { mutableStateOf<Pair<String, String>?>(null) }+ var failure by remember(variantId, platformId, shopDomain) { mutableStateOf<String?>(null) }+ val selected = product?.variants?.firstOrNull { it.id == selectedVariant }+ val publisherDomain = selected?.shopDomain?.takeIf { it.isNotBlank() }+ ?: product?.shopDomain?.takeIf { it.isNotBlank() } ?: shopDomain+ val refreshKey = selectedVariant to publisherDomain+ val loading = refreshing || activeKey != refreshKey - LaunchedEffect(variantId, platformId, shopDomain) {- // Prefer the search snapshot for instant paint, then re-check live.- viewModel.results.firstOrNull {- it.platformId == platformId && it.shopDomain == shopDomain &&- it.variants.any { v -> v.id == variantId }- }?.let {- product = it- }- AppInit.awaitReady()- if (shopDomain.isNotBlank()) {- val platform = UcpCheckoutApi.platformFor(platformId)- UcpCatalog.lookup(platform, shopDomain, listOf(variantId)).fold(- onSuccess = { products ->- products.firstOrNull()?.let {- product = it- refreshed = true- }- // The looked-up variant may differ from the tapped one; keep the- // selection only if the store still lists it.- if (products.flatMap { it.variants }.none { it.id == selectedVariant }) {- selectedVariant = products.firstOrNull()?.variants?.firstOrNull()?.id- ?: variantId- }- },- onFailure = {- val err = (it as? UcpHttpException)?.error- messenger.show(- err?.message() ?: "Couldn't refresh this product.",- )- },- )+ LaunchedEffect(variantId, platformId, refreshKey, retry) {+ activeKey = refreshKey+ refreshing = true+ verifiedKey = null+ failure = null+ val snapshot = product+ val publisherName = selected?.storeName?.takeIf { it.isNotBlank() }+ ?: snapshot?.takeIf { it.shopDomain == publisherDomain }?.storeName.orEmpty()+ try {+ if (publisherDomain.isBlank()) {+ failure = "The publishing store domain is missing. Cart actions are disabled."+ } else {+ AppInit.awaitReady()+ val platform = UcpCheckoutApi.platformFor(platformId)+ UcpCatalog.refreshProduct(+ platform, publisherDomain, selectedVariant, snapshot?.id, selected?.selectedOptions.orEmpty(), snapshot?.title,+ ).fold(+ onSuccess = { live ->+ if (live.variants.none { it.id == selectedVariant }) {+ failure = "The store no longer lists this exact variant. Cart actions are disabled."+ } else {+ // Detail responses can narrow to one option. Other choices stay unverified until selected.+ val choices = snapshot?.variants?.map { previous ->+ live.variants.firstOrNull { it.id == previous.id }?.let { refreshed ->+ refreshed.copy(+ storeName = refreshed.storeName.ifBlank { previous.storeName },+ shopDomain = refreshed.shopDomain.ifBlank { previous.shopDomain },+ selectedOptions = refreshed.selectedOptions.ifEmpty { previous.selectedOptions },+ )+ } ?: previous+ }.orEmpty()+ product = live.copy(+ storeName = live.storeName.ifBlank { publisherName },+ variants = choices + live.variants.filter { fresh -> choices.none { it.id == fresh.id } },+ )+ verifiedKey = refreshKey+ }+ },+ onFailure = { error ->+ if (error is CancellationException) throw error+ failure = (error as? UcpHttpException)?.error?.message()+ ?: "Couldn't refresh this product from the publishing store. Check your connection and retry."+ },+ )+ }+ } catch (error: CancellationException) {+ throw error+ } catch (error: Exception) {+ failure = (error as? UcpHttpException)?.error?.message()+ ?: "Couldn't refresh this product from the publishing store. Check your connection and retry."+ } finally {+ refreshing = false }- loading = false } + val verified = !loading && verifiedKey == refreshKey+ val canAdd = verified && product?.checkoutEligible == true && selected?.available == true+ val addToCart: () -> Unit = {+ val current = product+ if (canAdd && current != null) {+ val cartProduct = current.copy(shopDomain = selected?.shopDomain?.takeIf { it.isNotBlank() } ?: current.shopDomain)+ viewModel.addToCart(cartProduct, selectedVariant, quantity, context)+ }+ } AppScaffold( title = product?.title ?: stringResource(R.string.app_name), onNavigateBack = onBack, scrollBehavior = appBarScrollBehavior(), ) { padding -> val current = product- if (loading && current == null) {- Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- CircularProgressIndicator()- }- return@AppScaffold- } if (current == null) {- Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- Text(stringResource(R.string.check_connection_retry))- }- return@AppScaffold- }- LazyColumn(- contentPadding = PaddingValues(16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp),- modifier = Modifier.fillMaxSize().padding(padding),- ) {- val images = current.images- if (images.isNotEmpty()) {- item {- LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- items(images, key = { it.url }) { image ->- AsyncImage(- model = image.url,- contentDescription = image.alt ?: current.title,- modifier = Modifier- .fillParentMaxWidth(0.85f)- .height(280.dp),- contentScale = ContentScale.Crop,- )- }+ Box(Modifier.fillMaxSize().padding(padding).padding(16.dp), contentAlignment = Alignment.Center) {+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {+ if (loading) {+ CircularProgressIndicator()+ Text("Checking live price and availability...")+ } else {+ Text(failure ?: "This product is unavailable. Please retry.")+ Button(onClick = { retry += 1 }) { Text("Retry") } } } }- item {- DetailSection("Price") {- val variant = current.variants.firstOrNull { it.id == selectedVariant }- Text(- MoneyFormat.format(variant?.price ?: current.priceRange),- style = MaterialTheme.typography.headlineSmall,- color = MaterialTheme.colorScheme.primary,- )+ } else {+ ProductDetailContent(+ product = current,+ selectedVariantId = selectedVariant,+ quantity = quantity,+ loading = loading,+ verified = verified,+ failure = failure,+ onSelectVariant = { selectedVariant = it },+ onQuantityChange = { quantity = it },+ onRetry = { retry += 1 },+ onAddToCart = { if (canAdd) { addToCart(); messenger.show("Added to cart") } },+ onBuyNow = { if (canAdd) { addToCart(); onCheckout() } },+ onOpenUrl = { url -> MerchantUrls.httpsUrl(url)?.let { openContinueUrl(context, it) } },+ modifier = Modifier.fillMaxSize().padding(padding),+ )+ }+ }+}++/** Stateless content shared with metadata fixtures; all effects belong to the screen host. */+@Composable+internal fun ProductDetailContent(+ product: UcpProduct,+ selectedVariantId: String,+ quantity: Int,+ loading: Boolean,+ verified: Boolean,+ failure: String?,+ onSelectVariant: (String) -> Unit,+ onQuantityChange: (Int) -> Unit,+ onRetry: () -> Unit,+ onAddToCart: () -> Unit,+ onBuyNow: () -> Unit,+ onOpenUrl: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ val variant = product.variants.firstOrNull { it.id == selectedVariantId }+ val storeDomain = variant?.shopDomain?.takeIf { it.isNotBlank() } ?: product.shopDomain+ val storeName = variant?.storeName?.takeIf { it.isNotBlank() }+ ?: product.storeName.takeIf { storeDomain == product.shopDomain }.orEmpty()+ val canAdd = verified && !loading && product.checkoutEligible && variant?.available == true+ val description = remember(product.descriptionHtml, product.description, onOpenUrl) {+ // Native conversion also handles merchants that put HTML fragments in the plain field.+ AnnotatedString.fromHtml(+ product.descriptionHtml.ifBlank { product.description },+ linkInteractionListener = LinkInteractionListener { link ->+ (link as? LinkAnnotation.Url)?.url?.let { url ->+ MerchantUrls.httpsUrl(url)?.let(onOpenUrl) }- }- if (current.variants.size > 1) {- item {- DetailSection("Options") {- VariantPicker(- variants = current.variants,- selectedId = selectedVariant,- onSelect = { selectedVariant = it },+ },+ )+ }+ LazyColumn(+ contentPadding = PaddingValues(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ modifier = modifier,+ ) {+ if (product.images.isNotEmpty()) {+ item {+ LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ items(product.images, key = { it.url }) { image ->+ AsyncImage(+ model = image.url,+ contentDescription = image.alt ?: product.title,+ modifier = Modifier.fillParentMaxWidth(0.85f).height(280.dp),+ contentScale = ContentScale.Crop, ) } } }- if (current.description.isNotBlank()) {- item {- DetailSection("Details") {- Text(- current.description,- style = MaterialTheme.typography.bodyMedium,- )- }+ }+ item {+ DetailSection("Publishing store") {+ Text(storeName.ifBlank { storeDomain.ifBlank { "Publishing store" } }, style = MaterialTheme.typography.titleMedium)+ if (storeName.isNotBlank()) {+ Text(storeDomain.ifBlank { "Store domain unavailable" }, style = MaterialTheme.typography.bodyMedium) } }- item {- QuantityRow(quantity = quantity, onChange = { quantity = it })+ }+ item {+ DetailSection("Price") {+ Text(+ variant?.price?.let { MoneyFormat.format(it) } ?: "Select an option to see its price",+ style = MaterialTheme.typography.headlineSmall,+ color = MaterialTheme.colorScheme.primary,+ ) }+ }+ if (product.variants.size > 1) { item {- val canAdd = refreshed && !loading && current.checkoutEligible &&- current.variants.firstOrNull { it.id == selectedVariant }?.available == true- if (!current.checkoutEligible && current.url.isNotBlank()) {- Button(onClick = { openContinueUrl(context, current.url) }) {- Text("View on merchant site")+ DetailSection("Options") {+ VariantPicker(product.variants, selectedVariantId, onSelectVariant)+ }+ }+ }+ item { ProductQuantityRow(quantity, onQuantityChange) }+ item {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ when {+ loading -> Text("Checking live price and availability...")+ !verified -> {+ Text(failure ?: "Live price and availability are not verified. Cart actions are disabled.")+ Button(onClick = onRetry) { Text("Retry") } }+ variant?.available != true -> Text("This variant is out of stock.") }- if (!refreshed) Text("Live price could not be verified. Cart actions are disabled.") Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- Button(- onClick = {- viewModel.addToCart(current, selectedVariant, quantity, context)- messenger.show("Added to cart")- },- enabled = canAdd,- modifier = Modifier.weight(1f),- ) {+ Button(onClick = onAddToCart, enabled = canAdd, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.add_to_cart)) }- Button(- onClick = {- viewModel.addToCart(current, selectedVariant, quantity, context)- onCheckout()- },- enabled = canAdd,- modifier = Modifier.weight(1f),- ) {+ Button(onClick = onBuyNow, enabled = canAdd, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.buy_now)) } }- Spacer(Modifier.height(4.dp))- if (!current.checkoutEligible && current.url.isNotBlank()) {+ if ((!product.checkoutEligible || !verified && !loading) && MerchantUrls.httpsUrl(product.url) != null) {+ Button(onClick = { onOpenUrl(product.url) }) { Text("View on merchant site") } Text( "Completes on the merchant site.", style = MaterialTheme.typography.bodySmall,@@ -217,12 +291,19 @@ fun ProductScreen( } } }+ if (description.isNotBlank()) {+ item {+ DetailSection("Details") {+ Text(description, style = MaterialTheme.typography.bodyMedium)+ }+ }+ } } } @Composable private fun VariantPicker(- variants: List<com.vayunmathur.shop.data.ProductVariant>,+ variants: List<ProductVariant>, selectedId: String, onSelect: (String) -> Unit, ) {@@ -235,49 +316,22 @@ private fun VariantPicker( verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) {- Text(- variant.title.ifBlank { "Default" },- style = MaterialTheme.typography.bodyMedium,- )+ Text(variant.title.ifBlank { "Default" }, style = MaterialTheme.typography.bodyMedium) if (!variant.available) {- Text(- "Out of stock",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.error,- )+ Text("Out of stock", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) } } Spacer(Modifier.width(8.dp)) Text( MoneyFormat.format(variant.price), style = MaterialTheme.typography.bodyMedium,- color = if (selected) {- MaterialTheme.colorScheme.primary- } else {- MaterialTheme.colorScheme.onSurfaceVariant- },+ color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, ) Spacer(Modifier.width(8.dp))- Button(- onClick = { onSelect(variant.id) },- enabled = variant.available && !selected,- ) {+ Button(onClick = { onSelect(variant.id) }, enabled = variant.available && !selected) { Text(if (selected) "Selected" else "Select") } } } } }--@Composable-private fun QuantityRow(quantity: Int, onChange: (Int) -> Unit) {- Row(verticalAlignment = Alignment.CenterVertically) {- Text("Quantity", style = MaterialTheme.typography.bodyMedium)- Spacer(Modifier.width(12.dp))- Button(onClick = { onChange((quantity - 1).coerceAtLeast(1)) }) { Text("−") }- Spacer(Modifier.width(8.dp))- Text("$quantity", style = MaterialTheme.typography.titleMedium)- Spacer(Modifier.width(8.dp))- Button(onClick = { onChange((quantity + 1).coerceAtMost(99)) }) { Text("+") }- }-}
shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.ktindex eb6db1adcd..f07d0f7640 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.kt@@ -164,8 +164,8 @@ private fun ProductResults( ) { items(results, key = { "${it.platformId}|${it.shopDomain}|${it.id}" }) { product -> ProductCard(product = product, onClick = {- val variantId = product.variants.firstOrNull()?.id ?: return@ProductCard- onProductClick(variantId, product.platformId, product.shopDomain)+ val variant = product.variants.firstOrNull() ?: return@ProductCard+ onProductClick(variant.id, product.platformId, variant.shopDomain.ifBlank { product.shopDomain }) }) } }@@ -192,7 +192,7 @@ private fun ProductCard(product: UcpProduct, onClick: () -> Unit) { ) Spacer(Modifier.height(4.dp)) Text(- text = MoneyFormat.format(product.priceRange),+ text = MoneyFormat.formatRange(product.priceRange, product.priceRangeMax), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.primary, )
shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.kt
diff --git a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.kt b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.ktindex 9123cf5594..47abb12623 100644--- a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.kt+++ b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.kt@@ -43,7 +43,7 @@ class MetadataPreviews { ProductVariant( id = "gid://shopify/ProductVariant/12", title = "10 / Blue",- price = Money(12999, "USD"),+ price = Money(14999, "USD"), optionValues = listOf("10", "Blue"), ), )@@ -54,6 +54,7 @@ class MetadataPreviews { title = "Trail Runner", description = "Grippy shoes for muddy miles", priceRange = Money(12999, "USD"),+ priceRangeMax = Money(14999, "USD"), platformId = "shopify", shopDomain = "example.myshopify.com", variants = variants,@@ -64,6 +65,7 @@ class MetadataPreviews { title = "Wool Overshirt", description = "Heavyweight merino flannel", priceRange = Money(18900, "USD"),+ priceRangeMax = Money(18900, "USD"), platformId = "shopify", shopDomain = "example.myshopify.com", variants = listOf(
shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt
diff --git a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.ktnew file mode 100644index 0000000000..b414e6b359--- /dev/null+++ b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt@@ -0,0 +1,74 @@+package com.vayunmathur.shop.ui++import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.ProductVariant+import com.vayunmathur.shop.data.UcpProduct++/** Immutable metadata fixture: no ViewModel, remote images, initialization or network. */+class ProductMetadataPreviews {+ private val product = UcpProduct(+ id = "fixture-product",+ title = "Trail Runner",+ description = "Lightweight shoes for everyday trails.",+ descriptionHtml = "<p><b>Ready for the trail.</b> Lightweight shoes with a grippy sole.</p>" ++ "<p><i>Recycled mesh</i> keeps every mile comfortable. " ++ "<a href=\"https://trail.example/care\">Care guide</a></p>",+ priceRange = Money(12999, "USD"),+ platformId = "shopify",+ shopDomain = "catalog.example",+ storeName = "Trail Collective",+ checkoutEligible = true,+ variants = listOf(+ ProductVariant(+ id = "fixture-blue",+ title = "9 / Blue",+ price = Money(12999, "USD"),+ available = true,+ storeName = "Trail Outfitters",+ shopDomain = "trail.example",+ ),+ ProductVariant(+ id = "fixture-green",+ title = "10 / Green",+ price = Money(12999, "USD"),+ available = true,+ storeName = "Trail Outfitters",+ shopDomain = "trail.example",+ ),+ ),+ )++ @PreviewTest+ @Preview(name = "5-product", group = "phone", widthDp = 360, heightDp = 780)+ @Composable+ fun Preview5Product() {+ DynamicTheme(darkTheme = false) {+ AppScaffold(title = product.title, scrollBehavior = appBarScrollBehavior()) { padding ->+ ProductDetailContent(+ product = product,+ selectedVariantId = "fixture-blue",+ quantity = 2,+ loading = false,+ verified = true,+ failure = null,+ onSelectVariant = {},+ onQuantityChange = {},+ onRetry = {},+ onAddToCart = {},+ onBuyNow = {},+ onOpenUrl = {},+ modifier = Modifier.fillMaxSize().padding(padding),+ )+ }+ }+ }+}
shop/src/test/java/com/vayunmathur/shop/domain/MoneyFormatTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/domain/MoneyFormatTest.kt b/shop/src/test/java/com/vayunmathur/shop/domain/MoneyFormatTest.ktindex 6e82be0bf5..05ce20ced7 100644--- a/shop/src/test/java/com/vayunmathur/shop/domain/MoneyFormatTest.kt+++ b/shop/src/test/java/com/vayunmathur/shop/domain/MoneyFormatTest.kt@@ -32,6 +32,20 @@ class MoneyFormatTest { assertTrue(MoneyFormat.format(Money(12999, "KWD")).contains("12.999")) } + @Test+ fun rangeFormatsBothPricesAndCollapsesEqualPrices() {+ assertEquals("$12.99 - $19.99", MoneyFormat.formatRange(Money(1299, "USD"), Money(1999, "USD")))+ assertEquals("$12.99", MoneyFormat.formatRange(Money(1299, "USD"), Money(1299, "USD")))+ }++ @Test+ fun missingOrInvalidUpperBoundsUseFromInsteadOfInventingARange() {+ val min = Money(1299, "USD")+ assertEquals("From $12.99", MoneyFormat.formatRange(min, null))+ assertEquals("From $12.99", MoneyFormat.formatRange(min, Money(1000, "USD")))+ assertEquals("From $12.99", MoneyFormat.formatRange(min, Money(1999, "EUR")))+ }+ @Test fun unknownCurrencyFallsBackToCode() { val formatted = MoneyFormat.format(Money(100, "XXQ"), Locale.US)
shop/src/test/java/com/vayunmathur/shop/network/UcpCatalogDatedTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/network/UcpCatalogDatedTest.kt b/shop/src/test/java/com/vayunmathur/shop/network/UcpCatalogDatedTest.ktindex 0411036c6a..d26d8cd352 100644--- a/shop/src/test/java/com/vayunmathur/shop/network/UcpCatalogDatedTest.kt+++ b/shop/src/test/java/com/vayunmathur/shop/network/UcpCatalogDatedTest.kt@@ -112,11 +112,22 @@ class UcpCatalogDatedTest { assertEquals("p1", UcpCatalog.getProduct(UcpPlatforms.GENERIC, "shop.example", "p1").getOrThrow().id) val call = detail.requests.last() assertEquals("$endpoint/catalog/product", call.url)- assertEquals(obj("""{"id":"p1"}"""), obj(call.body!!))+ assertEquals(obj("""{"id":"p1","context":{"address_country":"US"}}"""), obj(call.body!!)) } } } + @Test+ fun bothDatedParsersRetainTheFullMerchantRangeNotJustVisibleVariantPrices() {+ for (version in listOf(current, april)) {+ val item = product().replace("\"max\":{\"amount\":12999", "\"max\":{\"amount\":15999")+ val parsed = UcpCatalog.parseProducts(response(version, item), "generic", "shop.example", version).single()+ assertEquals(Money(12999, "USD"), parsed.priceRange)+ assertEquals(Money(15999, "USD"), parsed.priceRangeMax)+ assertEquals(Money(12999, "USD"), parsed.variants.single().price)+ }+ }+ @Test fun emptyLookupDoesNotDiscoverOrCallMerchant() { val fake = CatalogTransport(manifest(current), response(current))
shop/src/test/java/com/vayunmathur/shop/network/UcpProductDetailTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/network/UcpProductDetailTest.kt b/shop/src/test/java/com/vayunmathur/shop/network/UcpProductDetailTest.ktnew file mode 100644index 0000000000..8cc5071742--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/network/UcpProductDetailTest.kt@@ -0,0 +1,181 @@+package com.vayunmathur.shop.network++import com.vayunmathur.library.network.NetworkDataStream+import com.vayunmathur.library.network.RawResponse+import com.vayunmathur.library.network.SimpleResponse+import com.vayunmathur.library.network.asNetworkDataStream+import com.vayunmathur.shop.data.UcpError+import com.vayunmathur.shop.data.CatalogOptionSelection+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonObject+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class UcpProductDetailTest {+ private fun obj(raw: String) = UcpApi.json.parseToJsonElement(raw) as JsonObject+ private fun product(seller: String = "", url: String = "https://shop.example/products/p1"): String = """+ {"id":"p1","title":"Trail Runner","description":{"html":"<p>Soft <strong>wool</strong>.</p>"},+ "url":"$url","price_range":{"min":{"amount":100,"currency":"USD"},"max":{"amount":100,"currency":"USD"}},+ "variants":[{"id":"v1","title":"Blue","description":{"plain":"Blue"},+ "price":{"amount":100,"currency":"USD"},"availability":{"available":true}$seller}]}+ """++ private class DetailTransport(+ private val version: String, product: String, private val searchProduct: String? = null,+ private val detailStatus: Int = 200,+ ) : UcpTransport {+ val requests = mutableListOf<UcpRequest>()+ private val manifest = """{"ucp":{"version":"$version",+ "services":{"dev.ucp.shopping":[{"version":"$version","transport":"rest","endpoint":"https://shop.example/api"}]},+ "capabilities":{"dev.ucp.shopping.catalog.lookup":[{"version":"$version"}],+ "dev.ucp.shopping.catalog.search":[{"version":"$version"}]},"payment_handlers":{}}}"""+ private val payload = """{"ucp":{"version":"$version"},"product":$product}"""+ override suspend fun execute(request: UcpRequest): RawResponse {+ requests.add(request)+ return RawResponse(200, "", manifest.toByteArray(), emptyMap(), request.url)+ }+ override suspend fun stream(+ request: UcpRequest, block: suspend (NetworkDataStream?, SimpleResponse) -> Unit,+ ): SimpleResponse {+ requests.add(request)+ val search = request.url.endsWith("/catalog/search")+ val body = if (search) """{"ucp":{"version":"$version"},"products":[${searchProduct ?: ""}]}""" else payload+ val response = SimpleResponse(if (search) 200 else detailStatus, "", "", mapOf("Content-Type" to listOf("application/json")), request.url)+ block(body.toByteArray().asNetworkDataStream(), response)+ return response+ }+ }++ @Test+ fun refreshUsesProductDetailAndConfirmsTheRequestedVariantForBothVersions() = runBlocking {+ val previous = UcpApi.transport+ try {+ for (version in listOf(UcpApi.VERSION, UcpApi.APRIL_VERSION)) {+ val fake = DetailTransport(version, product())+ UcpApi.transport = fake+ val refreshed = UcpCatalog.refreshProduct(UcpPlatforms.GENERIC, "shop.example", "v1", "p1").getOrThrow()+ assertEquals("v1", refreshed.variants.single().id)+ assertEquals("<p>Soft <strong>wool</strong>.</p>", refreshed.descriptionHtml)+ assertEquals("https://shop.example/api/catalog/product", fake.requests.last().url)+ assertEquals(obj("""{"id":"p1","context":{"address_country":"US"}}"""), obj(fake.requests.last().body!!))+ assertEquals(2, fake.requests.size)+ }+ } finally {+ UcpApi.transport = previous+ }+ }++ @Test+ fun detailRequestSendsOptionNamesLabelsAndOptionalValueIds() = runBlocking {+ val previous = UcpApi.transport+ try {+ for (version in listOf(UcpApi.VERSION, UcpApi.APRIL_VERSION)) {+ val fake = DetailTransport(version, product())+ UcpApi.transport = fake+ val options = listOf(CatalogOptionSelection("Size", "9", "size-9"), CatalogOptionSelection("Color", "Blue"))+ UcpCatalog.refreshProduct(UcpPlatforms.GENERIC, "shop.example", "v1", "p1", options).getOrThrow()+ assertEquals(obj("""{"id":"p1","context":{"address_country":"US"},+ "selected":[{"name":"Size","label":"9","id":"size-9"},{"name":"Color","label":"Blue"}]}"""), obj(fake.requests.last().body!!))+ }+ } finally {+ UcpApi.transport = previous+ }+ }++ @Test+ fun parserRetainsSelectionsNeededToRefreshTheTappedVariant() {+ for (version in listOf(UcpApi.VERSION, UcpApi.APRIL_VERSION)) {+ val item = product().replace("\"availability\":", "\"options\":[{\"name\":\"Size\",\"label\":\"9\",\"id\":\"size-9\"}],\"availability\":")+ val data = obj("""{"ucp":{"version":"$version"},"products":[$item]}""")+ val parsed = UcpCatalog.parseProducts(data, "generic", "shop.example", version).single()+ assertEquals(listOf(CatalogOptionSelection("Size", "9", "size-9")), parsed.variants.single().selectedOptions)+ }+ }++ @Test+ fun featuredDetailOptionUsesFreshMerchantSearchToConfirmTheExactSku() = runBlocking {+ val previous = UcpApi.transport+ try {+ for (version in listOf(UcpApi.VERSION, UcpApi.APRIL_VERSION)) {+ val fake = DetailTransport(version, product().replace("\"v1\"", "\"featured\""), product())+ UcpApi.transport = fake+ val item = UcpCatalog.refreshProduct(UcpPlatforms.GENERIC, "shop.example", "v1", "p1", productTitle = "Trail Runner").getOrThrow()+ assertEquals("v1", item.variants.first().id)+ assertEquals(setOf("v1", "featured"), item.variants.map { it.id }.toSet())+ assertEquals("https://shop.example/api/catalog/search", fake.requests.last().url)+ assertEquals(4, fake.requests.size)+ }+ } finally {+ UcpApi.transport = previous+ }+ }++ @Test+ fun deniedAndRateLimitedDetailCallsNeverTriggerAnotherRequest() = runBlocking {+ val previous = UcpApi.transport+ try {+ for (status in listOf(401, 403, 429)) {+ val fake = DetailTransport(UcpApi.VERSION, product(), product(), status)+ UcpApi.transport = fake+ assertTrue(UcpCatalog.refreshProduct(UcpPlatforms.GENERIC, "shop.example", "v1", "p1", productTitle = "Trail Runner").isFailure)+ assertEquals(2, fake.requests.size)+ }+ } finally {+ UcpApi.transport = previous+ }+ }++ @Test+ fun missingSelectedVariantFailsInsteadOfSubstitutingAnotherOption() = runBlocking {+ val previous = UcpApi.transport+ try {+ UcpApi.transport = DetailTransport(UcpApi.VERSION, product())+ val result = UcpCatalog.refreshProduct(UcpPlatforms.GENERIC, "shop.example", "removed", "p1")+ assertTrue(result.isFailure)+ assertTrue((result.exceptionOrNull() as? UcpHttpException)?.error is UcpError.Unsupported)+ } finally {+ UcpApi.transport = previous+ }+ }++ @Test+ fun deepLinksWithoutSearchSnapshotCanRequestTheVariantDirectly() = runBlocking {+ val previous = UcpApi.transport+ try {+ val fake = DetailTransport(UcpApi.VERSION, product())+ UcpApi.transport = fake+ UcpCatalog.refreshProduct(UcpPlatforms.GENERIC, "shop.example", "v1").getOrThrow()+ assertEquals("v1", obj(fake.requests.last().body!!).text("id"))+ } finally {+ UcpApi.transport = previous+ }+ }++ @Test+ fun globalCatalogRoutesToTheSellerNotTheShopAppProductPage() {+ for (version in listOf(UcpApi.VERSION, UcpApi.APRIL_VERSION)) {+ val seller = """, "seller":{"name":"Trail Supply","domain":"shop.example","url":"https://shop.example"}"""+ val response = obj("""{"ucp":{"version":"$version"},"products":[${product(seller, "https://shop.app/products/p1")}] }""")+ val parsed = UcpCatalog.parseProducts(response, "shopify", "", version).single()+ assertEquals("shop.example", parsed.shopDomain)+ assertEquals("Trail Supply", parsed.storeName)+ assertEquals("shop.example", parsed.variants.single().shopDomain)+ assertEquals("Trail Supply", parsed.variants.single().storeName)+ assertTrue(parsed.checkoutEligible)+ }+ }++ @Test+ fun sellerUrlSupportsIdentityWithoutADomainAndUnsafeSellersStayIneligible() {+ val seller = """, "seller":{"name":"Trail Supply","url":"https://shop.example"}"""+ val valid = obj("""{"ucp":{"version":"${UcpApi.VERSION}"},"products":[${product(seller, "https://shop.app/products/p1")}] }""")+ assertEquals("shop.example", UcpCatalog.parseProducts(valid, "shopify", "", UcpApi.VERSION).single().shopDomain)+ val unsafe = """, "seller":{"name":"Not trusted","domain":"127.0.0.1","url":"http://127.0.0.1"}"""+ val invalid = obj("""{"ucp":{"version":"${UcpApi.VERSION}"},"products":[${product(unsafe, "https://shop.app/products/p1")}] }""")+ val parsed = UcpCatalog.parseProducts(invalid, "shopify", "", UcpApi.VERSION).single()+ assertEquals("", parsed.shopDomain)+ assertFalse(parsed.checkoutEligible)+ }+}