diff --git a/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt b/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt index a02cbce7..a04f7af9 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt @@ -1,6 +1,7 @@ package com.personalization import com.personalization.logs.LogCodes +import kotlin.jvm.internal.DefaultConstructorMarker import com.personalization.logs.LogReasons import com.personalization.logs.SdkLogs @@ -45,6 +46,9 @@ import com.personalization.logs.SdkLogs * device-level data (A/B group, push token, advertising id) is the app's and has no prefix. Android's * Auto Backup restores these files on the user's new device, the `did` among them; see * [SDK.deleteUserCredentials] for the files an app excludes from its backup rules to avoid that. + * @property appDomain the host of API v3, without a scheme: `app.rees46.ru`, unless the shop's cluster has + * its own. The SDK's methods that call API v3 go there. Popups v3 and stories v3 keep their own settings + * of it (`sdk.popups.appHost`, `PersonalizationStories.apiV3Domain`). * * Nothing here picks the core: [Rees46.initialize] and [Rees46.register] ask for the legacy one, and * the new core is for the SDK's Flutter and React Native bridges, which start it with @@ -70,8 +74,69 @@ data class Rees46Config @JvmOverloads constructor( val storageKey: String? = null, val deviceId: String? = null, val sendAdvertisingId: Boolean = false, + val appDomain: String = "app.rees46.ru", ) { + /** + * The constructor of 2.52 and earlier, without [appDomain], in the form Kotlin compiles a call that + * leaves parameters to their defaults: [defaults] marks those parameters, one bit each, in order. + * Apps built against those releases call it; [appDomain] takes its default. Its plain form is one of + * the overloads above. + */ + @Deprecated(message = BEFORE_APP_DOMAIN, level = DeprecationLevel.HIDDEN) + @Suppress("UNUSED_PARAMETER") + constructor( + shopId: String, + apiDomain: String?, + stream: String?, + autoSendPushToken: Boolean, + needReInitialization: Boolean, + addTrailingSlash: Boolean, + tag: String?, + enableAutoPopupPresentation: Boolean, + logLevel: LogLevel?, + storageKey: String?, + deviceId: String?, + sendAdvertisingId: Boolean, + defaults: Int, + marker: DefaultConstructorMarker?, + ) : this( + shopId = shopId, + apiDomain = apiDomain.takeUnless { defaults.leaves(1) } ?: DEFAULTS.apiDomain, + stream = stream.takeUnless { defaults.leaves(2) } ?: DEFAULTS.stream, + autoSendPushToken = if (defaults.leaves(3)) DEFAULTS.autoSendPushToken else autoSendPushToken, + needReInitialization = if (defaults.leaves(4)) DEFAULTS.needReInitialization else needReInitialization, + addTrailingSlash = if (defaults.leaves(5)) DEFAULTS.addTrailingSlash else addTrailingSlash, + tag = tag.takeUnless { defaults.leaves(6) } ?: DEFAULTS.tag, + enableAutoPopupPresentation = if (defaults.leaves(7)) DEFAULTS.enableAutoPopupPresentation else enableAutoPopupPresentation, + logLevel = logLevel.takeUnless { defaults.leaves(8) } ?: DEFAULTS.logLevel, + storageKey = if (defaults.leaves(9)) DEFAULTS.storageKey else storageKey, + deviceId = if (defaults.leaves(10)) DEFAULTS.deviceId else deviceId, + sendAdvertisingId = if (defaults.leaves(11)) DEFAULTS.sendAdvertisingId else sendAdvertisingId, + ) + + /** The `copy` of 2.52 and earlier, without [appDomain], for apps built against them: [appDomain] stays as it is. */ + @Deprecated(message = BEFORE_APP_DOMAIN, level = DeprecationLevel.HIDDEN) + fun copy( + shopId: String = this.shopId, + apiDomain: String = this.apiDomain, + stream: String = this.stream, + autoSendPushToken: Boolean = this.autoSendPushToken, + needReInitialization: Boolean = this.needReInitialization, + addTrailingSlash: Boolean = this.addTrailingSlash, + tag: String = this.tag, + enableAutoPopupPresentation: Boolean = this.enableAutoPopupPresentation, + logLevel: LogLevel = this.logLevel, + storageKey: String? = this.storageKey, + deviceId: String? = this.deviceId, + sendAdvertisingId: Boolean = this.sendAdvertisingId, + ): Rees46Config = copy( + shopId = shopId, apiDomain = apiDomain, stream = stream, autoSendPushToken = autoSendPushToken, + needReInitialization = needReInitialization, addTrailingSlash = addTrailingSlash, tag = tag, + enableAutoPopupPresentation = enableAutoPopupPresentation, logLevel = logLevel, storageKey = storageKey, + deviceId = deviceId, sendAdvertisingId = sendAdvertisingId, appDomain = appDomain, + ) + /** * The constructor of the releases with `coreV2`, for apps built against them: `coreV2` is ignored, * and `true` is logged as `invalid_config` (`bridge_only`). Source that passes it no longer compiles. @@ -123,6 +188,14 @@ data class Rees46Config @JvmOverloads constructor( } private companion object { + const val BEFORE_APP_DOMAIN = "The form of Rees46Config before appDomain, for apps built against 2.52 and earlier." + + /** The defaults of the primary constructor, for the forms of earlier releases. */ + val DEFAULTS = Rees46Config(shopId = "") + + /** Whether a call in the compiled form of a default call left parameter [index] to its default. */ + fun Int.leaves(index: Int): Boolean = this and (1 shl index) != 0 + const val BRIDGE_ONLY_CORE = "Rees46Config.coreV2 is gone: the new core is for the SDK's Flutter and " + "React Native bridges, which start it with Rees46.initializeBridge." diff --git a/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt b/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt index 1baa8ef4..b80089db 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt @@ -13,17 +13,31 @@ import com.personalization.Params.TrackEvent import com.personalization.api.OnApiCallbackListener import com.personalization.api.models.purchase.PurchaseTrackingRequest import com.personalization.api.models.tracking.TrackingSourceType +import com.personalization.api.managers.CartApi import com.personalization.api.managers.CartManager import com.personalization.api.managers.CategoryManager import com.personalization.api.managers.CollectionManager +import com.personalization.api.managers.CollectionsApi import com.personalization.api.managers.InAppNotificationManager +import com.personalization.api.managers.LoyaltyApi import com.personalization.api.managers.LoyaltyManager +import com.personalization.api.managers.NotificationsApi import com.personalization.api.managers.OrdersManager +import com.personalization.api.managers.PredictApi +import com.personalization.api.managers.PredictManager +import com.personalization.api.managers.ProductsApi import com.personalization.api.managers.ProductsManager +import com.personalization.api.managers.ProfileApi import com.personalization.api.managers.ProfileManager -import com.personalization.api.managers.PredictManager import com.personalization.api.managers.RecommendationManager +import com.personalization.api.managers.RecommendationsApi +import com.personalization.api.managers.ReviewsApi +import com.personalization.api.managers.SearchApi import com.personalization.api.managers.SearchManager +import com.personalization.api.managers.SegmentsApi +import com.personalization.api.managers.SlidersApi +import com.personalization.api.managers.StoriesApi +import com.personalization.api.managers.SubscriptionsApi import com.personalization.api.managers.TrackEventManager import com.personalization.api.managers.TrackingApi import com.personalization.api.params.ProfileParams @@ -51,6 +65,7 @@ import com.personalization.core.internal.DeviceStorage import com.personalization.core.internal.InitHooks import com.personalization.core.internal.InitSetup import com.personalization.core.internal.InstanceState +import com.personalization.core.internal.NamespaceCalls import com.personalization.core.internal.EventQueue import com.personalization.core.internal.ProcessAppLifecycle import com.personalization.core.internal.PushHub @@ -62,6 +77,20 @@ import com.personalization.core.internal.StorageLayout import com.personalization.core.internal.StorageMigrations import com.personalization.di.AppModule import com.personalization.di.DaggerSdkComponent +import com.personalization.features.cart.CartApiImpl +import com.personalization.features.collection.CollectionsApiImpl +import com.personalization.features.loyalty.LoyaltyApiImpl +import com.personalization.features.notifications.NotificationsApiImpl +import com.personalization.features.predict.PredictApiImpl +import com.personalization.features.products.ProductsApiImpl +import com.personalization.features.profile.ProfileApiImpl +import com.personalization.features.recommendation.RecommendationsApiImpl +import com.personalization.features.reviews.ReviewsApiImpl +import com.personalization.features.search.SearchApiImpl +import com.personalization.features.segments.SegmentsApiImpl +import com.personalization.features.sliders.SlidersApiImpl +import com.personalization.features.stories.StoriesApiImpl +import com.personalization.features.subscriptions.SubscriptionsApiImpl import com.personalization.features.inAppNotification.impl.ForegroundActivity import com.personalization.features.inAppNotification.impl.PopupPresentation import com.personalization.features.notification.data.mapper.toNotificationData @@ -112,10 +141,10 @@ private const val GAID_KEY = "google_advertising_id" /** * One shop's instance of the SDK: made by [Rees46.initialize], found with [Rees46.instance]. * - * The class stays `open` for apps that subclassed it in earlier releases. The members this release - * adds — [shopId], [deviceId], [sessionId], [state], [onStateChange], [flush] and - * [deleteUserCredentials] — may clash with members of the same name in such a subclass: a subclass - * that declares one of them needs to rename its own. + * The class stays `open` for apps that subclassed it in earlier releases. The members later releases + * added — [shopId], [deviceId], [sessionId], [state], [onStateChange], [flush], [deleteUserCredentials] + * and the namespaces, such as [cart] — may clash with members of the same name in such a subclass: a + * subclass that declares one of them needs to rename its own. */ @OptIn(InternalPersonalizationV3Api::class, BridgeApi::class) open class SDK { @@ -124,7 +153,7 @@ open class SDK { private var onMessageListener: OnMessageListener? = null private var onPushTokenListener: OnPushTokenListener? = null - private var search: Search = Search(JSONObject()) + private var blankSearch: Search = Search(JSONObject()) /** * True once initialize() has wired the Dagger graph. A push can reach the SDK in a process @@ -206,6 +235,138 @@ open class SDK { @Inject lateinit var trackEventManager: TrackEventManager + /** The path of the namespaces' methods: requests with a result on the new core. */ + private val namespaceCalls = NamespaceCalls(core = { core }, dispatchers = { dispatchers }, shopId = { logShopId }) + + /** + * The customer's cart on the server: `sdk.cart.get()`. For the Flutter and React Native bridges: it runs + * on the new core only ([Rees46.initializeBridge]), and on the legacy core every call fails with + * [SdkError.NotInitialized]; see [CartApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val cart: CartApi = CartApiImpl(namespaceCalls) + + /** + * The shop's catalog: `sdk.products.getInfo("37")`, `getList`, `getCounters`, `getCategory`. For the + * Flutter and React Native bridges, on the new core only, as [cart]; see [ProductsApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val products: ProductsApi = ProductsApiImpl(namespaceCalls) + + /** + * The shop's product collections: `sdk.collections.get("12")`. For the Flutter and React Native + * bridges, on the new core only, as [cart]; see [CollectionsApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val collections: CollectionsApi = CollectionsApiImpl(namespaceCalls) + + /** + * The shop's recommendation blocks: `sdk.recommendations.get("block-code")`. For the Flutter and React + * Native bridges, on the new core only, as [cart]; see [RecommendationsApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val recommendations: RecommendationsApi = RecommendationsApiImpl(namespaceCalls) + + /** Whether the last `/init` answer of the new core turned the search agent on (`search.blank_mode`). */ + @Volatile + private var agentSearchEnabled = false + + /** + * Search in the shop's catalog: `sdk.search.blank()`, `instant`, `full`, and the search agent: + * `agentEnabled`, `agentDialog`, `agent`. For the Flutter and React Native bridges, on the new core + * only, as [cart]; see [SearchApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val search: SearchApi = SearchApiImpl(namespaceCalls) { agentSearchEnabled } + + /** + * The customer's profile: `sdk.profile.get()`, `set`, `getLastOrder`. For the Flutter and React Native + * bridges, on the new core only, as [cart]; see [ProfileApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val profile: ProfileApi = ProfileApiImpl(namespaceCalls) { type, signature -> popupsV3?.onContextChange(type, signature) } + + /** + * The customer's subscriptions to channels and to products: `sdk.subscriptions.manage(…)`, `check`, + * `subscribeForPriceDrop` and the others. For the Flutter and React Native bridges, on the new core only, + * as [cart]; see [SubscriptionsApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val subscriptions: SubscriptionsApi = + SubscriptionsApiImpl(namespaceCalls) { type, signature -> popupsV3?.onContextChange(type, signature) } + + /** + * The customer's segments and the device's A/B group: `sdk.segments.add(12)`, `remove`, `get`, + * `getAbGroup`. For the Flutter and React Native bridges, on the new core only, as [cart]; see + * [SegmentsApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val segments: SegmentsApi = SegmentsApiImpl( + namespaceCalls, + abGroup = { if (::userSettingsRepository.isInitialized) userSettingsRepository.getSegmentForABTesting() else null }, + ) { type, signature -> popupsV3?.onContextChange(type, signature) } + + /** + * This shop's push token, the push events the app reports itself and its push callbacks: + * `sdk.notifications.trackClicked(code, type)`. For the Flutter and React Native bridges: it runs on the + * new core only ([Rees46.initializeBridge]), and on the legacy core every call fails with + * [SdkError.NotInitialized]; see [NotificationsApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val notifications: NotificationsApi = NotificationsApiImpl(this, namespaceCalls) + + /** + * The stories blocks: `sdk.stories.get(code)`. For the Flutter and React Native bridges: it runs on the + * new core only ([Rees46.initializeBridge]), and on the legacy core every call fails with + * [SdkError.NotInitialized]; see [StoriesApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val stories: StoriesApi = StoriesApiImpl(namespaceCalls) + + /** + * Forecasts of the customer's behaviour: `sdk.predict.getProbabilityToPurchase()`. For the bridges, on + * the new core only, as [stories]; see [PredictApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val predict: PredictApi = PredictApiImpl(namespaceCalls) + + /** + * The loyalty program on the customer's side: `sdk.loyalty.join(phone)`, `getStatus(phone)`, + * `getPromotions()`. For the bridges, on the new core only, as [stories]; see [LoyaltyApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val loyalty: LoyaltyApi = LoyaltyApiImpl(namespaceCalls) + + /** + * Banner sliders: `sdk.sliders.get(code)`; their banners' events are `tracking.bannerView` and + * `bannerClick`. For the bridges, on the new core only, as [stories]; see [SlidersApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val sliders: SlidersApi = SlidersApiImpl(namespaceCalls) + + /** + * NPS, CSAT and CES ratings, their dictionaries, and the reviews of products: `sdk.reviews.createNps(…)`. + * The polls go to [Rees46Config.appDomain]. For the Flutter and React Native bridges: it runs on the new + * core only ([Rees46.initializeBridge]), and on the legacy core every call fails with + * [SdkError.NotInitialized]; see [ReviewsApi]. Hidden from Java. + */ + @BridgeApi + @get:JvmSynthetic + val reviews: ReviewsApi = ReviewsApiImpl(namespaceCalls) + @Inject lateinit var searchManager: SearchManager @@ -686,6 +847,7 @@ open class SDK { ) initNetworkUseCase(url = baseUrl) + networkRepository.appDomain = config.appDomain released = false val coreV2 = CoreSelection.resolve(coreV2Requested, shopId) if (coreV2) { @@ -693,7 +855,7 @@ open class SDK { val lifecycle = ProcessAppLifecycle() lateinit var init: CoreInit // The core gets its /init and its queue before it takes a request: none goes without them. - val core = networkRepository.useCoreV2(shopId, connectivity, dispatchers) { core -> + val core = networkRepository.useCoreV2(shopId, connectivity, dispatchers, config.appDomain) { core -> init = createCoreInit(core, connectivity, lifecycle, context, config, storage, autoSendPushToken, needReInitialization, pushOnly) core.init = init // The token's rules are the new core's from the start: one FCM gives before /init waits for it. @@ -861,6 +1023,7 @@ open class SDK { }, hooks = object : InitHooks { override fun onAnswer(answer: JSONObject, fresh: Boolean) { + agentSearchEnabled = answer.optJSONObject(INIT_SEARCH)?.optString(INIT_BLANK_MODE) == BLANK_MODE_AGENT val response = answer.mapToSdkInitResponse() // A popup is shown from a fresh answer only, never again from the saved one. if (fresh) response?.popupDto?.let { inAppNotificationManager.shopPopUp(popupDto = it) } @@ -1370,7 +1533,7 @@ open class SDK { params: SearchParams, listener: OnApiCallbackListener ) { - if (search != null) { + if (blankSearch != null) { params.put(InternalParameter.SEARCH_TYPE, type.value) .put(InternalParameter.SEARCH_QUERY, query) getAsync(SEARCH_FIELD, params.build(), listener) @@ -1387,11 +1550,11 @@ open class SDK { ) ) fun searchBlank(listener: OnApiCallbackListener) { - if (search != null) { - if (search?.blank == null) { + if (blankSearch != null) { + if (blankSearch?.blank == null) { getAsync(BLANK_SEARCH_FIELD, Params().build(), object : OnApiCallbackListener() { override fun onSuccess(response: JSONObject?) { - search?.blank = response + blankSearch?.blank = response listener.onSuccess(response) } @@ -1400,7 +1563,7 @@ open class SDK { } }) } else { - listener.onSuccess(search?.blank) + listener.onSuccess(blankSearch?.blank) } } else { log(LogLevel.WARNING, LogCodes.SDK_LOG, "Search not initialized") @@ -1965,18 +2128,40 @@ open class SDK { * it as `source`) before it is handed over: a `/push` that goes while the tap is on its way — to the * instance that took this one's place — carries it too. When no queue takes the tap, the source is put * back as it was. + * + * [ended] hears, once, how the call ended: null once a queue accepted the event, or for a repeat — one + * accepted already, or one parked meanwhile once the first is accepted — otherwise why no queue took it. */ - private fun queuePushEvent(event: PushEvent, code: String, type: String, accepted: (SDK) -> Unit) { - if (core !is CoreV2) return - val reservation = PushHub.reserve(shopId, event, code) { queuePushEvent(event, code, type, accepted) } + private fun queuePushEvent(event: PushEvent, code: String, type: String, accepted: (SDK) -> Unit, ended: (SdkError?) -> Unit = {}) { + if (core !is CoreV2) { + ended(SdkError.NotInitialized) + return + } + val reservation = PushHub.reserve(shopId, event, code, repeat = { ended(null) }) { queuePushEvent(event, code, type, accepted, ended) } if (reservation != PushHub.Reservation.TAKEN) { val message = if (reservation == PushHub.Reservation.REPEAT) "The push event was handled already" else "The push event is being handled already: this one goes only if that one is not accepted" log(LogLevel.DEBUG, LogCodes.PUSH, message, mapOf("event" to event.name.lowercase(Locale.ROOT), "reason" to REASON_REPEAT)) + if (reservation == PushHub.Reservation.REPEAT) ended(null) return } val undoSource = if (event == PushEvent.CLICKED && TrackingSourceType.entries.any { it.value == type }) setTapSource(type, code) else null - offerPushEvent(event, code, type, undoSource, accepted) + offerPushEvent(event, code, type, undoSource, accepted, ended) + } + + /** + * For `sdk.notifications`: the push [event] of the message [code] of mailing [type] that the app reports + * itself, through the queue like one [Rees46.handlePush] sees ([queuePushEvent]) — once per message in a + * process, a tap with its tracking source — but without the push callbacks: the app knows of it already. + * [ended] hears null once the event is accepted or was accepted already, otherwise why it was not: + * `notInitialized` after [release], `shopBlocked` for a refused shop. The new core only. + */ + internal fun trackPushEvent(event: PushEvent, code: String, type: String, ended: (SdkError?) -> Unit) { + if (released) { + ended(SdkError.NotInitialized) + return + } + queuePushEvent(event, code, type, accepted = {}, ended = ended) } /** @@ -2021,25 +2206,28 @@ open class SDK { * brought up for a push gave way to the app's): it goes to that one. * - Refused otherwise (the instance released, the shop refused): it is not sent and may come again * ([PushHub.release]); a tap's source goes back as it was ([undoSource]). + * [ended] hears null when it is accepted, otherwise the refusal. */ - private fun offerPushEvent(event: PushEvent, code: String, type: String, undoSource: (() -> Unit)?, accepted: (SDK) -> Unit) { + private fun offerPushEvent(event: PushEvent, code: String, type: String, undoSource: (() -> Unit)?, accepted: (SDK) -> Unit, ended: (SdkError?) -> Unit = {}) { val shop = shopId val core = core as? CoreV2 if (core == null) { undoSource?.invoke() PushHub.release(shop, event, code) + ended(SdkError.NotInitialized) return } core.accept(pathOf(event), JSONObject().put(CODE_FIELD, code).put(TYPE_FIELD, type)) { refused -> if (refused == null) { PushHub.confirm(shop, event, code) accepted(this) + ended(null) return@accept } val live = SdkRegistry.byShopId(shop) if (refused == SdkError.NotInitialized && live != null && live !== this) { log(LogLevel.DEBUG, LogCodes.PUSH, "The push event goes to the shop's instance that took this one's place", mapOf("event" to event.name.lowercase(Locale.ROOT))) - live.offerPushEvent(event, code, type, undoSource, accepted) + live.offerPushEvent(event, code, type, undoSource, accepted, ended) return@accept } // Before the repeats parked meanwhile try again: one of them may set the source anew. @@ -2050,6 +2238,7 @@ open class SDK { } PushHub.release(shop, event, code) log(LogLevel.WARNING, LogCodes.PUSH, "The push event was not accepted", mapOf("event" to event.name.lowercase(Locale.ROOT), "error" to refused.javaClass.simpleName)) + ended(refused) } } @@ -2141,6 +2330,9 @@ open class SDK { private const val SEGMENT_PHONE_FIELD = "phone" private const val ITEM_IDS_FIELD = "item_ids" private const val SEGMENTS_FIELD = "segments" + private const val INIT_SEARCH = "search" + private const val INIT_BLANK_MODE = "blank_mode" + private const val BLANK_MODE_AGENT = "agent" private const val SEARCH_FIELD = "search" private const val REMOVE_FIELD = "remove" private const val CODE_FIELD = "code" diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/CartApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/CartApi.kt new file mode 100644 index 00000000..3b616490 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/CartApi.kt @@ -0,0 +1,32 @@ +package com.personalization.api.managers + +import com.personalization.api.responses.cart.CartItem +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * The customer's cart on the server — the `cart` namespace: `sdk.cart.get()`. The server builds the cart + * from the cart events of [TrackingApi] (`addToCart`, `syncCart`, `removeFromCart`) and finds it by the + * device's `did`; the SDK adds `did` and the other common fields itself. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + */ +@BridgeApi +interface CartApi { + + /** + * The cart's items (`GET /products/cart`); an empty cart is an empty list. An item without a product id + * is left out, and one without a quantity counts as 1. + * + * @throws SdkException with [SdkError.NotInitialized] (the legacy core, an instance not initialized or + * released), [SdkError.ShopBlocked], [SdkError.Network], [SdkError.Timeout], [SdkError.Http] (`404` for a + * `did` the server does not know), [SdkError.Decoding] or [SdkError.Cancelled] (`release()`). + */ + suspend fun get(): List + + /** [get] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun get(listener: CompletionListener>) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/CollectionsApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/CollectionsApi.kt new file mode 100644 index 00000000..40c72b05 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/CollectionsApi.kt @@ -0,0 +1,31 @@ +package com.personalization.api.managers + +import com.personalization.api.models.collections.CollectionResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * Product collections the shop sets up in its account — the `collections` namespace: + * `sdk.collections.get("12")`. The SDK adds `did` and the other common fields itself. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + */ +@BridgeApi +interface CollectionsApi { + + /** + * The products of the collection [collectionId] (`GET /collection/{collectionId}`). + * + * @throws SdkException with [SdkError.NotInitialized] (the legacy core, an instance not initialized or + * released), [SdkError.ShopBlocked], [SdkError.InvalidArgument] (an empty [collectionId], before any + * request), [SdkError.Network], [SdkError.Timeout], [SdkError.Http] (`400` for a collection the shop + * does not have or that is off), [SdkError.Decoding] or [SdkError.Cancelled] (`release()`). + */ + suspend fun get(collectionId: String): CollectionResponse + + /** [get] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun get(collectionId: String, listener: CompletionListener) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/LoyaltyApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/LoyaltyApi.kt new file mode 100644 index 00000000..a6517cee --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/LoyaltyApi.kt @@ -0,0 +1,91 @@ +package com.personalization.api.managers + +import com.personalization.api.models.loyalty.LoyaltyMember +import com.personalization.api.models.loyalty.LoyaltyPromotion +import com.personalization.api.models.loyalty.LoyaltyStatus +import com.personalization.api.models.profile.Gender +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * The loyalty program on the customer's side — the `loyalty` namespace: `sdk.loyalty.join(phone)`, + * `getStatus(phone)`, `getPromotions()`. The SDK never sends the shop's secret: [join] and [getStatus] + * answer only for a shop that allows the loyalty methods from the front end (otherwise `403`), and + * [getPromotions] finds the customer by the device's `did`. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + * + * Every method fails with [SdkException] — [SdkError.NotInitialized] (the legacy core, an instance not + * initialized or released), [SdkError.ShopBlocked], [SdkError.Network], [SdkError.Timeout], [SdkError.Http] + * (`404` without a loyalty program, `402` when it is off or not paid, `403` when it needs the secret, `400` + * for a wrong argument or an unknown customer), [SdkError.Decoding] or [SdkError.Cancelled] (`release()`) — + * and with [SdkError.InvalidArgument], before any request, for the arguments it names. + */ +@BridgeApi +interface LoyaltyApi { + + /** + * Makes [phone] a member of the loyalty program (`POST /loyalty/members/join`); the server finds or + * creates the customer by it. A phone already registered is a success with the same member, and the + * server updates the name, gender and birthday. + * + * [SdkError.InvalidArgument] for an empty [phone], or a [birthday] that is not an existing date as + * `YYYY-MM-DD`: a birthday the server cannot read erases the one it has. + * [gender] goes as `m` or `f`, the only values the server takes. + */ + suspend fun join( + phone: String, + firstName: String? = null, + lastName: String? = null, + gender: Gender? = null, + birthday: String? = null, + ): LoyaltyMember + + /** + * Whether [phone] is a member, and on which level (`GET /loyalty/members/status`). The server keeps the + * digits only. Someone who is not a member is a success with `isMember = false`. + * + * [SdkError.InvalidArgument] for an empty [phone]. + */ + suspend fun getStatus(phone: String): LoyaltyStatus + + /** + * The active promotions that suit the customer and their cart (`GET /loyalty/promos/for-client`); none + * is an empty list. [locationId] is the point of sale or city, [promoCodes] the customer's promo codes, + * [chargeBonuses] whether bonuses are spent (the server takes `false` without it), [currentTime] the + * local time at the point of sale as `HH:MM`, for promotions by the hour. + * + * [SdkError.InvalidArgument] for a [currentTime] that is not `HH:MM`, or an empty promo code. + */ + suspend fun getPromotions( + locationId: String? = null, + promoCodes: List? = null, + chargeBonuses: Boolean? = null, + currentTime: String? = null, + ): List + + /** [join] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun join( + phone: String, + firstName: String?, + lastName: String?, + gender: Gender?, + birthday: String?, + listener: CompletionListener, + ) + + /** [getStatus] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getStatus(phone: String, listener: CompletionListener) + + /** [getPromotions] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getPromotions( + locationId: String?, + promoCodes: List?, + chargeBonuses: Boolean?, + currentTime: String?, + listener: CompletionListener>, + ) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/NotificationsApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/NotificationsApi.kt new file mode 100644 index 00000000..2b8f518e --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/NotificationsApi.kt @@ -0,0 +1,81 @@ +package com.personalization.api.managers + +import com.personalization.PushProvider +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.PushCallbacks +import com.personalization.core.PushToken +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * Mobile pushes of one shop — the `notifications` namespace: the device's push token, the push events an + * app that parses its pushes itself reports (`delivered`, `opened`, `clicked`, `closed`, decision 0004) and + * the push callbacks. A push the SDK sees itself goes through `Rees46.handlePush`, which finds its shop. + * + * The push events go through the instance's queue, as the tracking events do: a call ends once its event is + * accepted — written to disk — not once the server has it, and the SDK adds `shop_id`, `did`, `stream` and + * `segment` itself, never `sid`. One event of one message (its `code`) goes once per process: a repeat sends + * nothing and ends in success. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On an + * instance of the legacy core a call sends nothing, a call with a result fails with + * [SdkError.NotInitialized], and the log says why (`core_flag_mismatch`). + */ +@BridgeApi +interface NotificationsApi { + + /** + * The push of message [code] (the push's `id`) of mailing [type] (`bulk`, `chain`, `transactional`, + * `digest`) reached the app: `POST track/delivered` through the queue. [listener] hears, once, on the + * main thread, success once the event is accepted or was accepted before, or a failure with + * [SdkError.InvalidArgument] for an empty [code] or [type], [SdkError.NotInitialized] or + * [SdkError.ShopBlocked]; never a network error: the event waits in the queue. The push callbacks do not + * hear of it: the app knows of it already. + */ + fun trackDelivered(code: String, type: String, listener: CompletionListener? = null) + + /** The notification of the push was shown: `POST track/opened`; otherwise as [trackDelivered]. */ + fun trackOpened(code: String, type: String, listener: CompletionListener? = null) + + /** + * The notification of the push was tapped: `POST track/clicked`; otherwise as [trackDelivered]. A [type] + * of `TrackingSourceType` also sets the tracking source for 48 hours, as `tracking.setSource` does: the + * `/push` events carry it as `source`. + */ + fun trackClicked(code: String, type: String, listener: CompletionListener? = null) + + /** The notification of the push was dismissed without a tap: `POST track/closed`; otherwise as [trackDelivered]. */ + fun trackClosed(code: String, type: String, listener: CompletionListener? = null) + + /** + * The push token the SDK knows for this shop, read from the storage without the network: [provider]'s; + * without one, that of the provider whose token the shop sent last, or the device's when it sent none, + * FCM before HMS. Null when there is none, on the legacy core, and after `release()`. + */ + fun getPushToken(provider: PushProvider? = null): PushToken? + + /** + * A [token] the app got from [provider] itself (its own messaging service, or `autoSendPushToken = + * false`): kept for the device and sent to this shop's server, `POST mobile_push_tokens` with + * `platform=android` and `push_provider` `firebase` or `huawei`. A token the shop sent this week ends in + * success without a request; a new one goes at once. The send waits for the instance to be ready — it + * needs the `did` — without a limit of its own: cancelling the call stops the wait for its answer, not + * the send. + * + * @throws SdkException with [SdkError.InvalidArgument] (an empty [token]), [SdkError.NotInitialized] (the + * legacy core, an instance not initialized or released), [SdkError.ShopBlocked], [SdkError.Network], + * [SdkError.Timeout], [SdkError.Http] (`400` without a token or a client, `403` for an unknown or + * disabled shop, `404` without `shop_id`) or [SdkError.Decoding] (a `2xx` answer with `"status": "error"`). + */ + suspend fun setPushToken(token: String, provider: PushProvider) + + /** [setPushToken] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun setPushToken(token: String, provider: PushProvider, listener: CompletionListener) + + /** + * This shop's push callbacks, as `SDK.setPushCallbacks` sets them: a new call replaces the ones before, + * `PushCallbacks()` clears them. Nothing on the legacy core. + */ + fun setCallbacks(callbacks: PushCallbacks) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/PredictApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/PredictApi.kt new file mode 100644 index 00000000..d6b0d8fd --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/PredictApi.kt @@ -0,0 +1,34 @@ +package com.personalization.api.managers + +import com.personalization.api.models.predict.PurchaseProbability +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * Forecasts of the customer's behaviour — the `predict` namespace: `sdk.predict.getProbabilityToPurchase()`. + * The customer is the device's `did`, which the SDK adds itself; contacts are not sent. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + */ +@BridgeApi +interface PredictApi { + + /** + * How likely the customer is to buy (`GET /api/v3/cdp/users/probability-to-purchase` on + * `Rees46Config.appDomain`), from the products they viewed, put in the cart or in favorites over the last + * days. It waits for the instance's first `/init`, which gives the device its `did`. + * + * @throws SdkException with [SdkError.NotInitialized] (the legacy core, an instance not initialized or + * released), [SdkError.ShopBlocked], [SdkError.Network], [SdkError.Timeout], [SdkError.Http] (`400` + * without a `did`, `402` for a shop that does not pay or has no `cdp` service, `403` for an inactive or + * restricted one, `404` for an unknown one), [SdkError.Decoding] (an answer without a numeric + * `probability`) or [SdkError.Cancelled] (`release()`). + */ + suspend fun getProbabilityToPurchase(): PurchaseProbability + + /** [getProbabilityToPurchase] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getProbabilityToPurchase(listener: CompletionListener) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/PredictManager.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/PredictManager.kt index 608fab6a..6c88b3a9 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/PredictManager.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/PredictManager.kt @@ -6,10 +6,16 @@ import com.personalization.api.responses.predict.PurchasePredictResponse interface PredictManager { /** - * GET predict/probability-to-purchase — predicted purchase probability for the current visitor. + * The predicted purchase probability for the customer of this device (`GET + * /api/v3/cdp/users/probability-to-purchase` on `Rees46Config.appDomain`, `app.rees46.ru` unless the shop's + * cluster has its own). It waits for the device's `did`. A customer the server does not know has + * `probability` 0 and an empty `clientId`. * - * @param params Optional identifiers (email, phone, telegram_id, loyalty_id). At least one of - * `did` (from SDK) or these fields is required by the API. + * [onError] gets the HTTP code of an answer outside `2xx` (`400` without a `did`, `402` for a shop that + * does not pay or has no `cdp` service, `403` for an inactive or restricted one, `404` for an unknown + * one) with its body, and `-1` for an answer without a numeric `probability` or a failure without one. + * + * @param params Not sent: the server finds the customer by the device's `did`, which the SDK sends. */ fun getProbabilityToPurchase( params: PurchasePredictParams = PurchasePredictParams(), diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ProductsApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ProductsApi.kt new file mode 100644 index 00000000..6aab5b53 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ProductsApi.kt @@ -0,0 +1,66 @@ +package com.personalization.api.managers + +import com.personalization.api.models.products.CategoryRequest +import com.personalization.api.models.products.CategoryResponse +import com.personalization.api.models.products.Product +import com.personalization.api.models.products.ProductsListRequest +import com.personalization.api.models.products.ProductsListResponse +import com.personalization.api.responses.products.counters.ProductCountersResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * The shop's catalog — the `products` namespace: `sdk.products.getInfo("37")`. Each method asks the API + * once and answers with a model; the SDK adds `did` and the other common fields itself. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + * + * Every method throws [SdkException] with [SdkError.NotInitialized] (the legacy core, an instance not + * initialized or released), [SdkError.ShopBlocked], [SdkError.InvalidArgument] (before any request), + * [SdkError.Network], [SdkError.Timeout], [SdkError.Http], [SdkError.Decoding] or [SdkError.Cancelled] + * (`release()`). Nothing repeats a request. + */ +@BridgeApi +interface ProductsApi { + + /** + * The product card of [itemId] (`GET /products/get`); null for a product the catalog does not have. + * An empty [itemId] is `invalidArgument`. + */ + suspend fun getInfo(itemId: String): Product? + + /** + * A page of the catalog's listing with its facets (`GET /products`); without a [request], the first + * page of the whole catalog. + */ + suspend fun getList(request: ProductsListRequest = ProductsListRequest()): ProductsListResponse + + /** + * How much interest [itemId] draws (`GET /products/counters`): views, carts and purchases today and in + * the last 30 minutes, and subscriptions to its price and its stock. An empty [itemId] is + * `invalidArgument`. + */ + suspend fun getCounters(itemId: String): ProductCountersResponse + + /** + * The screen of the category [categoryId]: its products and facets. It asks for the listing of that + * category (`GET /products` with `categories`), which is what the server's `/category/{id}` does. + * An empty [categoryId] is `invalidArgument`. + */ + suspend fun getCategory(categoryId: String, request: CategoryRequest = CategoryRequest()): CategoryResponse + + /** [getInfo] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getInfo(itemId: String, listener: CompletionListener) + + /** [getList] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getList(request: ProductsListRequest, listener: CompletionListener) + + /** [getCounters] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getCounters(itemId: String, listener: CompletionListener) + + /** [getCategory] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getCategory(categoryId: String, request: CategoryRequest, listener: CompletionListener) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ProfileApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ProfileApi.kt new file mode 100644 index 00000000..01945330 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ProfileApi.kt @@ -0,0 +1,51 @@ +package com.personalization.api.managers + +import com.personalization.api.models.products.Product +import com.personalization.api.models.profile.Profile +import com.personalization.api.models.profile.ProfileUpdateRequest +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * The customer's profile — the `profile` namespace: `sdk.profile.get()`. The API finds the customer by the + * device's `did`, which the SDK adds with the other common fields itself; the SDK never sends the shop's + * secret key, and keeps none of the personal data [set] sends. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + * + * Every method throws [SdkException] with [SdkError.NotInitialized] (the legacy core, an instance not + * initialized or released), [SdkError.ShopBlocked], [SdkError.InvalidArgument] (before any request), + * [SdkError.Network], [SdkError.Timeout], [SdkError.Http], [SdkError.Decoding] or [SdkError.Cancelled] + * (`release()`). Nothing repeats a request: whether to ask again is the app's choice. + */ +@BridgeApi +interface ProfileApi { + + /** The customer's profile (`GET /profile`); `http(404)` for a `did` the server does not know. */ + suspend fun get(): Profile + + /** + * Writes the properties of [request] to the profile (`POST /profile/set`), not through the queue: the + * result is the server's answer. Call it on sign-in, on a change of city and on every launch, with the + * current id and city. See [ProfileUpdateRequest] for what fails with `invalidArgument`. + */ + suspend fun set(request: ProfileUpdateRequest) + + /** + * The products of the customer's last order (`GET /orders/last_for_user`); an empty list without + * orders, `http(400)` for a `did` the server does not know. + */ + suspend fun getLastOrder(): List + + /** [get] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun get(listener: CompletionListener) + + /** [set] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun set(request: ProfileUpdateRequest, listener: CompletionListener) + + /** [getLastOrder] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getLastOrder(listener: CompletionListener>) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/RecommendationsApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/RecommendationsApi.kt new file mode 100644 index 00000000..9e767579 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/RecommendationsApi.kt @@ -0,0 +1,35 @@ +package com.personalization.api.managers + +import com.personalization.api.models.recommendations.RecommendationRequest +import com.personalization.api.models.recommendations.RecommendationResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * Recommendation blocks the shop sets up in its account — the `recommendations` namespace: + * `sdk.recommendations.get("block-code")`. The SDK adds `did`, the A/B group (`segment`) and the other + * common fields itself. For a view, a cart or a purchase to count for the block, the app passes the source + * `TrackingSource(TrackingSourceType.DYNAMIC, code)` to `sdk.tracking`. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + */ +@BridgeApi +interface RecommendationsApi { + + /** + * The products of the block [code] (`GET /recommend/{code}`) for where the customer is ([request]). + * + * @throws SdkException with [SdkError.NotInitialized] (the legacy core, an instance not initialized or + * released), [SdkError.ShopBlocked], [SdkError.InvalidArgument] (an empty [code], a limit below 1, + * `withLocations` without `extended`; before any request), [SdkError.Network], [SdkError.Timeout], + * [SdkError.Http] (`404` for a block the shop does not have, `402` for a service not paid for), + * [SdkError.Decoding] or [SdkError.Cancelled] (`release()`). + */ + suspend fun get(code: String, request: RecommendationRequest = RecommendationRequest()): RecommendationResponse + + /** [get] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun get(code: String, request: RecommendationRequest, listener: CompletionListener) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ReviewsApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ReviewsApi.kt new file mode 100644 index 00000000..cd6ec08f --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/ReviewsApi.kt @@ -0,0 +1,204 @@ +package com.personalization.api.managers + +import com.personalization.api.responses.reviews.ClientReview +import com.personalization.api.responses.reviews.CesCampaign +import com.personalization.api.responses.reviews.CsatCampaign +import com.personalization.api.responses.reviews.NpsCategory +import com.personalization.api.responses.reviews.PollChannel +import com.personalization.api.responses.reviews.PollReview +import com.personalization.api.responses.reviews.ProductReviewsResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * The customer's feedback — the `reviews` namespace: NPS, CSAT and CES ratings with the dictionaries their + * forms take questions and thanks from, and the reviews of products. The app collects a rating with its + * own form and sends it with a `create…` method; the SDK adds `did` and the other common fields itself, + * and the server finds the customer by the device's `did`. Nothing here takes a contact or the shop's secret. + * + * The polls go to the host of API v3, `Rees46Config.appDomain` (`app.rees46.ru` unless the shop's cluster + * has its own); the reviews of products to the API's host, `Rees46Config.apiDomain`. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + * + * Every method throws [SdkException] with [SdkError.NotInitialized] (the legacy core, an instance not + * initialized or released), [SdkError.ShopBlocked], [SdkError.InvalidArgument] (refused before a request, + * as each method says), [SdkError.Network], [SdkError.Timeout], [SdkError.Http], [SdkError.Decoding] or + * [SdkError.Cancelled] (`release()`). What an [SdkError.Http] code means: + * - the polls: `400` — wrong parameters, or a rating the server refuses (`label` up to 255 characters, + * `comment` up to 5000); `402` — the project is not paid; `403` — the project is inactive, or the request + * has no `did`; `404` — no shop, customer, channel, category or campaign, or the order is another + * customer's; `429` — more than 30 ratings a minute from the device, or 120 from the IP; + * - the reviews of products: `400` — no order; `403` — the reviews service is not enabled; `404` — no + * product, order or customer. + * + * None of them changes the instance's state: it may refuse one service, not the shop. Nothing repeats a + * request. + * + * Each method has a twin for Java and for code outside coroutines that ends in a [CompletionListener]: its + * result comes once, on the main thread. + */ +@BridgeApi +interface ReviewsApi { + + /** + * Sends an NPS rating — how ready the customer is to recommend the shop + * (`POST /api/v3/polls/nps/reviews`). Its question and thanks are those of the [NpsCategory] + * ([getNpsCategories]) for the rating. An empty or blank [orderId], [comment] or [label] is not sent. + * + * Sent again the same day with the same channel, category, order and label, it does not make a new + * review: the server updates the earlier one, and [PollReview.id] is that review's. A repeat with the + * same rating and no comment keeps the earlier comment; a changed rating without a comment clears it. + * A rating with a comment — the answer to the question after the rating — goes to the latest review of + * the last 90 days with the same channel, category, order, label and rating and no comment, if there is + * one, rather than making another. + * + * @param rate 0 to 10. + * @param channel the code of the channel in the shop's account (`android_app`), not empty. + * @param category the code of the category — what is rated —, not empty. + * @param orderId the order rated, when an order is. Another customer's order is `http(404)`; one the + * server does not know is dropped, and the rating is saved without it. + * @param comment the customer's comment. + * @param label a mark to group the reviews by in the report. + * @throws SdkException with [SdkError.InvalidArgument] for [rate] outside 0–10, an empty [channel] or + * [category]; otherwise as [ReviewsApi] says. + */ + suspend fun createNps( + rate: Int, + channel: String, + category: String, + orderId: String? = null, + comment: String? = null, + label: String? = null, + ): PollReview + + /** + * Sends a CSAT rating — how satisfied the customer is with one interaction: delivery, support, checkout + * (`POST /api/v3/polls/csat/reviews`). Its question and thanks are those of the [CsatCampaign] + * ([getCsatCampaigns]); the rest is as [createNps] says. + * + * @param rate 1 to 5. + * @param campaign the code of the campaign — what is rated —, not empty. + * @throws SdkException with [SdkError.InvalidArgument] for [rate] outside 1–5, an empty [channel] or + * [campaign]; otherwise as [ReviewsApi] says. + */ + suspend fun createCsat( + rate: Int, + channel: String, + campaign: String, + orderId: String? = null, + comment: String? = null, + label: String? = null, + ): PollReview + + /** + * Sends a CES rating — how much effort a task took the customer (`POST /api/v3/polls/ces/reviews`). + * Its question and thanks are those of the [CesCampaign] ([getCesCampaigns]); the rest is as + * [createCsat] says. + * + * @param rate 1 to 7. + * @throws SdkException with [SdkError.InvalidArgument] for [rate] outside 1–7, an empty [channel] or + * [campaign]; otherwise as [ReviewsApi] says. + */ + suspend fun createCes( + rate: Int, + channel: String, + campaign: String, + orderId: String? = null, + comment: String? = null, + label: String? = null, + ): PollReview + + /** The shop's NPS categories (`GET /api/v3/polls/nps/categories`); none is an empty list. */ + suspend fun getNpsCategories(): List + + /** + * The shop's channels of ratings (`GET /api/v3/polls/nps/channels`), common to NPS, CSAT and CES: the API + * serves them on the path of NPS only. A form usually knows its channel already. None is an empty list. + */ + suspend fun getNpsChannels(): List + + /** The shop's CSAT campaigns (`GET /api/v3/polls/csat/campaigns`); none is an empty list. */ + suspend fun getCsatCampaigns(): List + + /** The shop's CES campaigns (`GET /api/v3/polls/ces/campaigns`); none is an empty list. */ + suspend fun getCesCampaigns(): List + + /** + * The published reviews of a product and its rating, for the product's card (`GET /reviews/product`). + * The summary counts every published review; [limit] and [offset] page only the list, the newest first. + * Without reviews the list is empty, `count` is 0 and `averageRating` null. + * + * @param itemId the product's id, not empty. + * @param limit 1 to 100; the server gives 20 without it. + * @param offset 0 or more; 0 without it. + * @throws SdkException with [SdkError.InvalidArgument] for an empty [itemId], [limit] outside 1–100 or a + * negative [offset]; otherwise as [ReviewsApi] says. + */ + suspend fun getProductReviews(itemId: String, limit: Int? = null, offset: Int? = null): ProductReviewsResponse + + /** + * The reviews the device's customer wrote in one order, in every state of moderation + * (`GET /reviews/client`) — say, to show a rating beside a product in the order history. No reviews is an + * empty list; there are no pages. The order has to be the customer's: none, or another customer's, is + * `http(404)`, and so is a customer the CDP does not know — the method makes none. + * + * @param orderId the order's id, not empty. + * @throws SdkException with [SdkError.InvalidArgument] for an empty [orderId]; otherwise as [ReviewsApi] says. + */ + suspend fun getClientReviews(orderId: String): List + + /** [createNps] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun createNps( + rate: Int, + channel: String, + category: String, + orderId: String?, + comment: String?, + label: String?, + listener: CompletionListener, + ) + + /** [createCsat] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun createCsat( + rate: Int, + channel: String, + campaign: String, + orderId: String?, + comment: String?, + label: String?, + listener: CompletionListener, + ) + + /** [createCes] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun createCes( + rate: Int, + channel: String, + campaign: String, + orderId: String?, + comment: String?, + label: String?, + listener: CompletionListener, + ) + + /** [getNpsCategories] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getNpsCategories(listener: CompletionListener>) + + /** [getNpsChannels] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getNpsChannels(listener: CompletionListener>) + + /** [getCsatCampaigns] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getCsatCampaigns(listener: CompletionListener>) + + /** [getCesCampaigns] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getCesCampaigns(listener: CompletionListener>) + + /** [getProductReviews] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getProductReviews(itemId: String, limit: Int?, offset: Int?, listener: CompletionListener) + + /** [getClientReviews] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun getClientReviews(orderId: String, listener: CompletionListener>) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SearchApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SearchApi.kt new file mode 100644 index 00000000..5ce13885 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SearchApi.kt @@ -0,0 +1,117 @@ +package com.personalization.api.managers + +import com.personalization.api.models.search.AgentDialogResponse +import com.personalization.api.models.search.AgentResponse +import com.personalization.api.models.search.SearchBlankResponse +import com.personalization.api.models.search.SearchFullRequest +import com.personalization.api.models.search.SearchFullResponse +import com.personalization.api.models.search.SearchInstantResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * Search in the shop's catalog — the `search` namespace: `sdk.search.instant("phone")`. The SDK adds + * `did` and the other common fields itself. The methods send no search event: when the customer searched, + * the app calls `sdk.tracking.search`; a product opened from the results counts for the search with the + * source `TrackingSource(TrackingSourceType.INSTANT_SEARCH or FULL_SEARCH, query)`. + * + * The search agent (AI search) is a dialog the shop may show instead of the empty search: [agentEnabled] + * says whether to, [agentDialog] opens the dialog and [agent] sends the customer's message. It lives on the + * host of API v3, `Rees46Config.appDomain`. A product opened from the agent's answer counts for it with the + * source `TrackingSource(agent_search, sessionId)`, which `TrackingSourceType` gets with the next major + * release; its link already carries that attribution. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request, and + * [agentEnabled] is false. + * + * Every method throws [SdkException] with [SdkError.NotInitialized] (the legacy core, an instance not + * initialized or released), [SdkError.ShopBlocked], [SdkError.InvalidArgument] (before any request), + * [SdkError.Network], [SdkError.Timeout], [SdkError.Http], [SdkError.Decoding] or [SdkError.Cancelled] + * (`release()`). Nothing repeats a request. + */ +@BridgeApi +interface SearchApi { + + /** + * Whether the shop shows the search agent instead of the empty search: true when the last `/init` + * answer's `search.blank_mode` is `agent`; false for any other value, without the field, and before + * any answer. Read at once, without a request. + */ + val agentEnabled: Boolean + + /** + * What to show in an empty search field (`GET /search/blank`): the customer's recent queries and + * products, or popular ones, suggestions, popular categories, brands and links. + */ + suspend fun blank(): SearchBlankResponse + + /** + * Products and suggestions as the customer types [query] (`GET /search`, `instant_search`). An empty + * [query] is `invalidArgument`. [excludedMerchants] is sent only with [locations]: the server looks + * for merchants in those locations and finds no product without them. + */ + suspend fun instant( + query: String, + locations: List? = null, + excludedMerchants: List? = null, + excludedBrands: List? = null, + ): SearchInstantResponse + + /** + * The screen of the results of [query] (`GET /search`, `full_search`) with the filters, order and page + * of [request]. An empty [query] is `invalidArgument`. + */ + suspend fun full(query: String, request: SearchFullRequest = SearchFullRequest()): SearchFullResponse + + /** + * The customer's dialog with the search agent (`GET /api/v3/storefront/search/agent`): the last 20 + * sessions and the messages of [sessionId], or of the latest session without one. [locations] — the + * customer's locations, sent joined with commas; the profile's location without them. Call it when the + * agent's window opens. The products of the messages come with their current price and stock; a product + * no longer available is left out. + * + * [sessionId] is 64-bit, as [com.personalization.api.models.search.AgentSession.id]. + * + * Besides the errors of every method: `http(404)` for a session not found or of another customer, + * `http(429)` over the limit (60 requests a minute from a device), `http(503)` when the agent is + * unavailable or the customer is in the control group of search — show [blank] instead; `http(402)` + * when the shop has no search service; `http(403)` for an inactive shop. + */ + suspend fun agentDialog(sessionId: Long? = null, locations: List? = null): AgentDialogResponse + + /** + * Sends the customer's [message] to the search agent and returns its answer + * (`POST /api/v3/storefront/search/agent`), in the session [sessionId] or a new one without it; + * [locations] as in [agentDialog]. The agent may take up to 40 seconds and two more attempts, so the + * answer is read for up to 60 seconds. An empty [message], or one longer than 500 characters, is + * `invalidArgument`. Besides the errors of every method: `http(400)` before the device has its `did`, + * `http(404)`, `http(429)` over the limit (10 messages a minute from a device), `http(503)` when the + * agent did not answer or the customer is in the control group of search — show [blank] instead; + * `http(402)`; `http(403)`. + */ + suspend fun agent(message: String, sessionId: Long? = null, locations: List? = null): AgentResponse + + /** [blank] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun blank(listener: CompletionListener) + + /** [instant] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun instant( + query: String, + locations: List?, + excludedMerchants: List?, + excludedBrands: List?, + listener: CompletionListener, + ) + + /** [full] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun full(query: String, request: SearchFullRequest, listener: CompletionListener) + + /** [agentDialog] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun agentDialog(sessionId: Long?, locations: List?, listener: CompletionListener) + + /** [agent] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun agent(message: String, sessionId: Long?, locations: List?, listener: CompletionListener) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SegmentsApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SegmentsApi.kt new file mode 100644 index 00000000..4c9aae26 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SegmentsApi.kt @@ -0,0 +1,58 @@ +package com.personalization.api.managers + +import com.personalization.api.models.segments.Segment +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * The customer's segments and the device's A/B group — the `segments` namespace. The shop sets up static + * segments in its account, and the SDK adds the customer to them or takes them out; the server works out + * dynamic ones itself. The API finds the customer by the device's `did`, which the SDK adds with the other + * common fields itself. With `email` or `phone` the server applies the call to the contact's owner, without + * moving the device to it. + * + * For the Flutter and React Native bridges: [add], [remove] and [get] run on the new core only + * (`Rees46.initializeBridge`); on an instance of the legacy core they fail with [SdkError.NotInitialized] + * without a request. [getAbGroup] asks nothing of the server. + * + * [add], [remove] and [get] throw [SdkException] with [SdkError.NotInitialized] (the legacy core, an + * instance not initialized or released), [SdkError.ShopBlocked], [SdkError.InvalidArgument] (before any + * request), [SdkError.Network], [SdkError.Timeout], [SdkError.Http], [SdkError.Decoding] or + * [SdkError.Cancelled] (`release()`). Nothing repeats a request. + */ +@BridgeApi +interface SegmentsApi { + + /** + * Adds the customer to the static segment [segmentId] (`POST /segments/add`); nothing changes for a + * customer already in it. A [segmentId] not above 0, or an empty contact, is `invalidArgument`. + */ + suspend fun add(segmentId: Int, email: String? = null, phone: String? = null) + + /** Takes the customer out of the static segment [segmentId] (`POST /segments/remove`); as [add]. */ + suspend fun remove(segmentId: Int, email: String? = null, phone: String? = null) + + /** + * The segments the customer is in now, static and dynamic (`GET /segments/get`); an empty list without + * any, `http(404)` for a `did` the server does not know. + */ + suspend fun get(): List + + /** + * The device's A/B group, `"A"` or `"B"`, at once and without errors: the SDK picks it at random once + * and sends it with every request (`segment`), and the server splits A/B tests by it. Empty for an + * instance never initialized. + */ + fun getAbGroup(): String + + /** [add] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun add(segmentId: Int, email: String?, phone: String?, listener: CompletionListener) + + /** [remove] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun remove(segmentId: Int, email: String?, phone: String?, listener: CompletionListener) + + /** [get] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun get(listener: CompletionListener>) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SlidersApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SlidersApi.kt new file mode 100644 index 00000000..60cf571f --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SlidersApi.kt @@ -0,0 +1,34 @@ +package com.personalization.api.managers + +import com.personalization.api.models.sliders.Slider +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * Banner sliders — the `sliders` namespace: `sdk.sliders.get(code)`. The app draws the carousel and + * reports a banner shown and tapped with [TrackingApi.bannerView] and [TrackingApi.bannerClick]. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + */ +@BridgeApi +interface SlidersApi { + + /** + * The slider [code] with its banners for the customer of this device (`GET /slider`). [tags] keeps the + * banners with those tags of the dashboard; [locationId] is the customer's location (its `external_id`), + * without which a banner limited to locations is not shown. A slider without banners is an empty list. + * + * @throws SdkException with [SdkError.InvalidArgument] for an empty [code], or an empty tag or one with + * a comma (tags go joined by commas), [SdkError.NotInitialized] (the legacy core, an instance not + * initialized or released), [SdkError.ShopBlocked], [SdkError.Network], [SdkError.Timeout], + * [SdkError.Http] (`404` for an unknown or inactive slider, `402` when the shop does not pay for + * sliders), [SdkError.Decoding] or [SdkError.Cancelled] (`release()`). + */ + suspend fun get(code: String, tags: List? = null, locationId: String? = null): Slider + + /** [get] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun get(code: String, tags: List?, locationId: String?, listener: CompletionListener) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/StoriesApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/StoriesApi.kt new file mode 100644 index 00000000..905c0b97 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/StoriesApi.kt @@ -0,0 +1,33 @@ +package com.personalization.api.managers + +import com.personalization.api.models.stories.StoriesBlock +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * The stories blocks — the `stories` namespace: `sdk.stories.get(code)`. The events of a story are + * [TrackingApi.storyView] and [TrackingApi.storyClick]. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + */ +@BridgeApi +interface StoriesApi { + + /** + * The stories block [code] (`GET /stories/{code}`) for this device: its stories, their slides and the + * slides' elements. A block without stories, a paused one among them, is a block with an empty list. + * + * @throws SdkException with [SdkError.InvalidArgument] for an empty [code], [SdkError.NotInitialized] + * (the legacy core, an instance not initialized or released), [SdkError.ShopBlocked], + * [SdkError.Network], [SdkError.Timeout], [SdkError.Http] (`404` for an unknown block, `402` when the + * shop does not pay for stories, `400` for a device the server does not know), [SdkError.Decoding] or + * [SdkError.Cancelled] (`release()`). + */ + suspend fun get(code: String): StoriesBlock + + /** [get] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun get(code: String, listener: CompletionListener) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SubscriptionsApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SubscriptionsApi.kt new file mode 100644 index 00000000..b8aee5c7 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/SubscriptionsApi.kt @@ -0,0 +1,93 @@ +package com.personalization.api.managers + +import com.personalization.api.models.subscriptions.BackInStockProperties +import com.personalization.api.models.subscriptions.SubscriptionStatus +import com.personalization.api.models.subscriptions.SubscriptionsUpdateRequest +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException + +/** + * The customer's subscriptions — the `subscriptions` namespace: to channels and kinds of mailings, and to a + * product's price drop or its return to stock. The API finds the customer by the device's `did`, which the + * SDK adds with the other common fields itself. A contact (`email`, `phone`) tells which address or number + * a subscription is for, and the server applies the call to the contact's owner: pass one only when it is + * the customer's own. The SDK leaves checking a contact's format to the server; an empty one is + * `invalidArgument`. + * + * For the Flutter and React Native bridges: it runs on the new core only (`Rees46.initializeBridge`). On + * an instance of the legacy core every call fails with [SdkError.NotInitialized] without a request. + * + * Every method throws [SdkException] with [SdkError.NotInitialized] (the legacy core, an instance not + * initialized or released), [SdkError.ShopBlocked], [SdkError.InvalidArgument] (before any request), + * [SdkError.Network], [SdkError.Timeout], [SdkError.Http], [SdkError.Decoding] or [SdkError.Cancelled] + * (`release()`). Nothing repeats a request: whether to ask again is the app's choice. + */ +@BridgeApi +interface SubscriptionsApi { + + /** Subscribes the customer to channels and kinds of mailings, or unsubscribes (`POST /subscriptions/manage`). */ + suspend fun manage(request: SubscriptionsUpdateRequest) + + /** + * The customer's subscriptions on every channel (`GET /subscriptions/check`); `http(400)` for a `did` + * the server does not know. + */ + suspend fun check(): SubscriptionStatus + + /** + * Subscribes the customer to a drop of [itemId]'s price (`POST /subscriptions/subscribe_for_product_price`). + * [currentPrice] must be above 0; the server takes the price from the catalog. The server ends the + * subscription once it told the customer. + */ + suspend fun subscribeForPriceDrop(itemId: String, currentPrice: Double, email: String? = null, phone: String? = null) + + /** + * Unsubscribes the customer from price drops of [itemIds] (`POST /subscriptions/unsubscribe_from_product_price`); + * an empty list unsubscribes from every product. An empty id in the list is `invalidArgument`. + */ + suspend fun unsubscribeFromPriceDrop(itemIds: List, email: String? = null, phone: String? = null) + + /** + * Subscribes the customer to [itemId]'s return to stock, in the variant of [properties] + * (`POST /subscriptions/subscribe_for_product_available`). The server ends the subscription once it + * told the customer. + */ + suspend fun subscribeForBackInStock( + itemId: String, + properties: BackInStockProperties? = null, + email: String? = null, + phone: String? = null, + ) + + /** + * Unsubscribes the customer from [itemIds]' return to stock (`POST /subscriptions/unsubscribe_from_product_available`); + * an empty list unsubscribes from every product. An empty id in the list is `invalidArgument`. + */ + suspend fun unsubscribeFromBackInStock(itemIds: List, email: String? = null, phone: String? = null) + + /** [manage] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun manage(request: SubscriptionsUpdateRequest, listener: CompletionListener) + + /** [check] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun check(listener: CompletionListener) + + /** [subscribeForPriceDrop] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun subscribeForPriceDrop(itemId: String, currentPrice: Double, email: String?, phone: String?, listener: CompletionListener) + + /** [unsubscribeFromPriceDrop] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun unsubscribeFromPriceDrop(itemIds: List, email: String?, phone: String?, listener: CompletionListener) + + /** [subscribeForBackInStock] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun subscribeForBackInStock( + itemId: String, + properties: BackInStockProperties?, + email: String?, + phone: String?, + listener: CompletionListener, + ) + + /** [unsubscribeFromBackInStock] for Java and for code outside coroutines: [listener] gets its result once, on the main thread. */ + fun unsubscribeFromBackInStock(itemIds: List, email: String?, phone: String?, listener: CompletionListener) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackingApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackingApi.kt index 21dfc7e8..7bb86838 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackingApi.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackingApi.kt @@ -4,6 +4,10 @@ import com.personalization.api.OnApiCallbackListener import com.personalization.api.models.purchase.PurchaseTrackingRequest import com.personalization.api.models.tracking.TrackingItem import com.personalization.api.models.tracking.TrackingSource +import com.personalization.api.models.sliders.SliderBanner +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError /** * Standard tracking events — the `tracking` namespace of the SDK. @@ -154,4 +158,24 @@ interface TrackingApi { * Same behaviour and same wire shape as iOS. */ fun setSource(source: TrackingSource) + + /** + * A banner of a slider was shown (`track/slider`, `view`): once, when it first became visible in this + * showing of the slider. [bannerId] and [code] are the banner's [SliderBanner.id] and [SliderBanner.code] + * from [SlidersApi.get]. + * + * For the Flutter and React Native bridges, on the new core only: the event goes through the queue, and + * [listener] hears once, on the main thread, that the queue accepted it, or why not — + * [SdkError.InvalidArgument] for a [bannerId] that is not a positive whole number or an empty [code], + * [SdkError.ShopBlocked], or [SdkError.NotInitialized] after `release()` and on the legacy core, where + * nothing is sent. Hidden from Java. + */ + @BridgeApi + @JvmSynthetic + fun bannerView(bannerId: String, code: String, listener: CompletionListener? = null) + + /** A banner of a slider was tapped (`track/slider`, `click`); otherwise as [bannerView]. Hidden from Java. */ + @BridgeApi + @JvmSynthetic + fun bannerClick(bannerId: String, code: String, listener: CompletionListener? = null) } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/collections/CollectionResponse.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/collections/CollectionResponse.kt new file mode 100644 index 00000000..14057d7c --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/collections/CollectionResponse.kt @@ -0,0 +1,8 @@ +package com.personalization.api.models.collections + +import com.personalization.api.models.products.Product + +/** The products of a collection the shop set up in its account (`sdk.collections.get`). */ +data class CollectionResponse( + val products: List, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/loyalty/LoyaltyModels.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/loyalty/LoyaltyModels.kt new file mode 100644 index 00000000..46c68303 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/loyalty/LoyaltyModels.kt @@ -0,0 +1,54 @@ +package com.personalization.api.models.loyalty + +/* + * The loyalty program's models of `sdk.loyalty`, flat: the answers' `{status, payload}` envelope is gone. + * Their own package: `LoyaltyLevel` of `com.personalization.api.responses.loyalty` is the old answer's. + */ + +/** A member of the loyalty program (`loyalty.join`). */ +data class LoyaltyMember( + /** The member's id: the phone, digits only (`7XXXXXXXXXX`). [com.personalization.api.managers.LoyaltyApi.getStatus] takes it. */ + val identifier: String, +) + +/** Whether the customer is a member, and on which level (`loyalty.getStatus`). */ +data class LoyaltyStatus( + val isMember: Boolean, + /** Null on the base level, and for someone who is not a member. */ + val level: LoyaltyLevel?, +) + +/** A level of the loyalty program above the base one. */ +data class LoyaltyLevel( + val code: String, + val name: String?, + /** `YYYY-MM-DD`: the level is counted anew after it. */ + val expirationDate: String?, +) + +/** An active promotion that suits the customer and their cart (`loyalty.getPromotions`). */ +data class LoyaltyPromotion( + /** A 64-bit id: the server's ids of promotions are `bigint`. */ + val id: Long, + val name: String, + val description: String?, + /** `YYYY-MM-DD`. */ + val startDate: String?, + /** `YYYY-MM-DD`. */ + val finishDate: String?, + /** Where the promotion works; null — everywhere. */ + val stream: String?, + /** The badge's text. */ + val badgeLabel: String?, + /** The badge's colour, `#RRGGBB`. */ + val badgeColor: String?, + /** Null for a reward the SDK does not know yet. */ + val rewardType: LoyaltyRewardType?, +) + +/** What a promotion gives. */ +enum class LoyaltyRewardType(val value: String) { + DISCOUNT("discount"), + BONUSES_EARN("bonuses_earn"), + BONUSES_USAGE("bonuses_usage"), +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/predict/PurchaseProbability.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/predict/PurchaseProbability.kt new file mode 100644 index 00000000..c162a428 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/predict/PurchaseProbability.kt @@ -0,0 +1,14 @@ +package com.personalization.api.models.predict + +/** + * How likely the customer of this device is to buy (`sdk.predict.getProbabilityToPurchase()`). + * + * A customer the server does not know has [probability] 0 and no [clientId]; one it knows without the + * events the forecast reads has [probability] 0 and its [clientId]. + */ +data class PurchaseProbability( + /** From 0 to 1, to hundredths. */ + val probability: Double, + /** The id of the customer the server found (`client_id`, a number in the answer); null when none. */ + val clientId: String?, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/Product.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/Product.kt new file mode 100644 index 00000000..0b70c2e3 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/Product.kt @@ -0,0 +1,79 @@ +package com.personalization.api.models.products + +import com.personalization.api.responses.products.product.ProductParam + +/** + * A product in every answer of the catalog's namespaces: the product card (`sdk.products.getInfo`), a + * listing, a category, a collection, recommendations and search. [id], [name], [url], [price] and + * [currency] are always there; any other field the answer leaves out, or sends as an empty string, is null, + * never an empty string or 0. + * + * @property id the shop's own product id (`uniqid` in the product card, `id` elsewhere). + * @property groupId the group of the product's variants (`group_id`); for a product without a group the + * server sends a value of its own, such as `_37_`. + * @property imageUrl the original picture (`image_url`). + * @property picture the picture in the size the answer was asked for (`picture`). + * @property resizedImages the picture in each size the server keeps (`image_url_resized`): `"120"` … + * `"520"` and `"original"` → its link. + * @property priceFull the price with its fraction (`price_full`). + * @property oldPrice the price before the discount (`oldprice`); null, not 0, without one. + * @property oldPriceFull [oldPrice] with its fraction (`oldprice_full`); null, not 0, without one. + * @property discountPercent the discount in percent (`discount_percent`, or `discount` when that is a number). + * @property rating the product's rating; the server sends it only when it is not 0. + * @property isNew whether the shop marks the product as new; the server sends it only when it is. + * @property locationIds where the product is in stock (`location_ids`), or `["global"]`; only when the + * request asked for it (`withLocations` of `sdk.recommendations.get`). + */ +data class Product( + val id: String, + val groupId: String? = null, + val name: String, + val brand: String? = null, + val model: String? = null, + val description: String? = null, + val barcode: String? = null, + val url: String, + val deeplinkAndroid: String? = null, + val deeplinkIos: String? = null, + val imageUrl: String? = null, + val picture: String? = null, + val resizedImages: Map? = null, + val price: Double, + val priceFormatted: String? = null, + val priceFull: Double? = null, + val priceFullFormatted: String? = null, + val oldPrice: Double? = null, + val oldPriceFormatted: String? = null, + val oldPriceFull: Double? = null, + val oldPriceFullFormatted: String? = null, + val currency: String, + val discountPercent: Int? = null, + val discountFormatted: String? = null, + val salesRate: Int? = null, + val relativeSalesRate: Double? = null, + val rating: Int? = null, + val isNew: Boolean = false, + val stockQuantity: Int? = null, + val categoryIds: List? = null, + val categories: List? = null, + val params: List? = null, + val locationIds: List? = null, +) + +/** + * A product's category, and a category among the facets of a listing or a search. + * + * @property parentId the parent category (`parent_id`; `parent` among the facets). + * @property level how deep the category is in the tree; only in a product's categories. + * @property count how many products the listing or the search found in the category; only among the facets. + * @property alias only among the facets. + */ +data class ProductCategory( + val id: String, + val name: String? = null, + val url: String? = null, + val parentId: String? = null, + val level: Int? = null, + val count: Int? = null, + val alias: String? = null, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/ProductsRequests.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/ProductsRequests.kt new file mode 100644 index 00000000..24ebaf40 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/ProductsRequests.kt @@ -0,0 +1,73 @@ +package com.personalization.api.models.products + +/* + * What `sdk.products.getList` and `getCategory` ask for. A field left null is not sent. A list goes as one + * string joined with commas, and an empty list is not sent. A wrong value fails the call with + * `invalidArgument` before any request: [ProductsListRequest.limit] or [ProductsListRequest.page] below 1, + * a negative price, `priceMin` above `priceMax`, or [SortBy.RELEVANCE], which only a search sorts by. + */ + +/** + * The filters, the order and the page of the catalog's listing. + * + * @property merchants for marketplaces; with [locations], the merchants are looked for in those locations. + * @property locations products in stock in these locations. + * @property priceMin not below 0; the server drops the fraction. + * @property priceMax not below [priceMin]; the server drops the fraction. + * @property filters a product's parameter → the values to keep; sent as a JSON string. + * @property limit products on a page, from 1. + * @property page the page, from 1. + */ +data class ProductsListRequest( + val categoryIds: List? = null, + val brands: List? = null, + val merchants: List? = null, + val locations: List? = null, + val priceMin: Double? = null, + val priceMax: Double? = null, + val filters: Map>? = null, + val sortBy: SortBy? = null, + val sortDir: SortDirection? = null, + val limit: Int? = null, + val page: Int? = null, +) + +/** The filters, the order and the page of a category's screen; the fields as in [ProductsListRequest]. */ +data class CategoryRequest( + val brands: List? = null, + val locations: List? = null, + val filters: Map>? = null, + val priceMin: Double? = null, + val priceMax: Double? = null, + val sortBy: SortBy? = null, + val sortDir: SortDirection? = null, + val limit: Int? = null, + val page: Int? = null, +) + +/** + * What a listing or a search sorts by (`sort_by`). An open set: the server may add a key, and an app passes + * it as `SortBy("key")` without a new release of the SDK. + */ +@JvmInline +value class SortBy(val value: String) { + companion object { + val PRICE = SortBy("price") + val DISCOUNT = SortBy("discount") + val SALES_RATE = SortBy("sales_rate") + val DATE = SortBy("date") + val PRICE_MARGIN = SortBy("price_margin") + + /** The server applies it only together with another key, which the SDK cannot send yet. */ + val RATING = SortBy("rating") + + /** Only for `sdk.search.full`; a listing or a category fails with `invalidArgument`. */ + val RELEVANCE = SortBy("relevance") + } +} + +/** The direction of a sort; the server sorts in [DESC] order when the request names none. */ +enum class SortDirection(val value: String) { + ASC("asc"), + DESC("desc"), +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/ProductsResponses.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/ProductsResponses.kt new file mode 100644 index 00000000..b551a92f --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/products/ProductsResponses.kt @@ -0,0 +1,75 @@ +package com.personalization.api.models.products + +import com.personalization.api.responses.search.Brand +import com.personalization.api.responses.search.IndustrialFilters +import com.personalization.api.responses.search.Location +import com.personalization.api.responses.search.PriceRange + +/* + * The answers of `sdk.products` and the facets they share with `sdk.search`. In each, the list the answer + * is about ([ProductsListResponse.products]) is never null; any other field the answer leaves out is null. + */ + +/** + * A page of the catalog's listing (`sdk.products.getList`): the products, and the facets of everything the + * filters found. + * + * @property productsTotal how many products the filters found, on every page. + * @property filters the facets of the products' parameters: a parameter's name → its facet. + * @property industrialFilters colours and sizes; only a search sends them. + * @property priceRange the lowest and the highest price found. + * @property priceRanges how many products fall into each price interval. + */ +data class ProductsListResponse( + val productsTotal: Int? = null, + val products: List, + val categories: List? = null, + val brands: List? = null, + val locations: List? = null, + val filters: Map? = null, + val industrialFilters: IndustrialFilters? = null, + val priceRange: PriceRange? = null, + val priceRanges: List? = null, + val priceMedian: Double? = null, +) + +/** A category's screen (`sdk.products.getCategory`): its products and its facets; fields as in [ProductsListResponse]. */ +data class CategoryResponse( + val productsTotal: Int? = null, + val products: List, + val categories: List? = null, + val brands: List? = null, + val filters: Map? = null, + val priceRange: PriceRange? = null, + val priceRanges: List? = null, + val priceMedian: Double? = null, +) + +/** + * A facet: one parameter of the products in a filter's sidebar. + * + * @property count how many products carry the parameter. + * @property priority where the facet goes among the others. + * @property values a facet of values: a value → how many products carry it. + * @property min the lowest value of a numeric facet (`ranges.min`). + * @property max the highest value of a numeric facet (`ranges.max`). + */ +data class SearchFilter( + val count: Int? = null, + val priority: Int? = null, + val values: Map? = null, + val min: Double? = null, + val max: Double? = null, +) + +/** + * A price interval of the facets and how many products fall into it. + * + * @property from the interval's lower bound; 0 when the answer has none. + * @property to the interval's upper bound; null for an interval without one. + */ +data class PriceInterval( + val from: Double = 0.0, + val to: Double? = null, + val count: Int? = null, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/profile/Gender.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/profile/Gender.kt new file mode 100644 index 00000000..4cf35cc8 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/profile/Gender.kt @@ -0,0 +1,7 @@ +package com.personalization.api.models.profile + +/** The customer's gender, as the API writes it: `m` or `f`. The profile and the loyalty program share it. */ +enum class Gender(val value: String) { + MALE("m"), + FEMALE("f"), +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/profile/Profile.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/profile/Profile.kt new file mode 100644 index 00000000..d2edd143 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/profile/Profile.kt @@ -0,0 +1,81 @@ +package com.personalization.api.models.profile + +/** + * The customer's profile as the API gives it to the device (`sdk.profile.get`): without the shop's secret + * key it has no name, email or phone. Which fields come depends on the shop's settings; a field the answer + * leaves out is null. + * + * @property id the customer's id on the server, not the shop's own id ([ProfileUpdateRequest.externalId]). + * @property hasEmail whether the customer has an email. + * @property emailRegisteredAt when the shop first got the customer's email: `YYYY-MM-DD HH:MM:SS`, without + * a time zone. + * @property computedGender the gender the server worked out. + * @property boughtSomething whether the customer has bought anything. + * @property customProperties the profile's own properties the shop set up: a property's name → its value (a + * string, a number, a boolean, null, a list or a map of these). + */ +data class Profile( + val id: String? = null, + val hasEmail: Boolean? = null, + val emailRegisteredAt: String? = null, + val gender: Gender? = null, + val computedGender: Gender? = null, + val boughtSomething: Boolean? = null, + val customProperties: Map? = null, +) + +/** + * The properties `sdk.profile.set` writes: only the fields given change, and a null field is not sent, so + * its value on the server stays. An empty string erases [externalId], [telegramId], [birthday], [fbId] and + * [vkId], and leaves [location], [firstName] and [lastName] empty; [age] 0 erases the age. The server does + * not erase [email], [phone] or [loyaltyId] with an empty string, so an empty one is refused. [gender] has + * no empty value: `set` cannot erase it. A customer's id of another customer ([email], [phone], + * [externalId], [loyaltyId], [telegramId]) moves the device to that customer's profile: that is how a + * sign-in and a change of user on one device work. + * + * The call fails with `invalidArgument`, before any request, when nothing is given; when [email], [phone] + * or [loyaltyId] is empty; when [birthday] (a kid's too) is not an existing day `YYYY-MM-DD` of the years + * 1000 to 2999 — the server would ignore it in silence —, the empty [birthday] that erases it aside (a + * kid's may not be empty); when [age] is negative; when a key of [customProperties] is not of `a-z`, `0-9` + * and `_`, or is a field of this request or of the SDK (`email`, `first_name`, `auto`, `did`, …); or when + * one of its values is not a string, a number, a boolean, null, or a list or a map of these. + * + * @property externalId the customer's id in the shop's own system; sent as both `id` and `external_id`. + * @property loyaltyId the customer's id in an outside loyalty program. + * @property birthday `YYYY-MM-DD`: a date, not a moment, so it does not move between time zones. + * @property location the customer's city: a location's id from the product feed. + * @property cars sent as `auto`. + * @property customProperties the profile's own properties the shop set up in its account; each goes as a + * field of its own. A date goes as a string `YYYY-MM-DD`. + */ +data class ProfileUpdateRequest( + val email: String? = null, + val phone: String? = null, + val externalId: String? = null, + val loyaltyId: String? = null, + val telegramId: String? = null, + val fbId: String? = null, + val vkId: String? = null, + val firstName: String? = null, + val lastName: String? = null, + val gender: Gender? = null, + val birthday: String? = null, + val age: Int? = null, + val location: String? = null, + val kids: List? = null, + val cars: List? = null, + val customProperties: Map? = null, +) + +/** A customer's kid; [birthday] is `YYYY-MM-DD`. */ +data class ProfileKid( + val gender: Gender? = null, + val birthday: String? = null, +) + +/** A customer's car; [vds], as the API's documentation says, is the VIN. */ +data class ProfileCar( + val brand: String? = null, + val model: String? = null, + val vds: String? = null, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/recommendations/Recommendations.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/recommendations/Recommendations.kt new file mode 100644 index 00000000..a3f91de6 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/recommendations/Recommendations.kt @@ -0,0 +1,49 @@ +package com.personalization.api.models.recommendations + +import com.personalization.api.models.products.Product + +/** + * Where the customer is when a recommendation block shows: the block's rules pick its products with it. + * A field left null is not sent; a list goes as one string joined with commas, and an empty list is not + * sent. + * + * @property itemId the product on the screen: a product card, a cart line (`item_id`). + * @property categoryId the category on the screen (`category`). + * @property searchQuery the query on a search screen (`search_query`). + * @property excludedItemIds products the block must not show (`exclude`). + * @property limit how many products, from 1. + * @property extended true for whole products in [RecommendationResponse.products]; false for their ids + * only, in [RecommendationResponse.itemIds]. + * @property withLocations [Product.locationIds] for every product; only with [extended], otherwise the call + * fails with `invalidArgument`. + */ +data class RecommendationRequest( + val itemId: String? = null, + val categoryId: String? = null, + val searchQuery: String? = null, + val excludedItemIds: List? = null, + val brands: List? = null, + val locations: List? = null, + val limit: Int? = null, + val extended: Boolean = true, + val withLocations: Boolean = false, +) + +/** + * The products of a recommendation block (`sdk.recommendations.get`). A block on pause answers with no + * products: both lists are empty. + * + * @property id the block's id. + * @property title the block's title. + * @property link the link of the title, when the block has one. + * @property products the products, with [RecommendationRequest.extended]; empty without it. + * @property itemIds the products' ids, always: those of [products], or the ids alone without + * [RecommendationRequest.extended]. + */ +data class RecommendationResponse( + val id: Int? = null, + val title: String? = null, + val link: String? = null, + val products: List, + val itemIds: List, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/search/Agent.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/search/Agent.kt new file mode 100644 index 00000000..e5c2cd71 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/search/Agent.kt @@ -0,0 +1,87 @@ +package com.personalization.api.models.search + +/** + * The customer's dialog with the search agent (`sdk.search.agentDialog`). + * + * @property sessions the customer's last 20 sessions, the latest first, without their messages. + * @property session the chosen session with its messages; null while the customer has none. + */ +data class AgentDialogResponse( + val sessions: List = emptyList(), + val session: AgentSession? = null, +) + +/** + * The agent's answer to the customer's message (`sdk.search.agent`). + * + * @property session the session the message went to (a new one without a session id), without its messages. + * @property message the agent's answer. + */ +data class AgentResponse( + val session: AgentSession, + val message: AgentMessage, +) + +/** + * A session of the dialog; [id] is 64-bit, as the server's ids of sessions, and is what `agentDialog` and + * `agent` take as `sessionId`. + * + * @property title the start of the customer's first message. + * @property updatedAt when the last message came, ISO 8601. + * @property messages empty in the list of sessions and in [AgentResponse]. + */ +data class AgentSession( + val id: Long, + val title: String? = null, + val updatedAt: String? = null, + val messages: List = emptyList(), +) + +/** + * A message of the dialog; [id] is 64-bit, as the server's ids of messages. + * + * @property createdAt ISO 8601. + * @property products the products the agent offered; empty in the customer's messages. + */ +data class AgentMessage( + val id: Long, + val role: AgentMessageRole? = null, + val content: String? = null, + val createdAt: String? = null, + val products: List = emptyList(), +) + +/** + * Who wrote a message. An open set: a role the server adds later reads as it is, `AgentMessageRole("…")`. + */ +@JvmInline +value class AgentMessageRole(val value: String) { + companion object { + /** The customer. */ + val USER = AgentMessageRole("user") + + /** The agent. */ + val ASSISTANT = AgentMessageRole("assistant") + } +} + +/** + * A product the agent offered: not a `Product`, a short set of fields and why it fits. + * + * @property price in the customer's location, when the server knows it. + * @property oldPrice null, not 0, without an old price. + * @property url the product's link with the agent's attribution (`recommended_by=agent_search`); null for a + * product without an absolute http(s) link. + * @property reason why the product fits the request; empty without an explanation. + */ +data class AgentProduct( + val id: String, + val name: String? = null, + val price: Double? = null, + val oldPrice: Double? = null, + val priceFormatted: String? = null, + val oldPriceFormatted: String? = null, + val picture: String? = null, + val url: String? = null, + val reason: String? = null, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/search/Search.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/search/Search.kt new file mode 100644 index 00000000..1fe5a11d --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/search/Search.kt @@ -0,0 +1,136 @@ +package com.personalization.api.models.search + +import com.personalization.api.models.products.PriceInterval +import com.personalization.api.models.products.Product +import com.personalization.api.models.products.ProductCategory +import com.personalization.api.models.products.SearchFilter +import com.personalization.api.models.products.SortBy +import com.personalization.api.models.products.SortDirection +import com.personalization.api.responses.search.Brand +import com.personalization.api.responses.search.IndustrialFilters +import com.personalization.api.responses.search.Location +import com.personalization.api.responses.search.PopularItem +import com.personalization.api.responses.search.PriceRange + +/* + * What `sdk.search` asks for and answers with. In each answer the products are never null (empty when the + * search found none; an instant or a full search's answer without them is `decoding`); any other field the + * answer leaves out is null. + */ + +/** + * The filters, the order and the page of a full search. A field left null is not sent; a list goes as one + * string joined with commas, and an empty list is not sent. The checks are those of + * `ProductsListRequest`: [limit], [page], [categoryLimit] and [brandLimit] from 1, a price not below 0, + * [priceMin] not above [priceMax]; a wrong value fails the call with `invalidArgument` before any request. + * + * @property excludedMerchants for marketplaces; sent only with [locations], because the server looks for + * merchants in those locations and finds no product without them. + * @property excludedItemIds products to leave out, such as those in the cart (`exclude`). + * @property filters a product's parameter → the values to keep; sent as a JSON string. + * @property sortDir sent as `order`. + * @property disableClarification true turns the search's clarification off (`no_clarification`). + * @property categoryLimit how many categories the facets list. + * @property brandLimit how many brands the facets list; the server lists 1000 without it. + */ +data class SearchFullRequest( + val categoryIds: List? = null, + val brands: List? = null, + val excludedBrands: List? = null, + val merchants: List? = null, + val excludedMerchants: List? = null, + val locations: List? = null, + val priceMin: Double? = null, + val priceMax: Double? = null, + val colors: List? = null, + val fashionSizes: List? = null, + val excludedItemIds: List? = null, + val filters: Map>? = null, + val sortBy: SortBy? = null, + val sortDir: SortDirection? = null, + val disableClarification: Boolean = false, + val categoryLimit: Int? = null, + val brandLimit: Int? = null, + val limit: Int? = null, + val page: Int? = null, +) + +/** + * What to show in an empty search field (`sdk.search.blank`). + * + * @property products the products the customer viewed lately ([lastProducts] true), or popular ones. + * @property lastProducts true when [products] are the customer's own recent views; false without the field. + * @property lastQueries the customer's recent queries. + * @property suggests suggested queries. + */ +data class SearchBlankResponse( + val products: List = emptyList(), + val lastProducts: Boolean = false, + val lastQueries: List? = null, + val suggests: List? = null, + val popularCategories: List? = null, + val popularBrands: List? = null, + val popularLinks: List? = null, +) + +/** + * The results of a search as the customer types (`sdk.search.instant`). + * + * @property searchQuery the query after the server fixed its keyboard layout and typos. + * @property searchQueryOriginal the query as it came. + * @property clarification whether the search's clarification worked. + * @property queries suggested queries. + * @property redirect the page the shop sends this query to instead of the results. + */ +data class SearchInstantResponse( + val searchQuery: String? = null, + val searchQueryOriginal: String? = null, + val clarification: Boolean? = null, + val productsTotal: Int? = null, + val products: List = emptyList(), + val categories: List? = null, + val queries: List? = null, + val locations: List? = null, + val redirect: SearchRedirect? = null, +) + +/** The screen of a search's results (`sdk.search.full`); the facets as in `ProductsListResponse`. */ +data class SearchFullResponse( + val searchQuery: String? = null, + val searchQueryOriginal: String? = null, + val clarification: Boolean? = null, + val productsTotal: Int? = null, + val products: List = emptyList(), + val categories: List? = null, + val brands: List? = null, + val locations: List? = null, + val filters: Map? = null, + val industrialFilters: IndustrialFilters? = null, + val priceRange: PriceRange? = null, + val priceRanges: List? = null, + val priceMedian: Double? = null, +) + +/** + * A suggested or a recent query. + * + * @property url the link of a full search by it. + * @property score only among the suggestions of an instant search. + */ +data class Query( + val name: String, + val url: String? = null, + val score: Double? = null, +) + +/** + * A query the shop sends to a page instead of the results. + * + * @property url the page (`redirect_link`). + * @property deeplink the page in the app (`deep_link`), when the shop set one. + */ +data class SearchRedirect( + val query: String? = null, + val url: String? = null, + val deeplink: String? = null, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/segments/Segment.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/segments/Segment.kt new file mode 100644 index 00000000..70a3aa46 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/segments/Segment.kt @@ -0,0 +1,12 @@ +package com.personalization.api.models.segments + +/** + * A segment the customer is in (`sdk.segments.get`). + * + * @property type `dynamic`, `static`, `less_often`, `rfm`, `rfm3` or `unknown`; a string, not an enum, so a + * kind of segment the server adds later reads as it is. + */ +data class Segment( + val id: Int, + val type: String? = null, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/sliders/Slider.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/sliders/Slider.kt new file mode 100644 index 00000000..bb170418 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/sliders/Slider.kt @@ -0,0 +1,31 @@ +package com.personalization.api.models.sliders + +/** A banner slider by its code (`sdk.sliders.get(code)`): the app draws the carousel. */ +data class Slider( + /** The slider's code (`payload.properties.code`). */ + val code: String, + /** The block's width, px; 0 when the answer has none. */ + val width: Int, + /** The block's height, px; 0 when the answer has none. */ + val height: Int, + /** The banners for the customer of this device, already chosen by period, segments and location (`payload.slides`). */ + val banners: List, +) + +/** + * One banner of a slider. [id] and [code] are what [com.personalization.api.managers.TrackingApi.bannerView] + * and `bannerClick` take. + */ +data class SliderBanner( + /** The banner's id for its events (`banner_id`, a number in the answer). */ + val id: String, + /** The slider's code, the same on every banner of it (`recommended_code`). */ + val code: String, + val imageUrl: String?, + /** The landing page. */ + val url: String?, + val deeplinkIos: String?, + val deeplinkAndroid: String?, + /** The banner's ready markup. */ + val html: String?, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/stories/StoriesBlock.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/stories/StoriesBlock.kt new file mode 100644 index 00000000..589fb96e --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/stories/StoriesBlock.kt @@ -0,0 +1,153 @@ +package com.personalization.api.models.stories + +/* + * The stories block of `sdk.stories.get(code)` — the contract's model, the one the Flutter SDK already + * reads. Its own package: `Story` and `Slide` of `com.personalization.stories.models` belong to the old + * stories viewer. A string field the answer leaves out is an empty string, as in Flutter; only the fields + * the contract marks as optional are null. + */ + +/** A stories block (`GET /stories/{code}`): its id on the server and its stories, in the order of the bar. */ +data class StoriesBlock( + val id: String, + val stories: List, +) + +/** One story: a cover in the bar and the slides the viewer plays. */ +data class Story( + val id: String, + val name: String, + /** The cover's image URL. */ + val avatar: String, + /** Seen on this device, as the server remembers it. */ + val viewed: Boolean = false, + /** Pinned by the shop to the start of the bar. */ + val pinned: Boolean = false, + /** The slide to start from: the first one not seen yet. */ + val startPosition: Int = 0, + val slides: List, +) + +/** What a slide shows behind its elements. */ +enum class StorySlideType { + /** `image`: [StorySlide.background] is a picture. */ + IMAGE, + + /** `video`: [StorySlide.background] is a video, [StorySlide.preview] its poster. */ + VIDEO, + + /** Any other type (`""` in the answer): a product slide, whose product is a [StoryProductElement]. */ + PRODUCT, +} + +/** One slide of a story. */ +data class StorySlide( + /** A number for a slide with media, a string like `39_0` for a product slide. */ + val id: String, + val type: StorySlideType, + /** The image or video URL; on a product slide, the one of the stories' settings. */ + val background: String, + /** `#RRGGBB` behind the background; empty when not set. */ + val backgroundColor: String, + /** A video's poster; empty when there is none. */ + val preview: String, + /** Seconds on screen: [DEFAULT_DURATION] when the answer has none, or 0. */ + val duration: Int, + val elements: List, +) { + companion object { + /** Seconds a slide stays when the answer does not say: the same on every platform. */ + const val DEFAULT_DURATION: Int = 10 + } +} + +/** + * An element of a slide, by the answer's `type`. Elements of other types, `header` and the polls (behind + * the API v3 gate) are left out. + */ +sealed interface StoryElement + +/** `button`: a call to action with a link. */ +data class StoryButtonElement( + val title: String, + val link: String, + val linkAndroid: String, + val linkIos: String, + /** The old viewer's colours; the UI kit draws its own button. */ + val background: String, + val color: String, + /** `text_bold`, or `bold`. */ + val textBold: Boolean, +) : StoryElement + +/** `product`: the product of a product slide; [item] is null when the answer has none. */ +data class StoryProductElement( + val title: String, + val item: StoryProduct?, +) : StoryElement + +/** `products`: the products of a slide behind a show / hide toggle. */ +data class StoryProductsElement( + /** The toggle's label while the products are hidden (`labels.show_carousel`). */ + val showLabel: String, + /** The toggle's label while they are shown (`labels.hide_carousel`). */ + val hideLabel: String, + val products: List, +) : StoryElement + +/** `text_block`: a text over a slide. */ +data class StoryTextBlockElement( + /** `text_input`. */ + val text: String, + /** [DEFAULT_FONT_SIZE] when not set. */ + val fontSize: Double, + /** `serif`, `sans-serif`, `monospace`, or empty. */ + val fontType: String, + /** `bold`, or `text_bold`. */ + val bold: Boolean, + val italic: Boolean, + /** `left`, `center`, `right`, or empty. */ + val textAlign: String, + /** `#RRGGBB`, or empty. */ + val textColor: String, + /** `#RRGGBB` behind the text (`text_background_color`), or empty. */ + val backgroundColor: String, + /** 0 to 1, from `"50%"`, `"50"` or `0.5`; 0 — no frame behind the text. */ + val backgroundOpacity: Double, + /** Line height as a multiple of the font size; 0 — the font's own. */ + val lineSpacing: Double, + /** The top of the block, in percent of the slide's height. */ + val yOffset: Double, + /** A code the block copies on a tap; null when it has none. */ + val promocode: String?, +) : StoryElement { + companion object { + const val DEFAULT_FONT_SIZE: Double = 14.0 + } +} + +/** A product of a stories block: what the UI kit shows and links to. */ +data class StoryProduct( + val id: String, + val name: String, + val brand: String, + /** The resized image: the one to show. */ + val picture: String, + /** The original image (`image_url`). */ + val imageUrl: String, + val price: Double, + val priceFormatted: String, + /** The price before the discount (`oldprice`); null when it is not above [price]. */ + val oldPrice: Double?, + val oldPriceFormatted: String, + /** `discount_percent`, 0 when the shop did not load it into its catalog. */ + val discountPercent: Double, + val promocode: String, + /** The price with [promocode] (`price_with_promocode`); 0 when not sent. */ + val priceWithPromocode: Double, + val priceWithPromocodeFormatted: String, + val currency: String, + val url: String, + val deeplinkAndroid: String, + val deeplinkIos: String, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/models/subscriptions/Subscriptions.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/models/subscriptions/Subscriptions.kt new file mode 100644 index 00000000..bd5af633 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/models/subscriptions/Subscriptions.kt @@ -0,0 +1,103 @@ +package com.personalization.api.models.subscriptions + +/** + * What `sdk.subscriptions.manage` changes: `true` subscribes, `false` unsubscribes, null leaves a flag as + * it is and is not sent. A request without a single flag fails with `invalidArgument`, as does a contact + * that is an empty string. The kinds of mailings: `bulk` — mass mailings, `chain` — triggered ones, + * `transactional` — service ones. + * + * A contact in the request applies the change to the contact's owner. Pass a contact only when it is the + * customer's own. + * + * @property externalId the customer's id in the shop's own system. + * @property loyaltyId the customer's id in an outside loyalty program. + */ +data class SubscriptionsUpdateRequest( + val email: String? = null, + val phone: String? = null, + val externalId: String? = null, + val loyaltyId: String? = null, + val telegramId: String? = null, + val emailBulk: Boolean? = null, + val emailChain: Boolean? = null, + val emailTransactional: Boolean? = null, + val smsBulk: Boolean? = null, + val smsChain: Boolean? = null, + val smsTransactional: Boolean? = null, + val webPushBulk: Boolean? = null, + val webPushChain: Boolean? = null, + val webPushTransactional: Boolean? = null, + val mobilePushBulk: Boolean? = null, + val mobilePushChain: Boolean? = null, + val mobilePushTransactional: Boolean? = null, + val telegramBulk: Boolean? = null, + val telegramChain: Boolean? = null, + val telegramTransactional: Boolean? = null, + val whatsappBulk: Boolean? = null, + val whatsappChain: Boolean? = null, + val whatsappTransactional: Boolean? = null, + val maxBulk: Boolean? = null, + val maxChain: Boolean? = null, + val maxTransactional: Boolean? = null, + val walletBulk: Boolean? = null, + val walletChain: Boolean? = null, + val walletTransactional: Boolean? = null, +) + +/** + * The customer's subscriptions on every channel (`sdk.subscriptions.check`). A flag the answer leaves out is + * false. + * + * @property exists whether the customer is in the shop's customer base. + * @property emailBulk and the other 23 flags: whether the customer has the channel's contact and is + * subscribed to the kind of mailings. + * @property hasWebPush whether the customer has a working web push token (`web_push`). + * @property hasMobilePush whether the customer has a working mobile push token (`mobile_push`). + * @property emailSuppressed the email is blocked: its subscriptions cannot change. + */ +data class SubscriptionStatus( + val exists: Boolean = false, + val emailBulk: Boolean = false, + val emailChain: Boolean = false, + val emailTransactional: Boolean = false, + val smsBulk: Boolean = false, + val smsChain: Boolean = false, + val smsTransactional: Boolean = false, + val webPushBulk: Boolean = false, + val webPushChain: Boolean = false, + val webPushTransactional: Boolean = false, + val mobilePushBulk: Boolean = false, + val mobilePushChain: Boolean = false, + val mobilePushTransactional: Boolean = false, + val telegramBulk: Boolean = false, + val telegramChain: Boolean = false, + val telegramTransactional: Boolean = false, + val whatsappBulk: Boolean = false, + val whatsappChain: Boolean = false, + val whatsappTransactional: Boolean = false, + val maxBulk: Boolean = false, + val maxChain: Boolean = false, + val maxTransactional: Boolean = false, + val walletBulk: Boolean = false, + val walletChain: Boolean = false, + val walletTransactional: Boolean = false, + val hasWebPush: Boolean = false, + val hasMobilePush: Boolean = false, + val emailInvalid: Boolean = false, + val emailBlacklisted: Boolean = false, + val emailBounced: Boolean = false, + val emailSuppressed: Boolean = false, + val emailConfirmed: Boolean = false, +) + +/** + * The variant of a product a back-in-stock subscription waits for. Properties with no field given are not + * sent. + * + * @property fashionSize the size; the server reads it in lower case. + */ +data class BackInStockProperties( + val fashionSize: String? = null, + val fashionColor: String? = null, + val barcode: String? = null, +) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/params/PurchasePredictParams.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/params/PurchasePredictParams.kt index 442abe17..ba98a567 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/api/params/PurchasePredictParams.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/params/PurchasePredictParams.kt @@ -8,8 +8,8 @@ private const val QUERY_TELEGRAM_ID = "telegram_id" private const val QUERY_LOYALTY_ID = "loyalty_id" /** - * Optional query parameters for [com.personalization.api.managers.PredictManager.getProbabilityToPurchase]. - * Device id and shop id are added by the SDK network layer. + * Contacts [com.personalization.api.managers.PredictManager.getProbabilityToPurchase] takes, and no longer + * sends: the server finds the customer by the device's `did`, which the SDK sends with every request. */ data class PurchasePredictParams( val email: String? = null, diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/responses/cart/CartItem.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/responses/cart/CartItem.kt index 7aaaa94b..f882494e 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/api/responses/cart/CartItem.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/responses/cart/CartItem.kt @@ -2,6 +2,7 @@ package com.personalization.api.responses.cart import com.google.gson.annotations.SerializedName +/** One product in the customer's cart: its id ([id], `uniqid` in the answer) and how many of it. */ data class CartItem( @SerializedName("uniqid") val id: String, @SerializedName("quantity") val quantity: Int diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/responses/predict/PurchasePredictResponse.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/responses/predict/PurchasePredictResponse.kt index d625da92..0e529a78 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/api/responses/predict/PurchasePredictResponse.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/responses/predict/PurchasePredictResponse.kt @@ -2,9 +2,15 @@ package com.personalization.api.responses.predict import com.google.gson.annotations.SerializedName +/** + * The answer of [com.personalization.api.managers.PredictManager.getProbabilityToPurchase]: the `payload` + * of `{"status": "success", "payload": {"probability", "client_id"}}`. + */ data class PurchasePredictResponse( + /** From 0 to 1, to hundredths. */ @SerializedName("probability") val probability: Double, + /** The id of the customer the server found (a number in the answer); empty when none. */ @SerializedName("client_id") val clientId: String ) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/responses/reviews/ReviewsModels.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/responses/reviews/ReviewsModels.kt new file mode 100644 index 00000000..1ffd8c15 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/responses/reviews/ReviewsModels.kt @@ -0,0 +1,118 @@ +package com.personalization.api.responses.reviews + +/* + * The models of the `reviews` namespace (`com.personalization.api.managers.ReviewsApi`): what the + * questions and thanks of the polls say, a saved rating, and the reviews of products. A text the shop + * left empty is null. + */ + +/** + * A rating saved by `createNps`, `createCsat` or `createCes`: [id] of the review the server saved, or of the + * earlier one it updated. A 64-bit id: the server's ids of reviews are `bigint`. + */ +data class PollReview(val id: Long) + +/** + * An NPS category — what the customer rates (`checkout`, `delivery`) — with the question to ask after the + * rating and the thanks to show once it is sent: `detractor…` for 0–6, `passive…` for 7–8, `promoter…` for 9–10. + */ +data class NpsCategory( + val code: String, + val name: String, + val detractorQuestion: String? = null, + val passiveQuestion: String? = null, + val promoterQuestion: String? = null, + val detractorSuccess: String? = null, + val passiveSuccess: String? = null, + val promoterSuccess: String? = null, + /** The label of the button shown after the rating is sent. */ + val buttonLabel: String? = null, +) + +/** + * A CSAT campaign — the one interaction the customer rates — with its questions and thanks: + * `dissatisfied…` for 1–2, `neutral…` for 3, `satisfied…` for 4–5. + */ +data class CsatCampaign( + val code: String, + val name: String, + val dissatisfiedQuestion: String? = null, + val neutralQuestion: String? = null, + val satisfiedQuestion: String? = null, + val dissatisfiedSuccess: String? = null, + val neutralSuccess: String? = null, + val satisfiedSuccess: String? = null, + /** The label of the button shown after the rating is sent. */ + val buttonLabel: String? = null, +) + +/** + * A CES campaign — how much effort a task took the customer — with its questions and thanks: + * `difficult…` for 1–3, `neutral…` for 4–5, `easy…` for 6–7. + */ +data class CesCampaign( + val code: String, + val name: String, + val difficultQuestion: String? = null, + val neutralQuestion: String? = null, + val easyQuestion: String? = null, + val difficultSuccess: String? = null, + val neutralSuccess: String? = null, + val easySuccess: String? = null, + /** The label of the button shown after the rating is sent. */ + val buttonLabel: String? = null, +) + +/** A channel a rating comes from (`android_app`, `email`), common to NPS, CSAT and CES. */ +data class PollChannel(val code: String, val name: String) + +/** The published reviews of a product and its rating over all of them. */ +data class ProductReviewsResponse( + val summary: ProductRatingSummary, + /** The page of reviews `limit` and `offset` asked for, the newest first. */ + val reviews: List, +) + +/** A product's rating over all its published reviews, whatever page of them was asked for. */ +data class ProductRatingSummary( + /** How many published reviews the product has. */ + val count: Int, + /** The average rating, rounded to 0.1; null without reviews. */ + val averageRating: Double? = null, + /** How many reviews gave each rating, 1 to 5. */ + val ratings: Map = emptyMap(), +) + +/** One published review of a product; [id] is 64-bit, as the server's ids of reviews. */ +data class ProductReview( + val id: Long, + /** 1 to 5. */ + val rating: Int, + /** Null when the customer gave only a rating. */ + val comment: String? = null, + /** The author's name in the CDP; null when it is not known. */ + val author: String? = null, + /** The date and time of the review, ISO 8601, as the API sends it. */ + val createdAt: String, +) + +/** A review the device's customer wrote of a product of an order, in any state of moderation; [id] is 64-bit. */ +data class ClientReview( + val id: Long, + val itemId: String, + val orderId: String, + /** 1 to 5. */ + val rating: Int, + val comment: String? = null, + /** Null for a state this release does not know. */ + val state: ReviewState? = null, + /** The date and time of the review, ISO 8601, as the API sends it. */ + val createdAt: String, +) + +/** Where a review is in moderation; [value] is its name in the API. */ +enum class ReviewState(val value: String) { + MODERATION("moderation"), + PUBLISHED("published"), + REJECTED("rejected"), +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/BridgeApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/BridgeApi.kt index 696245eb..59ace1e1 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/BridgeApi.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/BridgeApi.kt @@ -21,7 +21,25 @@ package com.personalization.core * app's `PushCallbacks`; * - `BridgeErrors` — the whole [SdkError] behind an old `onError(code, message)`, and listeners that * report [SdkResult]; - * - `SDK.queueEvent` — a tracking event through the queue, completed once it is accepted. + * - `SDK.queueEvent` — a tracking event through the queue, completed once it is accepted; + * - the namespaces of the new core, where each method is a suspending function with a twin that ends in a + * [CompletionListener], and fails with [SdkError] — [SdkError.NotInitialized] on the legacy core, where + * they do not run, and [SdkError.InvalidArgument], before any request, for an argument the contract + * refuses: + * - `SDK.cart` — the customer's cart; + * - `SDK.products`, `SDK.collections`, `SDK.recommendations` and `SDK.search` — the catalog, its + * collections and recommendation blocks, and the search, the search agent on `Rees46Config.appDomain` + * among it; + * - `SDK.profile`, `SDK.subscriptions` and `SDK.segments` — the customer's profile, subscriptions and + * segments, and the device's A/B group; + * - `SDK.notifications` — the push events a bridge that parses its pushes reports itself, through the + * queue once per message, the push token and the push callbacks of one shop; + * - `SDK.stories`, `SDK.predict` and `SDK.loyalty` — the stories blocks, the probability to purchase, and + * the loyalty program on the customer's side; + * - `SDK.sliders` — banner sliders, whose banners' events are `TrackingApi.bannerView` and `bannerClick`, + * through the new core's queue only, in the public `tracking` namespace; + * - `SDK.reviews` — NPS, CSAT and CES ratings and their dictionaries on `Rees46Config.appDomain`, and the + * reviews of products. * * The instance's state needs nothing of its own: `SDK.onStateChange` tells the current state at once, * then every change. diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/SdkError.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/SdkError.kt index 046def93..cfdf5779 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/SdkError.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/SdkError.kt @@ -52,5 +52,10 @@ sealed class SdkError { } } -/** An [SdkError] as an exception, for the suspending methods. */ -class SdkException(val error: SdkError) : Exception(error.message) +/** + * An [SdkError] as an exception, for the suspending methods. Its message is the error's, or one that says + * more about this failure: a method of the new core called on the legacy one says so. + */ +class SdkException internal constructor(val error: SdkError, message: String) : Exception(message) { + constructor(error: SdkError) : this(error, error.message) +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreHttpClient.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreHttpClient.kt index 3a241333..5b7a96e8 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreHttpClient.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreHttpClient.kt @@ -9,6 +9,7 @@ import com.personalization.logs.SdkLogs import com.personalization.sdk.data.models.params.UserBasicParams import com.personalization.sdk.domain.models.NetworkMethod import com.personalization.sdk.domain.repositories.UserSettingsRepository +import com.personalization.utils.DomainFormattingUtils import kotlinx.coroutines.suspendCancellableCoroutine import okhttp3.Call import okhttp3.Callback @@ -80,6 +81,9 @@ internal object CoreHttp { * `/init` carries `did`, `sid` and `seance` only when they have a value (an empty `did` is not a * device), and no `segment`. A push event (`track/delivered` and the others) carries no `sid` or `seance` * and no empty field. + * + * A path under `api/v3/` goes to the host of API v3, [appUrl] (`Rees46Config.appDomain`); every other path + * to the API's, [baseUrl]. Both get the common fields. */ internal class CoreHttpClient( private val baseUrl: () -> String, @@ -89,6 +93,7 @@ internal class CoreHttpClient( shared: OkHttpClient = CoreHttp.shared, internal val timeouts: CoreTimeouts = CoreTimeouts(), private val clock: Clock = Clock.SYSTEM, + private val appUrl: () -> String = { appUrlOf(null) }, ) { /** This instance's client; [OkHttpClient.newBuilder] keeps the shared pool and dispatcher. */ @@ -109,15 +114,22 @@ internal class CoreHttpClient( .readTimeout(timeouts.initReadMs, TimeUnit.MILLISECONDS) .build() - /** The client for [method]: `/init` reads with its own timeout. */ - internal fun clientFor(method: NetworkMethod): OkHttpClient = - if (method.method == INIT_PATH) initClient else client + /** + * The client for [method]: `/init` reads with its own timeout, and a request with [readTimeoutMs] with + * that one; the client of every other request stays as it is. + */ + internal fun clientFor(method: NetworkMethod, readTimeoutMs: Long? = null): OkHttpClient = when { + readTimeoutMs != null -> client.newBuilder().readTimeout(readTimeoutMs, TimeUnit.MILLISECONDS).build() + method.method == INIT_PATH -> initClient + else -> client + } /** * Sends [params] (the method's own fields) to [method]; cancelling the caller cancels the request. With - * [commonFields] false the fields are all there already (the queue stamps its events itself). + * [commonFields] false the fields are all there already (the queue stamps its events itself). A method + * with a read timeout of its own passes it as [readTimeoutMs]: it holds for this request only. */ - suspend fun send(method: NetworkMethod, params: JSONObject, commonFields: Boolean = true): HttpResult { + suspend fun send(method: NetworkMethod, params: JSONObject, commonFields: Boolean = true, readTimeoutMs: Long? = null): HttpResult { if (!connectivity.isConnected) { log(LogLevel.WARNING, LogCodes.REQUEST_FAILED, "${line(method)}: no network") { context(method) + ("reason" to LogReasons.OFFLINE) @@ -132,7 +144,7 @@ internal class CoreHttpClient( return HttpResult.Failure(SdkError.InvalidArgument("The request could not be built")) } val started = clock.nowMillis() - val exchange = clientFor(method).newCall(built.request).exchange(phase) + val exchange = clientFor(method, readTimeoutMs).newCall(built.request).exchange(phase) report(method, built, exchange, clock.nowMillis() - started) return exchange.result } @@ -152,14 +164,21 @@ internal class CoreHttpClient( fields.remove(UserBasicParams.SEANCE) fields.keys().asSequence().toList().forEach { key -> if (fields.opt(key) == "") fields.remove(key) } } - val url = (baseUrl() + method.method).toHttpUrl() + val base = if (method.method.startsWith(API_V3_PATH)) appUrl() else baseUrl() + val url = (base + method.method).toHttpUrl() val builder = Request.Builder() .header(USER_AGENT, SDK.userAgent()) .tag(Phase::class.java, phase) return when (method) { is NetworkMethod.GET -> { val query = url.newBuilder() - fields.keys().forEach { key -> query.addQueryParameter(key, fields.getString(key)) } + fields.keys().forEach { key -> + // A list goes as the key repeated, once per item: `promo_codes[]=A&promo_codes[]=B`. + when (val value = fields.get(key)) { + is JSONArray -> for (index in 0 until value.length()) query.addQueryParameter(key, value.get(index).toString()) + else -> query.addQueryParameter(key, fields.getString(key)) + } + } Built(builder.url(query.build()).get().build(), null) } is NetworkMethod.POST -> { @@ -212,7 +231,7 @@ internal class CoreHttpClient( } // OkHttp gives every answer it hands over a body; without one the answer is empty. val text = response.body?.string().orEmpty() - if (text.isBlank()) return Exchange(HttpResult.Success(JSONObject()), status, text) + if (text.isBlank()) return Exchange(HttpResult.Success(JSONObject(), empty = true), status, text) val json = try { JSONTokener(text).nextValue() } catch (e: JSONException) { @@ -332,6 +351,20 @@ internal class CoreHttpClient( private const val ERROR_TIMEOUT = "timeout" private val HTTP_SUCCESS = 200..299 private val JSON = "application/json; charset=utf-8".toMediaType() + + /** The paths of API v3, which live on the host of `Rees46Config.appDomain`. */ + const val API_V3_PATH = "api/v3/" + private const val DEFAULT_APP_DOMAIN = "app.rees46.ru" + + /** + * The base URL of API v3 for [appDomain] (`Rees46Config.appDomain`): `https://` unless it names its + * scheme, a trailing slash; a missing or blank one is `app.rees46.ru`. Throws for a scheme other than + * `http` or `https`: read when a request is built, it fails that request only. + */ + fun appUrlOf(appDomain: String?): String = DomainFormattingUtils.formatApiDomain( + apiDomain = appDomain?.trim()?.takeIf { it.isNotEmpty() } ?: DEFAULT_APP_DOMAIN, + addTrailingSlash = true, + ) } } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CorePushTokens.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CorePushTokens.kt index 1f7f229d..e5d3909f 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CorePushTokens.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CorePushTokens.kt @@ -4,6 +4,7 @@ import android.content.SharedPreferences import com.personalization.LogLevel import com.personalization.PushProvider import com.personalization.api.OnApiCallbackListener +import com.personalization.core.PushToken import com.personalization.core.SdkError import com.personalization.logs.LogCodes import com.personalization.logs.LogReasons @@ -33,7 +34,8 @@ import java.util.concurrent.atomic.AtomicBoolean * when. A token the shop has not sent goes at once; the same token at most once a week. * - The week is taken before the request: two sends of one token at once make one request, the second * hearing the first's answer. The claim is kept in the partition with its time, and the token and the - * date of the send only once the server took it. A failed send gives the claim back, and a claim older + * date of the send only once the server took it. A failed send gives the claim back, a `2xx` answer + * `{"status": "error"}` among them (its listeners hear `decoding`), and a claim older * than [CLAIM_TTL_MS] (five minutes) without a send — its process died — is free. The week, the claim and * the send are kept for each provider (FCM, HMS) on its own. * - A token goes only once the instance is ready ([ready]) and never without a `did`. A token the app @@ -96,6 +98,22 @@ internal class CorePushTokens( /** The device's token of [provider], or the one this shop sent last. */ fun token(provider: PushProvider): String? = device.pushToken(provider.id) ?: sentToken(provider) + /** + * `notifications.getPushToken`: the token of [provider] ([token]); without one, that of the provider + * whose token this shop sent last, or — when it sent none — the device's, FCM before HMS. Null when there + * is none, and after [release]. Reads the storage, never the network. + */ + fun known(provider: PushProvider?): PushToken? { + if (synchronized(lock) { released }) return null + val providers = if (provider != null) { + listOf(provider) + } else { + val sent = PushProvider.entries.filter { sentToken(it) != null }.sortedByDescending(::sentDate) + sent + (PushProvider.entries - sent.toSet()) + } + return providers.firstNotNullOfOrNull { candidate -> token(candidate)?.let { PushToken(it, candidate) } } + } + /** * A token FCM or HMS gave: kept and sent, when the shop takes them, once the instance is ready. A shop * that does not send tokens by itself neither keeps nor sends it (`push_token_skipped`, `auto_send_off`). @@ -213,9 +231,21 @@ internal class CorePushTokens( /** Guarded by [lock]: the answer was taken. */ private var ended = false - override fun onSuccess(response: JSONObject?) = landed { waiting -> - log(LogLevel.INFO, LogCodes.PUSH_TOKEN_SENT, "Push token sent", mapOf("provider" to provider.id)) - waiting.forEach { delivery.success(it, response ?: JSONObject()) } + override fun onSuccess(response: JSONObject?) { + if (response?.optString(FIELD_STATUS) == STATUS_ERROR) { + // A `2xx` whose body says it failed took no token: `decoding`, as the namespaces read + // such an answer, and the week stays free. + landed(failed = true) { waiting -> + log(LogLevel.WARNING, LogCodes.PUSH_TOKEN_FAILED, "Push token was not sent: the answer is an error with a 2xx status", + mapOf("provider" to provider.id, "error" to ERROR_DECODING)) + waiting.forEach { delivery.failure(it, LegacyErrors.of(SdkError.Decoding)) } + } + return + } + landed { waiting -> + log(LogLevel.INFO, LogCodes.PUSH_TOKEN_SENT, "Push token sent", mapOf("provider" to provider.id)) + waiting.forEach { delivery.success(it, response ?: JSONObject()) } + } } override fun onSuccess(response: JSONArray) = landed { waiting -> @@ -341,6 +371,9 @@ internal class CorePushTokens( const val REASON_PUSH_ONLY = LogReasons.PUSH_ONLY private const val FIELD_PLATFORM = "platform" + private const val FIELD_STATUS = "status" + private const val STATUS_ERROR = "error" + private const val ERROR_DECODING = "decoding" private const val FIELD_TOKEN = "token" private const val FIELD_PUSH_PROVIDER = "push_provider" private const val PLATFORM_ANDROID = "android" diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreV2.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreV2.kt index ea89e79a..43f2a70c 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreV2.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreV2.kt @@ -12,7 +12,10 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async import kotlinx.coroutines.cancel +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first @@ -30,7 +33,8 @@ import java.util.concurrent.atomic.AtomicBoolean * `track/stories`, `track/slider`, `popup/showed`) go to the [EventQueue] instead, once it is set. * * Every request ends in exactly one callback, on a background thread as today: the answer, or the - * error mapped to the old `onError(code, msg)` by [LegacyErrors]. [release] cancels the requests in + * error mapped to the old `onError(code, msg)` by [LegacyErrors]. [request] is the same path for the + * namespaces: it returns the outcome with its [SdkError] instead. [release] cancels the requests in * flight (`cancelled`) and stops `/init`, and a request made after it fails with `notInitialized`. */ internal class CoreV2( @@ -126,28 +130,7 @@ internal class CoreV2( } private fun sendNow(method: NetworkMethod, params: JSONObject, needsSession: Boolean = true, answer: (HttpResult) -> Boolean) { - val request = requests.launch { - val waited = if (needsSession) awaitInstance() else awaitReady() - if (waited != null) { - if (waited == SdkError.Timeout) { - SdkLogs.log(LogLevel.WARNING, LogCodes.REQUEST_FAILED, "${method.type} ${method.method}: the SDK is not ready", shopId, - mapOf("method" to method.type, "path" to method.method, "reason" to LogReasons.NOT_READY)) - } - answer(HttpResult.Failure(waited)) - return@launch - } - val result = try { - client.send(method, params) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - // The client turns every failure into a result; this is the net under it. - SdkLogs.log(LogLevel.WARNING, LogCodes.REQUEST_FAILED, "${method.type} ${method.method}: no answer", shopId, - mapOf("method" to method.type, "path" to method.method), e) - HttpResult.Failure(SdkError.Network) - } - answer(result) - } + val request = requests.launch { answer(perform(method, params, needsSession)) } // Cancelled before or while it ran: the request still gets its one answer. request.invokeOnCompletion { cause -> if (cause != null) endings.launch { @@ -160,12 +143,63 @@ internal class CoreV2( } /** - * Waits, within the read timeout, for the instance's `/init` to be set, for the instance to be ready - * and, when the session's window ended, for the `/init` of a new session ([CoreInit.usable]); then - * the request gets its own full timeout. Null when it may go. + * A request with a result, for the namespaces: it waits for the instance as [send] does, within + * [readTimeoutMs] (the client's read timeout without one), goes once and returns its outcome. Nothing + * repeats it: whether to ask again is the caller's choice. + * + * After [release] it fails with `notInitialized` without a request, and [release] ends one in flight + * with `cancelled`. Cancelling the caller cancels the request too, and the caller gets its own + * [CancellationException], as a cancelled coroutine does. + */ + suspend fun request(method: NetworkMethod, params: JSONObject, readTimeoutMs: Long? = null): HttpResult { + if (released) return HttpResult.Failure(SdkError.NotInitialized) + val call = requests.async { perform(method, params, readTimeoutMs = readTimeoutMs) } + return try { + call.await() + } catch (e: CancellationException) { + call.cancel() + // The caller was cancelled: its cancellation goes on. + currentCoroutineContext().ensureActive() + // The instance was released while the request waited or went. + SdkLogs.log(LogLevel.DEBUG, LogCodes.REQUEST_CANCELLED, "${method.type} ${method.method}: cancelled", shopId, + mapOf("method" to method.type, "path" to method.method)) + HttpResult.Failure(SdkError.Cancelled) + } + } + + /** + * One request: waits for the instance — with [needsSession] for a live session too — within + * [readTimeoutMs] or the client's read timeout, then sends. Every failure is a result. + */ + private suspend fun perform(method: NetworkMethod, params: JSONObject, needsSession: Boolean = true, readTimeoutMs: Long? = null): HttpResult { + val waitMs = readTimeoutMs ?: readyWaitMs + val waited = if (needsSession) awaitInstance(waitMs) else awaitReady(waitMs) + if (waited != null) { + if (waited == SdkError.Timeout) { + SdkLogs.log(LogLevel.WARNING, LogCodes.REQUEST_FAILED, "${method.type} ${method.method}: the SDK is not ready", shopId, + mapOf("method" to method.type, "path" to method.method, "reason" to LogReasons.NOT_READY)) + } + return HttpResult.Failure(waited) + } + return try { + client.send(method, params, readTimeoutMs = readTimeoutMs) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // The client turns every failure into a result; this is the net under it. + SdkLogs.log(LogLevel.WARNING, LogCodes.REQUEST_FAILED, "${method.type} ${method.method}: no answer", shopId, + mapOf("method" to method.type, "path" to method.method), e) + HttpResult.Failure(SdkError.Network) + } + } + + /** + * Waits, within [waitMs] (the read timeout), for the instance's `/init` to be set, for the instance to + * be ready and, when the session's window ended, for the `/init` of a new session ([CoreInit.usable]); + * then the request gets its own full timeout. Null when it may go. */ - private suspend fun awaitInstance(): SdkError? { - val waited = withTimeoutOrNull(readyWaitMs) { + private suspend fun awaitInstance(waitMs: Long = readyWaitMs): SdkError? { + val waited = withTimeoutOrNull(waitMs) { val current = initFlow.filterNotNull().first() Verdict(current.usable()) } @@ -173,8 +207,8 @@ internal class CoreV2( } /** [awaitInstance] for what needs only a `did`: the instance ready, whatever its session. Null when it may go. */ - private suspend fun awaitReady(): SdkError? { - val waited = withTimeoutOrNull(readyWaitMs) { + private suspend fun awaitReady(waitMs: Long = readyWaitMs): SdkError? { + val waited = withTimeoutOrNull(waitMs) { val current = initFlow.filterNotNull().first() Verdict(current.ready()) } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/HttpResult.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/HttpResult.kt index 7a170999..d3840610 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/HttpResult.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/HttpResult.kt @@ -7,8 +7,11 @@ import org.json.JSONObject /** The outcome of one request of the new client. */ internal sealed interface HttpResult { - /** A `2xx` answer: a [JSONObject] (empty for an empty answer) or a [JSONArray]. */ - class Success(val body: Any) : HttpResult + /** + * A `2xx` answer: a [JSONObject] or a [JSONArray]. [empty] is an answer without a body, whose [body] + * is an empty [JSONObject]: a request with a result reads it as an empty result, not as `{}`. + */ + class Success(val body: Any, val empty: Boolean = false) : HttpResult /** * [errorBody] is the body of an answer outside `2xx`, kept only for the old callbacks, which got it diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/LegacyCore.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/LegacyCore.kt index 177526e2..8350cb50 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/LegacyCore.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/LegacyCore.kt @@ -30,9 +30,13 @@ import java.util.concurrent.Executor * success, an empty answer or one that is not JSON succeeds with an empty object, no connection is * `504` and a failure without an answer `-1`. It cannot cancel a request in flight; after [release] a * request fails at once with `notInitialized` (`onError(-1)`). + * + * A path under `api/v3/` goes to the host of API v3, [appUrl] (`Rees46Config.appDomain`), as on the new + * core; every other path to the API's, [baseUrl]. */ internal class LegacyCore( private val settings: UserSettingsRepository, + private val appUrl: () -> String = { CoreHttpClient.appUrlOf(null) }, private val baseUrl: () -> String, ) : Core { @@ -88,7 +92,7 @@ internal class LegacyCore( // The outcome is decided first and delivered once the connection is done with, so a // callback that throws cannot change it. val outcome: Outcome = try { - logUrl = baseUrl() + networkMethod.method + logUrl = baseOf(networkMethod) + networkMethod.method val buildUri = build(networkMethod, params) val url = getUrl(networkMethod, buildUri) logUrl = url.toString() @@ -169,12 +173,16 @@ internal class LegacyCore( return Outcome.Success(if (json is JSONObject || json is JSONArray) json else JSONObject()) } + /** The host of [networkMethod]'s path; read when the request is built, so a bad `appDomain` fails that request only. */ + private fun baseOf(networkMethod: NetworkMethod): String = + if (networkMethod.method.startsWith(CoreHttpClient.API_V3_PATH)) appUrl() else baseUrl() + private fun build( networkMethod: NetworkMethod, params: JSONObject ): Uri { - val builder = Uri.parse(baseUrl() + networkMethod.method).buildUpon() + val builder = Uri.parse(baseOf(networkMethod) + networkMethod.method).buildUpon() val it = params.keys() while (it.hasNext()) { @@ -191,7 +199,7 @@ internal class LegacyCore( ): URL { return if (networkMethod is NetworkMethod.POST) { - URL(baseUrl() + networkMethod.method) + URL(baseOf(networkMethod) + networkMethod.method) } else { URL(buildUri.toString()) } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/NamespaceArguments.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/NamespaceArguments.kt new file mode 100644 index 00000000..29860099 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/NamespaceArguments.kt @@ -0,0 +1,110 @@ +package com.personalization.core.internal + +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import org.json.JSONArray +import org.json.JSONObject +import java.math.BigDecimal +import java.net.URLEncoder + +/* + * Checking a namespace method's arguments and writing them as the request's fields, by the contract's + * rules (`contract/README.md`, "Параметры"; `contract/products.md`, `ProductsListRequest`), inside + * [NamespaceCalls.checked]: a wrong argument is `invalidArgument` before any request, `null` is a field not + * sent, a list goes as one string joined with commas and no spaces, an empty list is not sent, a fractional + * number goes without trailing zeros (`100`, not `100.0`). + */ + +/** + * Ends the call with [SdkError.InvalidArgument]: [message] names the argument and the rule it breaks, never + * its value. Inside [NamespaceCalls.checked], which logs it. + */ +internal fun invalidArgument(message: String): Nothing = throw SdkException(SdkError.InvalidArgument(message)) + +/** [value] when it is not blank; otherwise the call fails with `invalidArgument` naming [name]. */ +internal fun requireNotBlank(value: String, name: String): String = + value.takeIf { it.isNotBlank() } ?: invalidArgument("$name must not be empty") + +/** Fails with `invalidArgument` when a contact or a customer's id is given and is empty: null is "not sent", not "". */ +internal fun requireContact(value: String?, name: String) { + if (value != null && value.isBlank()) invalidArgument("$name must not be empty") +} + +private val DATE = Regex("""(\d{4})-(\d{2})-(\d{2})""") + +/** The year of [value] when it is a day of the calendar as `YYYY-MM-DD` (`2026-02-30` is none); null otherwise. */ +private fun calendarYear(value: String): Int? { + val (year, month, day) = DATE.matchEntire(value)?.destructured?.toList()?.map { it.toInt() } ?: return null + val days = when (month) { + 1, 3, 5, 7, 8, 10, 12 -> 31 + 4, 6, 9, 11 -> 30 + 2 -> if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) 29 else 28 + else -> 0 + } + return year.takeIf { day in 1..days } +} + +/** + * Whether [value] is an existing day of the calendar as `YYYY-MM-DD`: `2026-02-30` is none. A birthday + * `loyalty/members/join` cannot read erases the date it has. + */ +internal fun isCalendarDate(value: String): Boolean = calendarYear(value) != null + +/** + * Whether [value] is a birthday `profile/set` takes: an existing day `YYYY-MM-DD` of the years 1000 to + * 2999. The server ignores any other in silence. + */ +internal fun isBirthday(value: String): Boolean = calendarYear(value)?.let { it in 1000..2999 } == true + +/** Fails with `invalidArgument` naming [name] unless [value] is a birthday `profile/set` takes ([isBirthday]). */ +internal fun requireBirthday(value: String, name: String) { + if (!isBirthday(value)) invalidArgument("$name must be a date YYYY-MM-DD of the years 1000 to 2999") +} + +/** Fails with `invalidArgument` when [value] is given and is below [min]. */ +internal fun requireAtLeast(value: Int?, min: Int, name: String) { + if (value != null && value < min) invalidArgument("$name must be at least $min") +} + +/** Fails with `invalidArgument` when a price bound is negative or not a number, or when [min] is above [max]. */ +internal fun requirePriceRange(min: Double?, max: Double?, minName: String = "priceMin", maxName: String = "priceMax") { + if (min != null && !(min.isFinite() && min >= 0)) invalidArgument("$minName must be a number not below 0") + if (max != null && !(max.isFinite() && max >= 0)) invalidArgument("$maxName must be a number not below 0") + if (min != null && max != null && min > max) invalidArgument("$minName must not be above $maxName") +} + +/** Puts [value] under [key] unless it is null. */ +internal fun JSONObject.putIfNotNull(key: String, value: Any?): JSONObject { + if (value != null) put(key, value) + return this +} + +/** Puts [values] under [key] as one string joined with commas and no spaces; nothing for null or an empty list. */ +internal fun JSONObject.putList(key: String, values: List?): JSONObject { + if (!values.isNullOrEmpty()) put(key, values.joinToString(",")) + return this +} + +/** Puts [value] under [key] as a number without trailing zeros (`100`, `99.5`); nothing for null. */ +internal fun JSONObject.putNumber(key: String, value: Double?): JSONObject { + if (value != null) put(key, plainNumber(value)) + return this +} + +/** + * Puts the free-form [filters] (a product's parameter → its values) under [key] as a JSON string: + * `{"color":["red"]}`. Nothing for null or an empty map. + */ +internal fun JSONObject.putFilters(key: String, filters: Map>?): JSONObject { + if (filters.isNullOrEmpty()) return this + val json = JSONObject() + filters.forEach { (name, values) -> json.put(name, JSONArray(values)) } + put(key, json.toString()) + return this +} + +/** [value] as the API reads a number: without trailing zeros and without an exponent. */ +internal fun plainNumber(value: Double): String = BigDecimal.valueOf(value).stripTrailingZeros().toPlainString() + +/** [value] encoded for one segment of a path: `a/b c` is `a%2Fb%20c`. */ +internal fun pathSegment(value: String): String = URLEncoder.encode(value, "UTF-8").replace("+", "%20") diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/NamespaceCalls.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/NamespaceCalls.kt new file mode 100644 index 00000000..1c2553df --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/NamespaceCalls.kt @@ -0,0 +1,205 @@ +package com.personalization.core.internal + +import com.personalization.LogLevel +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import com.personalization.sdk.domain.models.NetworkMethod +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.json.JSONObject + +/** + * The path every method of a namespace (`sdk.cart`, and those after it) takes: its arguments checked before + * anything is asked ([checked]), then one request with a result over the new core ([request]) with its + * answer read into the method's model, or one event through the new core's queue ([event]); and the + * contract's two forms of a method — a suspending function and one that ends in a [CompletionListener]. + * + * The namespaces run on the new core only, which the bridges start with `Rees46.initializeBridge`. On the + * legacy core a call fails with [SdkError.NotInitialized] at once, without a request, and the log says why + * (`core_flag_mismatch`, at warning); so it does on an instance never initialized or released. The core + * decides before the arguments: on the legacy core every call ends the same way, whatever its arguments. + * + * What a call can end with: the value; [SdkError.InvalidArgument] for an argument the contract refuses, + * without a request; [SdkError.ShopBlocked] for a refused shop; [SdkError.Timeout] when the instance was not + * ready within the read timeout, or the answer did not come in it; [SdkError.Network] without a connection; + * [SdkError.Http] for an answer outside `2xx` (`serverCode` stays null: the server sends no machine code + * yet); [SdkError.Decoding] for a `2xx` answer that does not read into the model, `{"status": "error"}` + * among them; [SdkError.Cancelled] when `release()` ends the request. Nothing repeats a request. A `402`, + * `403` or `404` changes nothing in the instance: it may refuse one service, not the shop. + */ +internal class NamespaceCalls( + private val core: () -> Core?, + private val dispatchers: () -> CoreDispatchers, + private val shopId: () -> String?, +) { + + /** Where the listener forms run; nothing they do reaches the app's process as an exception. */ + private val scope: CoroutineScope by lazy { + CoroutineScope(SupervisorJob() + dispatchers().io + CoroutineExceptionHandler { _, throwable -> + SdkLogs.log(LogLevel.ERROR, LogCodes.SDK_LOG, "A call of a namespace failed unexpectedly", shopId(), throwable = throwable) + }) + } + + /** + * What [build] makes of a method's arguments — the request's fields, a path, or nothing — for the + * namespace method [call] (`cart.get`, for the log), once the call may go: off the new core it fails with + * [SdkError.NotInitialized] first, whatever the arguments, logged as `core_flag_mismatch`; then a wrong + * argument, which [build] reports with [invalidArgument], fails it with [SdkError.InvalidArgument], logged + * as `invalid_argument` with the call — and [reason], for a method whose refusals have codes of their own + * (`empty_code`) — never with an argument's value. Nothing is sent. The one check of the namespaces: + * [request] and [event] make it too. + * + * @throws SdkException with the reason. + */ + fun checked(call: String, reason: String? = null, build: () -> T): T { + newCore(call) + return refusing(call, reason, build) + } + + /** + * Sends [params] to [method] for the namespace method [call] and reads the `2xx` answer with [read]: it + * gets the answer's [JSONObject] or [org.json.JSONArray], or null for an answer without a body, and + * returns the method's value, or null when the answer does not fit it (`decoding`). A method with a read + * timeout of its own passes [readTimeoutMs]. A method with arguments builds [params] in [checked] first. + * + * @throws SdkException with the reason the call failed. + */ + suspend fun request( + call: String, + method: NetworkMethod, + params: JSONObject = JSONObject(), + readTimeoutMs: Long? = null, + read: (Any?) -> T?, + ): T { + return when (val result = newCore(call).request(method, params, readTimeoutMs)) { + is HttpResult.Failure -> throw SdkException(result.error) + is HttpResult.Success -> readAnswer(call, method, result, read) ?: throw SdkException(SdkError.Decoding) + } + } + + /** + * An event of the namespace method [call] (`tracking.bannerView`): the fields [fields] makes, checked as + * [checked] checks them, to [path] through the new core's queue, which adds the common fields and sends + * it. The queue gets it on the caller's thread, so events keep the order of the calls. [listener] hears + * once, on the main thread: success once the queue accepted the event, or why it did not — what + * [checked] says, [SdkError.NotInitialized] after `release()`, [SdkError.ShopBlocked] for a refused shop. + * A refused event is not sent. + */ + fun event(call: String, path: String, listener: CompletionListener?, fields: () -> JSONObject) { + val core: CoreV2 + val params: JSONObject + try { + core = newCore(call) + params = refusing(call, null, fields) + } catch (e: SdkException) { + tell(listener, SdkResult.Failure(e.error)) + return + } + core.accept(path, params) { refused -> + tell(listener, if (refused == null) SdkResult.Success(Unit) else SdkResult.Failure(refused)) + } + } + + /** + * The form of a method for Java and for code outside coroutines: runs [block], its suspending form, and + * hands [listener] its value or its error, once, on the main thread ([tell]). + */ + fun complete(listener: CompletionListener, block: suspend () -> T) { + scope.launch { + val result: SdkResult = try { + SdkResult.Success(block()) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } catch (e: CancellationException) { + // The scope is never cancelled: a request's cancellation comes back as `cancelled` already. + SdkResult.Failure(SdkError.Cancelled) + } catch (e: Exception) { + SdkLogs.log(LogLevel.ERROR, LogCodes.SDK_LOG, "A call of a namespace failed unexpectedly", shopId(), throwable = e) + SdkResult.Failure(SdkError.Network) + } + hand(listener, result) + } + } + + /** + * Hands [listener] the [result] it already has, once, on the main thread and never on the caller's + * stack; nothing without a listener. + */ + fun tell(listener: CompletionListener?, result: SdkResult) { + if (listener == null) return + scope.launch { hand(listener, result) } + } + + /** Calls [listener] on the main thread; an exception it throws is logged as `callback_failed` and goes no further. */ + private suspend fun hand(listener: CompletionListener, result: SdkResult) { + withContext(dispatchers().main) { + try { + listener.onComplete(result) + } catch (e: Exception) { + SdkLogs.log(LogLevel.ERROR, LogCodes.CALLBACK_FAILED, "The app's CompletionListener threw", shopId(), throwable = e) + } + } + } + + /** The value [read] makes of a `2xx` answer; null, logged as `decoding_failed`, when it makes none. */ + private fun readAnswer(call: String, method: NetworkMethod, result: HttpResult.Success, read: (Any?) -> T?): T? { + val body = result.body.takeUnless { result.empty } + if (body is JSONObject && body.optString(STATUS) == STATUS_ERROR) { + // Not the server's message: an error's text may repeat what the request carried. + decodingFailed(call, method, "The answer to ${method.type} ${method.method} is an error with a 2xx status") + return null + } + val value = try { + read(body) + } catch (e: Exception) { + null + } + if (value == null) decodingFailed(call, method, "The answer to ${method.type} ${method.method} does not read as $call's result") + return value + } + + private fun decodingFailed(call: String, method: NetworkMethod, message: String) { + SdkLogs.log(LogLevel.WARNING, LogCodes.DECODING_FAILED, message, shopId(), + mapOf("call" to call, "method" to method.type, "path" to method.method)) + } + + /** The new core for [call]; otherwise the call fails with `notInitialized`, logged on the legacy core. */ + private fun newCore(call: String): CoreV2 { + val core = core() + if (core !is CoreV2) throw notOnThisCore(call, core) + return core + } + + /** What [build] makes; a wrong argument it reports is logged as `invalid_argument` and fails [call]. */ + private fun refusing(call: String, reason: String?, build: () -> T): T = try { + build() + } catch (e: SdkException) { + val error = e.error + if (error is SdkError.InvalidArgument) { + val context = mapOf("call" to call) + (reason?.let { mapOf("reason" to it) } ?: emptyMap()) + SdkLogs.log(LogLevel.WARNING, LogCodes.INVALID_ARGUMENT, "$call was refused: ${error.message}", shopId(), context) + } + throw e + } + + /** The failure of [call] on an instance whose core is not the new one: [core] is the legacy one, or none. */ + private fun notOnThisCore(call: String, core: Core?): SdkException { + if (core == null) return SdkException(SdkError.NotInitialized) + val message = "$call runs on the new core only: start the shop with Rees46.initializeBridge" + SdkLogs.log(LogLevel.WARNING, LogCodes.CORE_FLAG_MISMATCH, message, shopId(), mapOf("call" to call)) + return SdkException(SdkError.NotInitialized, message) + } + + private companion object { + const val STATUS = "status" + const val STATUS_ERROR = "error" + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/PushHub.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/PushHub.kt index 160f1a91..21992fd1 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/PushHub.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/PushHub.kt @@ -60,6 +60,12 @@ internal object PushHub { */ private val reserved = HashMap Unit>>() + /** + * What the repeats parked beside [reserved] hear when the first one is accepted ([confirm]): the + * `notifications` methods, whose caller waits for a result, end there. Guarded like [reserved]. + */ + private val parkedRepeats = HashMap Unit>>() + /** What [reserve] decided for one event of one message. */ enum class Reservation { /** Taken: the caller hands the event to its queue, then [confirm]s or [release]s it. */ @@ -90,26 +96,39 @@ internal object PushHub { * Whether [event] of the message [code] may go to [shopId]'s queue now: once per process. The event * counts as sent only once a queue accepted it ([confirm]); one the queue did not take is [release]d * and may go when it comes again. A repeat that comes while the first is being handed over is - * [Reservation.PARKED]: [retry] runs if the first is released, so the two are never lost together. + * [Reservation.PARKED]: [retry] runs if the first is released, so the two are never lost together, and + * [repeat] if the first is accepted, as a repeat. */ - fun reserve(shopId: String, event: PushEvent, code: String, retry: () -> Unit): Reservation = synchronized(seen) { + fun reserve(shopId: String, event: PushEvent, code: String, repeat: () -> Unit = {}, retry: () -> Unit): Reservation = synchronized(seen) { val key = key(shopId, event, code) if (seen.containsKey(key)) return Reservation.REPEAT val waiting = reserved[key] if (waiting != null) { waiting += retry + parkedRepeats.getOrPut(key) { ArrayList() } += repeat return Reservation.PARKED } reserved[key] = ArrayList() Reservation.TAKEN } - /** A queue accepted the event [reserve] took: a repeat sends nothing from now on, the parked ones included. */ + /** + * A queue accepted the event [reserve] took: a repeat sends nothing from now on, the parked ones included, + * which hear their `repeat` now, on this thread. + */ fun confirm(shopId: String, event: PushEvent, code: String) { val key = key(shopId, event, code) - synchronized(seen) { + val repeats = synchronized(seen) { reserved.remove(key) seen[key] = true + parkedRepeats.remove(key) + }.orEmpty() + repeats.forEach { repeat -> + try { + repeat() + } catch (e: Exception) { + SdkLogs.log(LogLevel.ERROR, LogCodes.PUSH_FAILED, "A repeat of a push event could not be told it was sent", shopId, throwable = e) + } } } @@ -118,7 +137,11 @@ internal object PushHub { * parked meanwhile try again now, on this thread. */ fun release(shopId: String, event: PushEvent, code: String) { - val parked = synchronized(seen) { reserved.remove(key(shopId, event, code)) }.orEmpty() + val parked = synchronized(seen) { + // The repeats try again, and each tells its own end. + parkedRepeats.remove(key(shopId, event, code)) + reserved.remove(key(shopId, event, code)) + }.orEmpty() parked.forEach { retry -> try { retry() @@ -227,6 +250,7 @@ internal object PushHub { synchronized(seen) { seen.clear() reserved.clear() + parkedRepeats.clear() } forgetPushes() facadeReported.clear() diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/TolerantJson.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/TolerantJson.kt new file mode 100644 index 00000000..41b2ab77 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/TolerantJson.kt @@ -0,0 +1,101 @@ +package com.personalization.core.internal + +import org.json.JSONArray +import org.json.JSONObject + +/* + * Reading the API's answers into the namespaces' models, as the contract asks (`contract/README.md`, + * "Ответы"): a field that is missing or `null` is null, a number may come as a string and a string as a + * number, a value of the wrong kind is null rather than an error, and fields the model does not know are + * never looked at. A model decides what it cannot do without; `decoding` is for an answer that does not + * fit the model as a whole. + */ + +/** The value of [key]; null when it is missing or JSON `null`. */ +internal fun JSONObject.valueOrNull(key: String): Any? = opt(key)?.takeUnless { it == JSONObject.NULL } + +/** + * [key] as a string: a string as it is, a number as its digits (`37`, not `37.0`, for a whole one), a + * boolean as `true` or `false`. Null when missing, `null`, an object or an array. + */ +internal fun JSONObject.stringOrNull(key: String): String? = when (val value = valueOrNull(key)) { + is String -> value + is Number -> value.wholeOrNull()?.toString() ?: value.toString() + is Boolean -> value.toString() + else -> null +} + +/** [stringOrNull] that is null for an empty or blank string too: for ids and codes. */ +internal fun JSONObject.nonBlankStringOrNull(key: String): String? = stringOrNull(key)?.takeIf { it.isNotBlank() } + +/** [key] as a whole number that fits an [Int], given as a number or a string (`2`, `"2"`, `2.0`); otherwise null. */ +internal fun JSONObject.intOrNull(key: String): Int? = + longOrNull(key)?.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.toInt() + +/** [key] as a whole number, given as a number or a string (`2`, `"2"`, `2.0`); otherwise null. */ +internal fun JSONObject.longOrNull(key: String): Long? = when (val value = valueOrNull(key)) { + is Number -> value.wholeOrNull() + is String -> value.trim().let { text -> text.toLongOrNull() ?: text.toDoubleOrNull()?.wholeOrNull() } + else -> null +} + +/** [key] as a finite number, given as a number or a string (`999.5`, `"999.5"`); otherwise null. */ +internal fun JSONObject.doubleOrNull(key: String): Double? = when (val value = valueOrNull(key)) { + is Number -> value.toDouble() + is String -> value.trim().toDoubleOrNull() + else -> null +}?.takeIf { it.isFinite() } + +/** [key] as a boolean: `true`/`false`, as JSON or as a string, or `1`/`0`; otherwise null. */ +internal fun JSONObject.booleanOrNull(key: String): Boolean? = when (val value = valueOrNull(key)) { + is Boolean -> value + is Number -> when (value.wholeOrNull()) { + 1L -> true + 0L -> false + else -> null + } + is String -> when (value.trim().lowercase()) { + "true", "1" -> true + "false", "0" -> false + else -> null + } + else -> null +} + +/** [key] as an object; null when it is missing or of another kind. */ +internal fun JSONObject.objectOrNull(key: String): JSONObject? = valueOrNull(key) as? JSONObject + +/** [key] as an array; null when it is missing or of another kind. */ +internal fun JSONObject.arrayOrNull(key: String): JSONArray? = valueOrNull(key) as? JSONArray + +/** + * The objects of the array read with [read], in order. An element that is not an object, or that [read] + * turns down with null, is left out: one bad element does not lose the others. + */ +internal fun JSONArray.mapObjects(read: (JSONObject) -> T?): List = + (0 until length()).mapNotNull { index -> (opt(index) as? JSONObject)?.let(read) } + +/** The strings of the array, numbers written as [stringOrNull] writes them; anything else is left out. */ +internal fun JSONArray.strings(): List = (0 until length()).mapNotNull { index -> + when (val value = opt(index)) { + is String -> value + is Number -> value.wholeOrNull()?.toString() ?: value.toString() + else -> null + } +} + +/** + * The value of a closed set whose wire name is [raw]; null for a name the SDK does not know, so a value the + * server adds later leaves the field empty instead of failing the answer. + */ +internal fun valueOfWire(raw: String?, values: Iterable, wire: (T) -> String): T? = + raw?.let { name -> values.firstOrNull { wire(it) == name } } + +/** The number as a [Long] when it is whole and fits one; otherwise null. */ +private fun Number.wholeOrNull(): Long? = when (this) { + is Int -> toLong() + is Long -> this + is Short -> toLong() + is Byte -> toLong() + else -> toDouble().takeIf { it.isFinite() && it == Math.floor(it) && it >= Long.MIN_VALUE && it <= Long.MAX_VALUE }?.toLong() +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/di/SdkModule.kt b/personalization-sdk/src/main/kotlin/com/personalization/di/SdkModule.kt index 34db6e4b..e140b7ab 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/di/SdkModule.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/di/SdkModule.kt @@ -16,6 +16,8 @@ import com.personalization.api.managers.PredictManager import com.personalization.api.managers.SearchManager import com.personalization.api.managers.TrackEventManager import com.personalization.api.managers.TrackingApi +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.NamespaceCalls import com.personalization.features.cart.CartManagerImpl import com.personalization.features.category.impl.CategoryManagerImpl import com.personalization.features.collection.impl.CollectionManagerImpl @@ -114,11 +116,17 @@ class SdkModule { storiesManager: StoriesManager, setTrackingSourceUseCase: SetTrackingSourceUseCase, sendNetworkMethodUseCase: SendNetworkMethodUseCase, + getUserSettingsValueUseCase: GetUserSettingsValueUseCase, ): TrackingApi = TrackingApiImpl( trackEventManager = trackEventManager, storiesManager = storiesManager, setTrackingSourceUseCase = setTrackingSourceUseCase, checksArguments = { sendNetworkMethodUseCase.queuesEvents }, + events = NamespaceCalls( + core = { sendNetworkMethodUseCase.core }, + dispatchers = { CoreDispatchers.DEFAULT }, + shopId = { getUserSettingsValueUseCase.getShopId().ifEmpty { null } }, + ), ) @Singleton diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/cart/CartApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/cart/CartApiImpl.kt new file mode 100644 index 00000000..f905da8b --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/cart/CartApiImpl.kt @@ -0,0 +1,49 @@ +package com.personalization.features.cart + +import com.personalization.api.managers.CartApi +import com.personalization.api.responses.cart.CartItem +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.objectOrNull +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** [CartApi] over the namespaces' path ([NamespaceCalls]). */ +@OptIn(BridgeApi::class) +internal class CartApiImpl(private val calls: NamespaceCalls) : CartApi { + + override suspend fun get(): List = + calls.request(GET, NetworkMethod.GET(PATH), read = ::readCart) + + override fun get(listener: CompletionListener>) = calls.complete(listener) { get() } + + internal companion object { + const val GET = "cart.get" + const val PATH = "products/cart" + + /** + * The items of a cart answer: `{"data": {"items": [...]}}`, as the server sends it, or + * `{"payload": {"cart_items": [...]}}`, as the API's documentation says it will. An answer without + * a body is an empty cart; any other answer is null (`decoding`). + */ + fun readCart(body: Any?): List? { + if (body == null) return emptyList() + if (body !is JSONObject) return null + val items = body.objectOrNull("data")?.arrayOrNull("items") + ?: body.objectOrNull("payload")?.arrayOrNull("cart_items") + ?: return null + return items.mapObjects(::readItem) + } + + /** An item by its product id (`uniqid`), left out without one; 1 when it has no quantity. */ + private fun readItem(item: JSONObject): CartItem? { + val id = item.nonBlankStringOrNull("uniqid") ?: return null + return CartItem(id = id, quantity = item.intOrNull("quantity") ?: 1) + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/collection/CollectionsApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/collection/CollectionsApiImpl.kt new file mode 100644 index 00000000..afeb11ee --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/collection/CollectionsApiImpl.kt @@ -0,0 +1,36 @@ +package com.personalization.features.collection + +import com.personalization.api.managers.CollectionsApi +import com.personalization.api.models.collections.CollectionResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.pathSegment +import com.personalization.core.internal.requireNotBlank +import com.personalization.features.products.CatalogJson +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** [CollectionsApi] over the namespaces' path ([NamespaceCalls]). */ +@OptIn(BridgeApi::class) +internal class CollectionsApiImpl(private val calls: NamespaceCalls) : CollectionsApi { + + override suspend fun get(collectionId: String): CollectionResponse { + val path = calls.checked(GET) { PATH + pathSegment(requireNotBlank(collectionId, "collectionId")) } + return calls.request(GET, NetworkMethod.GET(path), JSONObject(), read = ::readCollection) + } + + override fun get(collectionId: String, listener: CompletionListener) = + calls.complete(listener) { get(collectionId) } + + internal companion object { + const val GET = "collections.get" + const val PATH = "collection/" + + /** The collection's products; an answer without `products` is null (`decoding`). */ + fun readCollection(body: Any?): CollectionResponse? { + if (body !is JSONObject) return null + return CollectionResponse(products = CatalogJson.products(body) ?: return null) + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/loyalty/LoyaltyApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/loyalty/LoyaltyApiImpl.kt new file mode 100644 index 00000000..6319db85 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/loyalty/LoyaltyApiImpl.kt @@ -0,0 +1,164 @@ +package com.personalization.features.loyalty + +import com.personalization.api.managers.LoyaltyApi +import com.personalization.api.models.loyalty.LoyaltyLevel +import com.personalization.api.models.loyalty.LoyaltyMember +import com.personalization.api.models.loyalty.LoyaltyPromotion +import com.personalization.api.models.loyalty.LoyaltyRewardType +import com.personalization.api.models.loyalty.LoyaltyStatus +import com.personalization.api.models.profile.Gender +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.booleanOrNull +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.isCalendarDate +import com.personalization.core.internal.longOrNull +import com.personalization.core.internal.objectOrNull +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.stringOrNull +import com.personalization.core.internal.valueOfWire +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONArray +import org.json.JSONObject + +/** + * [LoyaltyApi] over the namespaces' path ([NamespaceCalls]). Whether `members/join` and `members/status` + * may be asked without the shop's secret is open (В17, В18 of the contract's questions): the server + * answers them only for a shop that allows the loyalty methods from the front end, `403` otherwise. + */ +@OptIn(BridgeApi::class) +internal class LoyaltyApiImpl(private val calls: NamespaceCalls) : LoyaltyApi { + + override suspend fun join( + phone: String, + firstName: String?, + lastName: String?, + gender: Gender?, + birthday: String?, + ): LoyaltyMember { + val params = calls.checked(JOIN) { + if (phone.isBlank()) invalidArgument("phone is empty") + // A birthday the server cannot read erases the one it has: only a real date goes. + if (birthday != null && !isCalendarDate(birthday)) invalidArgument("birthday must be an existing date YYYY-MM-DD") + JSONObject().put(PHONE, phone) + .putIfNotNull(FIRST_NAME, firstName) + .putIfNotNull(LAST_NAME, lastName) + .putIfNotNull(GENDER, gender?.value) + .putIfNotNull(BIRTHDAY, birthday) + } + return calls.request(JOIN, NetworkMethod.POST(JOIN_PATH), params, read = ::readMember) + } + + override suspend fun getStatus(phone: String): LoyaltyStatus { + val params = calls.checked(GET_STATUS) { + if (phone.isBlank()) invalidArgument("phone is empty") + JSONObject().put(IDENTIFIER, phone) + } + return calls.request(GET_STATUS, NetworkMethod.GET(STATUS_PATH), params, read = ::readStatus) + } + + override suspend fun getPromotions( + locationId: String?, + promoCodes: List?, + chargeBonuses: Boolean?, + currentTime: String?, + ): List { + val params = calls.checked(GET_PROMOTIONS) { + if (currentTime != null && !TIME.matches(currentTime)) invalidArgument("currentTime is not HH:MM") + if (promoCodes?.any { it.isBlank() } == true) invalidArgument("promoCodes has an empty code") + val params = JSONObject() + .putIfNotNull(LOCATION_ID, locationId) + .putIfNotNull(CURRENT_TIME, currentTime) + // Only as a Rails array, `promo_codes[]=A&promo_codes[]=B`: the server drops a string with commas. + if (!promoCodes.isNullOrEmpty()) params.put(PROMO_CODES, JSONArray(promoCodes)) + params.putIfNotNull(CHARGE_BONUSES, chargeBonuses) + } + return calls.request(GET_PROMOTIONS, NetworkMethod.GET(PROMOTIONS_PATH), params, read = ::readPromotions) + } + + override fun join( + phone: String, + firstName: String?, + lastName: String?, + gender: Gender?, + birthday: String?, + listener: CompletionListener, + ) = calls.complete(listener) { join(phone, firstName, lastName, gender, birthday) } + + override fun getStatus(phone: String, listener: CompletionListener) = + calls.complete(listener) { getStatus(phone) } + + override fun getPromotions( + locationId: String?, + promoCodes: List?, + chargeBonuses: Boolean?, + currentTime: String?, + listener: CompletionListener>, + ) = calls.complete(listener) { getPromotions(locationId, promoCodes, chargeBonuses, currentTime) } + + internal companion object { + const val JOIN = "loyalty.join" + const val GET_STATUS = "loyalty.getStatus" + const val GET_PROMOTIONS = "loyalty.getPromotions" + const val JOIN_PATH = "loyalty/members/join" + const val STATUS_PATH = "loyalty/members/status" + const val PROMOTIONS_PATH = "loyalty/promos/for-client" + + private const val PHONE = "phone" + private const val FIRST_NAME = "first_name" + private const val LAST_NAME = "last_name" + private const val GENDER = "gender" + private const val BIRTHDAY = "birthday" + private const val IDENTIFIER = "identifier" + private const val LOCATION_ID = "location_id" + private const val PROMO_CODES = "promo_codes[]" + private const val CHARGE_BONUSES = "charge_bonuses" + private const val CURRENT_TIME = "current_time" + private const val PAYLOAD = "payload" + + private val TIME = Regex("""([01]\d|2[0-3]):[0-5]\d""") + + /** `payload.identifier`; null (`decoding`) without one. */ + fun readMember(body: Any?): LoyaltyMember? { + val identifier = (body as? JSONObject)?.objectOrNull(PAYLOAD)?.nonBlankStringOrNull(IDENTIFIER) ?: return null + return LoyaltyMember(identifier) + } + + /** `payload.member` and `payload.level`; a level whose `code` is null is the base one: no level. */ + fun readStatus(body: Any?): LoyaltyStatus? { + val payload = (body as? JSONObject)?.objectOrNull(PAYLOAD) ?: return null + val member = payload.booleanOrNull("member") ?: return null + val level = payload.objectOrNull("level")?.let { level -> + level.nonBlankStringOrNull("code")?.let { code -> + LoyaltyLevel(code = code, name = level.nonBlankStringOrNull("name"), expirationDate = level.nonBlankStringOrNull("expiration_date")) + } + } + return LoyaltyStatus(isMember = member, level = level) + } + + /** `payload.promotions`; a promotion without a whole `id` is left out. */ + fun readPromotions(body: Any?): List? { + val promotions = (body as? JSONObject)?.objectOrNull(PAYLOAD)?.arrayOrNull("promotions") ?: return null + return promotions.mapObjects(::readPromotion) + } + + private fun readPromotion(promotion: JSONObject): LoyaltyPromotion? { + val id = promotion.longOrNull("id") ?: return null + return LoyaltyPromotion( + id = id, + name = promotion.stringOrNull("name").orEmpty(), + description = promotion.nonBlankStringOrNull("description"), + startDate = promotion.nonBlankStringOrNull("start_date"), + finishDate = promotion.nonBlankStringOrNull("finish_date"), + stream = promotion.nonBlankStringOrNull("stream"), + badgeLabel = promotion.nonBlankStringOrNull("badge_label"), + badgeColor = promotion.nonBlankStringOrNull("badge_color"), + rewardType = valueOfWire(promotion.stringOrNull("reward_type"), LoyaltyRewardType.entries) { it.value }, + ) + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/notifications/NotificationsApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/notifications/NotificationsApiImpl.kt new file mode 100644 index 00000000..bc672324 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/notifications/NotificationsApiImpl.kt @@ -0,0 +1,127 @@ +package com.personalization.features.notifications + +import com.personalization.PushProvider +import com.personalization.SDK +import com.personalization.api.OnApiCallbackListener +import com.personalization.api.managers.NotificationsApi +import com.personalization.core.BridgeApi +import com.personalization.core.BridgeErrors +import com.personalization.core.CompletionListener +import com.personalization.core.PushCallbacks +import com.personalization.core.PushEvent +import com.personalization.core.PushToken +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.internal.CorePushTokens +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.invalidArgument +import kotlinx.coroutines.CompletableDeferred +import org.json.JSONArray +import org.json.JSONObject + +/** + * [NotificationsApi] over the instance's push machinery: its queue for the push events + * ([SDK.trackPushEvent], once per message in a process), its [CorePushTokens] for the token, its push + * callbacks. Each call first passes [NamespaceCalls.checked]: the legacy core refuses it, and an empty code + * or type of a push event is `invalidArgument`. + */ +@OptIn(BridgeApi::class) +internal class NotificationsApiImpl(private val sdk: SDK, private val calls: NamespaceCalls) : NotificationsApi { + + override fun trackDelivered(code: String, type: String, listener: CompletionListener?) = + track(PushEvent.DELIVERED, TRACK_DELIVERED, code, type, listener) + + override fun trackOpened(code: String, type: String, listener: CompletionListener?) = + track(PushEvent.OPENED, TRACK_OPENED, code, type, listener) + + override fun trackClicked(code: String, type: String, listener: CompletionListener?) = + track(PushEvent.CLICKED, TRACK_CLICKED, code, type, listener) + + override fun trackClosed(code: String, type: String, listener: CompletionListener?) = + track(PushEvent.CLOSED, TRACK_CLOSED, code, type, listener) + + override fun getPushToken(provider: PushProvider?): PushToken? { + if (!onNewCore(GET_PUSH_TOKEN)) return null + return tokens()?.known(provider) + } + + override suspend fun setPushToken(token: String, provider: PushProvider) { + calls.checked(SET_PUSH_TOKEN) {} + val tokens = tokens() ?: throw SdkException(SdkError.NotInitialized) + val ended = CompletableDeferred() + // An empty token is refused there, with its log line; one that went this week ends in success, and a + // `2xx` answer `{"status": "error"}` in `decoding`, the week left free. + tokens.set(token, provider, object : OnApiCallbackListener() { + override fun onSuccess(response: JSONObject?) { + ended.complete(null) + } + + override fun onSuccess(response: JSONArray) { + ended.complete(null) + } + + override fun onError(code: Int, msg: String?) { + // The whole error, while it is this thread's. + ended.complete(BridgeErrors.errorOf(code, msg)) + } + }) + ended.await()?.let { throw SdkException(it) } + } + + override fun setPushToken(token: String, provider: PushProvider, listener: CompletionListener) = + calls.complete(listener) { setPushToken(token, provider) } + + override fun setCallbacks(callbacks: PushCallbacks) { + if (onNewCore(SET_CALLBACKS)) sdk.setPushCallbacks(callbacks) + } + + /** + * Hands the push [event] to the instance's queue on the caller's thread, so events keep the order they + * were reported in; [listener] hears how it ended on the main thread. + */ + private fun track(event: PushEvent, call: String, code: String, type: String, listener: CompletionListener?) { + val empty = when { + code.isBlank() -> FIELD_CODE + type.isBlank() -> FIELD_TYPE + else -> null + } + try { + calls.checked(call, reason = empty?.let { "empty_$it" }) { empty?.let { invalidArgument("$it is empty") } } + } catch (e: SdkException) { + calls.tell(listener, SdkResult.Failure(e.error)) + return + } + val ended = CompletableDeferred() + sdk.trackPushEvent(event, code, type) { ended.complete(it) } + listener?.let { calls.complete(it) { ended.await()?.let { error -> throw SdkException(error) } } } + } + + /** Whether [call] may run: the new core; otherwise `notInitialized`, logged on the legacy core. */ + private fun onNewCore(call: String): Boolean = try { + calls.checked(call) {} + true + } catch (e: SdkException) { + false + } + + /** The instance's token rules; set on the new core with its start. */ + private fun tokens(): CorePushTokens? = try { + sdk.pushTokenManager.core + } catch (e: UninitializedPropertyAccessException) { + null + } + + internal companion object { + const val TRACK_DELIVERED = "notifications.trackDelivered" + const val TRACK_OPENED = "notifications.trackOpened" + const val TRACK_CLICKED = "notifications.trackClicked" + const val TRACK_CLOSED = "notifications.trackClosed" + const val GET_PUSH_TOKEN = "notifications.getPushToken" + const val SET_PUSH_TOKEN = "notifications.setPushToken" + const val SET_CALLBACKS = "notifications.setCallbacks" + + private const val FIELD_CODE = "code" + private const val FIELD_TYPE = "type" + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/predict/PredictApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/predict/PredictApiImpl.kt new file mode 100644 index 00000000..88812de9 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/predict/PredictApiImpl.kt @@ -0,0 +1,39 @@ +package com.personalization.features.predict + +import com.personalization.api.managers.PredictApi +import com.personalization.api.models.predict.PurchaseProbability +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.doubleOrNull +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.objectOrNull +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** + * [PredictApi] over the namespaces' path ([NamespaceCalls]), on API v3 of the shop's account + * (`Rees46Config.appDomain`): the API host's `predict/probability-to-purchase` answers `503`, its service + * is no longer deployed there (В42 of the contract's questions). + */ +@OptIn(BridgeApi::class) +internal class PredictApiImpl(private val calls: NamespaceCalls) : PredictApi { + + override suspend fun getProbabilityToPurchase(): PurchaseProbability = + calls.request(GET, NetworkMethod.GET(PATH), read = ::readProbability) + + override fun getProbabilityToPurchase(listener: CompletionListener) = + calls.complete(listener) { getProbabilityToPurchase() } + + internal companion object { + const val GET = "predict.getProbabilityToPurchase" + const val PATH = "api/v3/cdp/users/probability-to-purchase" + + /** `{"status": "success", "payload": {probability, client_id}}`; null (`decoding`) without a numeric `payload.probability`. */ + fun readProbability(body: Any?): PurchaseProbability? { + val payload = (body as? JSONObject)?.objectOrNull("payload") ?: return null + val probability = payload.doubleOrNull("probability") ?: return null + return PurchaseProbability(probability = probability, clientId = payload.nonBlankStringOrNull("client_id")) + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/predict/impl/PredictManagerImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/predict/impl/PredictManagerImpl.kt index db39d1cc..7ed75d2e 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/features/predict/impl/PredictManagerImpl.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/predict/impl/PredictManagerImpl.kt @@ -1,16 +1,21 @@ package com.personalization.features.predict.impl -import com.google.gson.Gson import com.personalization.api.OnApiCallbackListener import com.personalization.api.managers.PredictManager import com.personalization.api.params.PurchasePredictParams import com.personalization.api.responses.predict.PurchasePredictResponse +import com.personalization.core.SdkError +import com.personalization.core.internal.LegacyErrors +import com.personalization.features.predict.PredictApiImpl import com.personalization.sdk.domain.usecases.network.SendNetworkMethodUseCase import org.json.JSONObject import javax.inject.Inject -private const val PROBABILITY_TO_PURCHASE_PATH = "predict/probability-to-purchase" - +/** + * [PredictManager] on the path of `sdk.predict` ([PredictApiImpl.PATH]), on both cores: the API host's + * `predict/probability-to-purchase` answers `503`, its service is no longer deployed there. The answer's + * `payload` becomes the released [PurchasePredictResponse]. + */ internal class PredictManagerImpl @Inject constructor( private val sendNetworkMethodUseCase: SendNetworkMethodUseCase ) : PredictManager { @@ -20,17 +25,19 @@ internal class PredictManagerImpl @Inject constructor( onSuccess: (PurchasePredictResponse) -> Unit, onError: (Int, String?) -> Unit ) { + // The contacts of [params] are not sent: the server reads the device's did first, which every + // request carries, so it never read them. sendNetworkMethodUseCase.getAsync( - PROBABILITY_TO_PURCHASE_PATH, - params.toQueryJson(), + PredictApiImpl.PATH, + JSONObject(), object : OnApiCallbackListener() { override fun onSuccess(response: JSONObject?) { - if (response == null) { - onError(-1, null) + val probability = PredictApiImpl.readProbability(response) + if (probability == null) { + onError(LegacyErrors.NO_ANSWER, SdkError.Decoding.message) return } - val parsed = Gson().fromJson(response.toString(), PurchasePredictResponse::class.java) - onSuccess(parsed) + onSuccess(PurchasePredictResponse(probability = probability.probability, clientId = probability.clientId.orEmpty())) } override fun onError(code: Int, msg: String?) { diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/products/CatalogJson.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/products/CatalogJson.kt new file mode 100644 index 00000000..7d8e7e22 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/products/CatalogJson.kt @@ -0,0 +1,262 @@ +package com.personalization.features.products + +import com.personalization.api.models.products.PriceInterval +import com.personalization.api.models.products.Product +import com.personalization.api.models.products.ProductCategory +import com.personalization.api.models.products.SearchFilter +import com.personalization.api.models.products.SortBy +import com.personalization.api.models.products.SortDirection +import com.personalization.api.responses.products.product.ProductParam +import com.personalization.api.responses.search.Brand +import com.personalization.api.responses.search.ColorFilter +import com.personalization.api.responses.search.IndustrialFilters +import com.personalization.api.responses.search.Location +import com.personalization.api.responses.search.PopularItem +import com.personalization.api.responses.search.PriceRange +import com.personalization.api.responses.search.SizeFilter +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.booleanOrNull +import com.personalization.core.internal.doubleOrNull +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.objectOrNull +import com.personalization.core.internal.putFilters +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.putList +import com.personalization.core.internal.putNumber +import com.personalization.core.internal.requireAtLeast +import com.personalization.core.internal.requirePriceRange +import com.personalization.core.internal.strings +import com.personalization.core.internal.stringOrNull +import com.personalization.core.internal.valueOrNull +import org.json.JSONArray +import org.json.JSONObject + +/** + * Reading the catalog's answers into the models of `products`, `collections`, `recommendations` and + * `search` (`contract/products.md`), tolerantly: a number may come as a string, a field missing or of the + * wrong kind is null, a product's optional text that is empty is null too, and an element of a list that + * lacks what its model cannot do without is left out. + */ +internal object CatalogJson { + + /** + * A product; null without one of the fields every product has: an id, `name`, `url`, `price` and + * `currency`. [uniqidFirst] reads the id from `uniqid` before `id`, as the product card needs. + */ + fun product(json: JSONObject, uniqidFirst: Boolean = false): Product? { + val id = (if (uniqidFirst) json.nonBlankStringOrNull("uniqid") else null) + ?: json.nonBlankStringOrNull("id") + ?: return null + return Product( + id = id, + groupId = json.nonBlankStringOrNull("group_id"), + name = json.stringOrNull("name") ?: return null, + brand = json.textOrNull("brand"), + model = json.textOrNull("model"), + description = json.textOrNull("description"), + barcode = json.textOrNull("barcode"), + url = json.stringOrNull("url") ?: return null, + deeplinkAndroid = json.textOrNull("deeplink_android"), + deeplinkIos = json.textOrNull("deeplink_ios"), + imageUrl = json.textOrNull("image_url"), + picture = json.textOrNull("picture"), + resizedImages = json.mapOrNull("image_url_resized")?.let(::stringMap), + price = json.doubleOrNull("price") ?: return null, + priceFormatted = json.textOrNull("price_formatted"), + priceFull = json.doubleOrNull("price_full"), + priceFullFormatted = json.textOrNull("price_full_formatted"), + // The server sends 0 for a product without an old price. + oldPrice = json.doubleOrNull("oldprice")?.takeIf { it != 0.0 }, + oldPriceFormatted = json.textOrNull("oldprice_formatted"), + oldPriceFull = json.doubleOrNull("oldprice_full")?.takeIf { it != 0.0 }, + oldPriceFullFormatted = json.textOrNull("oldprice_full_formatted"), + currency = json.stringOrNull("currency") ?: return null, + // `discount` is a flag in the product card (never a number) and the percent elsewhere. + discountPercent = json.intOrNull("discount_percent") ?: json.intOrNull("discount"), + discountFormatted = json.textOrNull("discount_formatted"), + salesRate = json.intOrNull("sales_rate"), + relativeSalesRate = json.doubleOrNull("relative_sales_rate"), + rating = json.intOrNull("rating"), + isNew = json.booleanOrNull("is_new") ?: false, + stockQuantity = json.intOrNull("stock_quantity"), + categoryIds = json.arrayOrNull("category_ids")?.strings(), + categories = json.arrayOrNull("categories")?.mapObjects(::category), + params = params(json), + locationIds = json.arrayOrNull("location_ids")?.strings(), + ) + } + + /** [key] as a string; null for an empty one as for a missing one: a product's optional text has a value or none. */ + private fun JSONObject.textOrNull(key: String): String? = stringOrNull(key)?.takeIf { it.isNotEmpty() } + + /** The products of [key]; an element that is not a whole product is left out. Null without the list. */ + fun products(json: JSONObject, key: String = "products"): List? = + json.arrayOrNull(key)?.mapObjects { product(it) } + + /** A category of a product (`parent_id`, `level`) or of the facets (`parent`, `count`, `alias`); null without an id. */ + fun category(json: JSONObject): ProductCategory? { + val id = json.nonBlankStringOrNull("id") ?: return null + return ProductCategory( + id = id, + name = json.stringOrNull("name"), + url = json.stringOrNull("url"), + parentId = json.nonBlankStringOrNull("parent_id") ?: json.nonBlankStringOrNull("parent"), + level = json.intOrNull("level"), + count = json.intOrNull("count"), + alias = json.stringOrNull("alias"), + ) + } + + /** + * A product's parameters. The lists of products send them as `[{"key", "values"}]`; the product card + * (`products/get`) as an object of the parameter's name → `{"value": [...], "searchable"}`, in the + * catalog's order. Null without `params`. + */ + private fun params(json: JSONObject): List? = when (val params = json.valueOrNull("params")) { + is JSONArray -> params.mapObjects(::param) + is JSONObject -> params.keys().asSequence().mapNotNull { key -> + if (key.isBlank()) return@mapNotNull null + val values = when (val param = params.valueOrNull(key)) { + is JSONObject -> param.valuesOf("value") ?: param.valuesOf("values") + else -> params.valuesOf(key) + } + ProductParam(key = key, values = values.orEmpty()) + }.toList() + else -> null + } + + /** A product's parameter; its values as strings, numbers among them. Null without a key. */ + private fun param(json: JSONObject): ProductParam? { + val key = json.nonBlankStringOrNull("key") ?: return null + return ProductParam(key = key, values = json.valuesOf("values").orEmpty()) + } + + /** The values of [key]: a list's strings and numbers as strings, or one value as a list of it; null without them. */ + private fun JSONObject.valuesOf(key: String): List? = + arrayOrNull(key)?.strings() ?: stringOrNull(key)?.let(::listOf) + + fun categories(json: JSONObject): List? = json.arrayOrNull("categories")?.mapObjects(::category) + + /** The brands with their counts; a brand without a name or a count is left out. */ + fun brands(json: JSONObject): List? = json.arrayOrNull("brands")?.mapObjects { brand -> + Brand(count = brand.intOrNull("count") ?: return@mapObjects null, name = brand.stringOrNull("name") ?: return@mapObjects null) + } + + /** The locations; one without an id or a name is left out. */ + fun locations(json: JSONObject): List? = json.arrayOrNull("locations")?.mapObjects { location -> + Location( + id = location.nonBlankStringOrNull("id") ?: return@mapObjects null, + name = location.stringOrNull("name") ?: return@mapObjects null, + type = location.stringOrNull("type"), + ) + } + + /** The facets of the products' parameters: a parameter's name → its facet. */ + fun filters(json: JSONObject): Map? = json.mapOrNull("filters")?.let { filters -> + filters.keys().asSequence().mapNotNull { name -> + filters.objectOrNull(name)?.let { name to searchFilter(it) } + }.toMap() + } + + private fun searchFilter(json: JSONObject): SearchFilter { + val ranges = json.objectOrNull("ranges") + return SearchFilter( + count = json.intOrNull("count"), + priority = json.intOrNull("priority"), + values = json.mapOrNull("values")?.let { values -> + values.keys().asSequence().mapNotNull { value -> values.intOrNull(value)?.let { value to it } }.toMap() + }, + min = ranges?.doubleOrNull("min"), + max = ranges?.doubleOrNull("max"), + ) + } + + /** Colours and sizes with their counts; an element without its value or count is left out. */ + fun industrialFilters(json: JSONObject): IndustrialFilters? = json.objectOrNull("industrial_filters")?.let { filters -> + IndustrialFilters( + colors = filters.arrayOrNull("colors")?.mapObjects { color -> + ColorFilter( + color = color.stringOrNull("color") ?: return@mapObjects null, + count = color.intOrNull("count") ?: return@mapObjects null, + ) + }, + fashionSizes = filters.arrayOrNull("fashion_sizes")?.mapObjects { size -> + SizeFilter( + size = size.stringOrNull("size") ?: return@mapObjects null, + count = size.intOrNull("count") ?: return@mapObjects null, + ) + }, + ) + } + + /** The lowest and the highest price; null unless both are there. */ + fun priceRange(json: JSONObject): PriceRange? { + val range = json.objectOrNull("price_range") ?: return null + return PriceRange(max = range.doubleOrNull("max") ?: return null, min = range.doubleOrNull("min") ?: return null) + } + + fun priceRanges(json: JSONObject): List? = json.arrayOrNull("price_ranges")?.mapObjects { interval -> + PriceInterval( + from = interval.doubleOrNull("from") ?: 0.0, + to = interval.doubleOrNull("to"), + count = interval.intOrNull("count"), + ) + } + + /** Popular categories, brands or links; one without a name or a link is left out. */ + fun popularItems(json: JSONObject, key: String): List? = json.arrayOrNull(key)?.mapObjects { item -> + PopularItem(name = item.stringOrNull("name") ?: return@mapObjects null, url = item.stringOrNull("url") ?: return@mapObjects null) + } + + /** + * The request's fields of a listing (`/products`), for `getList` and `getCategory`, after their checks: + * [SortBy.RELEVANCE] is only for a search. + */ + fun listingParams( + categoryIds: List?, + brands: List?, + merchants: List?, + locations: List?, + priceMin: Double?, + priceMax: Double?, + filters: Map>?, + sortBy: SortBy?, + sortDir: SortDirection?, + limit: Int?, + page: Int?, + ): JSONObject { + requirePriceRange(priceMin, priceMax) + requireAtLeast(limit, 1, "limit") + requireAtLeast(page, 1, "page") + if (sortBy == SortBy.RELEVANCE) invalidArgument("sortBy relevance is only for search.full") + return JSONObject() + .putList("categories", categoryIds) + .putList("brands", brands) + .putList("merchants", merchants) + .putList("locations", locations) + .putNumber("price_min", priceMin) + .putNumber("price_max", priceMax) + .putFilters("filters", filters) + .putIfNotNull("sort_by", sortBy?.value) + .putIfNotNull("sort_dir", sortDir?.value) + .putIfNotNull("limit", limit) + .putIfNotNull("page", page) + } + + /** The values of an object as strings; a value of another kind is left out. */ + private fun stringMap(json: JSONObject): Map = + json.keys().asSequence().mapNotNull { key -> json.stringOrNull(key)?.let { key to it } }.toMap() + + /** + * [key] as an object; an empty array, which the server sends for an empty object, is an empty one. + * Null when missing or of another kind. + */ + private fun JSONObject.mapOrNull(key: String): JSONObject? = when (val value = valueOrNull(key)) { + is JSONObject -> value + is JSONArray -> JSONObject().takeIf { value.length() == 0 } + else -> null + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/products/ProductsApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/products/ProductsApiImpl.kt new file mode 100644 index 00000000..6f668097 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/products/ProductsApiImpl.kt @@ -0,0 +1,144 @@ +package com.personalization.features.products + +import com.personalization.api.managers.ProductsApi +import com.personalization.api.models.products.CategoryRequest +import com.personalization.api.models.products.CategoryResponse +import com.personalization.api.models.products.Product +import com.personalization.api.models.products.ProductsListRequest +import com.personalization.api.models.products.ProductsListResponse +import com.personalization.api.responses.products.counters.ProductCounter +import com.personalization.api.responses.products.counters.ProductCounterTriggers +import com.personalization.api.responses.products.counters.ProductCountersResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.doubleOrNull +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.objectOrNull +import com.personalization.core.internal.requireNotBlank +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** [ProductsApi] over the namespaces' path ([NamespaceCalls]). */ +@OptIn(BridgeApi::class) +internal class ProductsApiImpl(private val calls: NamespaceCalls) : ProductsApi { + + override suspend fun getInfo(itemId: String): Product? { + val params = calls.checked(GET_INFO) { JSONObject().put("item_id", requireNotBlank(itemId, "itemId")) } + return calls.request(GET_INFO, NetworkMethod.GET(INFO_PATH), params, read = ::readInfo).product + } + + override suspend fun getList(request: ProductsListRequest): ProductsListResponse { + val params = calls.checked(GET_LIST) { + with(request) { + CatalogJson.listingParams(categoryIds, brands, merchants, locations, priceMin, priceMax, filters, sortBy, sortDir, limit, page) + } + } + return calls.request(GET_LIST, NetworkMethod.GET(LIST_PATH), params, read = ::readList) + } + + override suspend fun getCounters(itemId: String): ProductCountersResponse { + val params = calls.checked(GET_COUNTERS) { JSONObject().put("item", requireNotBlank(itemId, "itemId")) } + return calls.request(GET_COUNTERS, NetworkMethod.GET(COUNTERS_PATH), params, read = ::readCounters) + } + + /** A delegate of [getList] with the category: the server's `/category/{id}` is the same listing. */ + override suspend fun getCategory(categoryId: String, request: CategoryRequest): CategoryResponse { + val params = calls.checked(GET_CATEGORY) { + val category = listOf(requireNotBlank(categoryId, "categoryId")) + with(request) { + CatalogJson.listingParams(category, brands, null, locations, priceMin, priceMax, filters, sortBy, sortDir, limit, page) + } + } + return calls.request(GET_CATEGORY, NetworkMethod.GET(LIST_PATH), params, read = ::readCategory) + } + + override fun getInfo(itemId: String, listener: CompletionListener) = calls.complete(listener) { getInfo(itemId) } + + override fun getList(request: ProductsListRequest, listener: CompletionListener) = + calls.complete(listener) { getList(request) } + + override fun getCounters(itemId: String, listener: CompletionListener) = + calls.complete(listener) { getCounters(itemId) } + + override fun getCategory(categoryId: String, request: CategoryRequest, listener: CompletionListener) = + calls.complete(listener) { getCategory(categoryId, request) } + + /** A product card, or none: the path's result must not be null, so it carries the card. */ + internal class Card(val product: Product?) + + internal companion object { + const val GET_INFO = "products.getInfo" + const val GET_LIST = "products.getList" + const val GET_COUNTERS = "products.getCounters" + const val GET_CATEGORY = "products.getCategory" + const val INFO_PATH = "products/get" + const val LIST_PATH = "products" + const val COUNTERS_PATH = "products/counters" + + /** + * The product card: the id from `uniqid`, then `id`. An empty answer (`{}`, the server's answer for a + * product it does not have) is no product; an answer without an id, or without another field every + * product has, is null (`decoding`). + */ + fun readInfo(body: Any?): Card? { + if (body == null) return Card(null) + if (body !is JSONObject) return null + if (body.length() == 0) return Card(null) + return CatalogJson.product(body, uniqidFirst = true)?.let(::Card) + } + + /** A page of the listing; an answer without `products` is null (`decoding`). */ + fun readList(body: Any?): ProductsListResponse? { + if (body !is JSONObject) return null + return ProductsListResponse( + productsTotal = body.intOrNull("products_total"), + products = CatalogJson.products(body) ?: return null, + categories = CatalogJson.categories(body), + brands = CatalogJson.brands(body), + locations = CatalogJson.locations(body), + filters = CatalogJson.filters(body), + industrialFilters = CatalogJson.industrialFilters(body), + priceRange = CatalogJson.priceRange(body), + priceRanges = CatalogJson.priceRanges(body), + priceMedian = body.doubleOrNull("price_median"), + ) + } + + /** A category's screen: the listing's answer without the fields a category has not; `products` as in [readList]. */ + fun readCategory(body: Any?): CategoryResponse? { + if (body !is JSONObject) return null + return CategoryResponse( + productsTotal = body.intOrNull("products_total"), + products = CatalogJson.products(body) ?: return null, + categories = CatalogJson.categories(body), + brands = CatalogJson.brands(body), + filters = CatalogJson.filters(body), + priceRange = CatalogJson.priceRange(body), + priceRanges = CatalogJson.priceRanges(body), + priceMedian = body.doubleOrNull("price_median"), + ) + } + + /** The counters; a counter the answer leaves out is 0, as the model has it. Null for an answer that is not an object. */ + fun readCounters(body: Any?): ProductCountersResponse? { + if (body !is JSONObject) return null + return ProductCountersResponse( + daily = body.objectOrNull("daily")?.let(::counter), + now = body.objectOrNull("now")?.let(::counter), + triggers = body.objectOrNull("triggers")?.let { triggers -> + ProductCounterTriggers( + backInStock = triggers.intOrNull("back_in_stock") ?: 0, + priceDrop = triggers.intOrNull("price_drop") ?: 0, + ) + }, + ) + } + + private fun counter(json: JSONObject) = ProductCounter( + view = json.intOrNull("view") ?: 0, + cart = json.intOrNull("cart") ?: 0, + purchase = json.intOrNull("purchase") ?: 0, + ) + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/profile/ProfileApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/profile/ProfileApiImpl.kt new file mode 100644 index 00000000..37721210 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/profile/ProfileApiImpl.kt @@ -0,0 +1,165 @@ +package com.personalization.features.profile + +import com.personalization.api.managers.ProfileApi +import com.personalization.api.models.products.Product +import com.personalization.api.models.profile.Gender +import com.personalization.api.models.profile.Profile +import com.personalization.api.models.profile.ProfileUpdateRequest +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.booleanOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.requireAtLeast +import com.personalization.core.internal.requireBirthday +import com.personalization.core.internal.requireContact +import com.personalization.core.internal.stringOrNull +import com.personalization.core.internal.valueOfWire +import com.personalization.core.internal.valueOrNull +import com.personalization.features.products.CatalogJson +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONArray +import org.json.JSONObject + +/** + * [ProfileApi] over the namespaces' path ([NamespaceCalls]). [contextChanged] tells popups v3 that the + * profile changed, once the server took it, so their list is asked for again. + */ +@OptIn(BridgeApi::class) +internal class ProfileApiImpl( + private val calls: NamespaceCalls, + private val contextChanged: (type: String, signature: String) -> Unit = { _, _ -> }, +) : ProfileApi { + + override suspend fun get(): Profile = calls.request(GET, NetworkMethod.GET(GET_PATH), read = ::readProfile) + + override suspend fun set(request: ProfileUpdateRequest) { + val params = calls.checked(SET) { setParams(request) } + val signature = params.toString() + calls.request(SET, NetworkMethod.POST(SET_PATH), params) { Unit } + contextChanged(SET_PATH, signature) + } + + override suspend fun getLastOrder(): List = + calls.request(GET_LAST_ORDER, NetworkMethod.GET(LAST_ORDER_PATH), read = ::readLastOrder) + + override fun get(listener: CompletionListener) = calls.complete(listener) { get() } + + override fun set(request: ProfileUpdateRequest, listener: CompletionListener) = calls.complete(listener) { set(request) } + + override fun getLastOrder(listener: CompletionListener>) = calls.complete(listener) { getLastOrder() } + + internal companion object { + const val GET = "profile.get" + const val SET = "profile.set" + const val GET_LAST_ORDER = "profile.getLastOrder" + const val GET_PATH = "profile" + const val SET_PATH = "profile/set" + const val LAST_ORDER_PATH = "orders/last_for_user" + + private val CUSTOM_KEY = Regex("[a-z0-9_]+") + + /** The fields of the request itself and those the SDK adds: a custom property may not take their names. */ + private val RESERVED_KEYS = setOf( + "email", "phone", "id", "external_id", "loyalty_id", "telegram_id", "fb_id", "vk_id", "first_name", + "last_name", "gender", "birthday", "age", "location", "kids", "auto", + "shop_id", "did", "sid", "seance", "segment", "stream", + ) + + /** + * The request's fields after their checks ([ProfileUpdateRequest]). An empty [ProfileUpdateRequest.externalId], + * [ProfileUpdateRequest.telegramId] or [ProfileUpdateRequest.birthday] goes as `""`: the server erases + * them so. It does not erase `email`, `phone` or `loyalty_id` so: an empty one is refused. Any other + * string goes as it is. + */ + fun setParams(request: ProfileUpdateRequest): JSONObject = with(request) { + requireContact(email, "email") + requireContact(phone, "phone") + requireContact(loyaltyId, "loyaltyId") + birthday?.takeIf { it.isNotEmpty() }?.let { requireBirthday(it, "birthday") } + requireAtLeast(age, 0, "age") + kids?.forEach { kid -> kid.birthday?.let { requireBirthday(it, "a kid's birthday") } } + val params = JSONObject() + .putIfNotNull("email", email) + .putIfNotNull("phone", phone) + // Both servers look the customer up by `id` and keep `external_id` in the profile. + .putIfNotNull("id", externalId) + .putIfNotNull("external_id", externalId) + .putIfNotNull("loyalty_id", loyaltyId) + .putIfNotNull("telegram_id", telegramId) + .putIfNotNull("fb_id", fbId) + .putIfNotNull("vk_id", vkId) + .putIfNotNull("first_name", firstName) + .putIfNotNull("last_name", lastName) + .putIfNotNull("gender", gender?.value) + .putIfNotNull("birthday", birthday) + .putIfNotNull("age", age) + .putIfNotNull("location", location) + .putIfNotNull("kids", kids?.takeIf { it.isNotEmpty() }?.let { list -> + JSONArray(list.map { JSONObject().putIfNotNull("gender", it.gender?.value).putIfNotNull("birthday", it.birthday) }) + }) + .putIfNotNull("auto", cars?.takeIf { it.isNotEmpty() }?.let { list -> + JSONArray(list.map { JSONObject().putIfNotNull("brand", it.brand).putIfNotNull("model", it.model).putIfNotNull("vds", it.vds) }) + }) + customProperties?.forEach { (key, value) -> + if (!CUSTOM_KEY.matches(key)) invalidArgument("customProperties: the key $key is not of a-z, 0-9 and _") + if (key in RESERVED_KEYS) invalidArgument("customProperties: the key $key is a field of the request") + params.put(key, customValue(value) ?: invalidArgument("customProperties: the value of $key is of a kind the API does not take")) + } + if (params.length() == 0) invalidArgument("The request sets nothing") + params + } + + /** [value] as JSON: a string, a finite number, a boolean, null, or a list or a map of these; null for anything else. */ + private fun customValue(value: Any?): Any? = when (value) { + null -> JSONObject.NULL + is String, is Boolean -> value + is Int, is Long, is Short, is Byte -> value + is Number -> value.toDouble().takeIf { it.isFinite() } + is List<*> -> JSONArray().apply { value.forEach { put(customValue(it) ?: return null) } } + is Map<*, *> -> JSONObject().apply { + value.forEach { (key, item) -> put(key as? String ?: return null, customValue(item) ?: return null) } + } + else -> null + } + + /** The profile; an answer that is not an object is null (`decoding`). */ + fun readProfile(body: Any?): Profile? { + if (body !is JSONObject) return null + return Profile( + id = body.nonBlankStringOrNull("id"), + hasEmail = body.booleanOrNull("has_email"), + emailRegisteredAt = body.stringOrNull("email_registered_at"), + gender = gender(body.stringOrNull("gender")), + computedGender = gender(body.stringOrNull("computed_gender")), + boughtSomething = body.booleanOrNull("bought_something"), + customProperties = when (val properties = body.valueOrNull("custom_properties")) { + is JSONObject -> properties.keys().asSequence().associateWith { plain(properties.opt(it)) } + // The server sends an empty object as an empty array. + is JSONArray -> if (properties.length() == 0) emptyMap() else null + else -> null + }, + ) + } + + /** The products of the last order: an array of products; an answer without a body is no order. */ + fun readLastOrder(body: Any?): List? = when (body) { + null -> emptyList() + is JSONArray -> body.mapObjects { CatalogJson.product(it) } + else -> null + } + + private fun gender(value: String?): Gender? = valueOfWire(value, Gender.entries) { it.value } + + /** A JSON value as plain Kotlin: maps, lists, strings, numbers, booleans and null. */ + private fun plain(value: Any?): Any? = when (value) { + null, JSONObject.NULL -> null + is JSONObject -> value.keys().asSequence().associateWith { plain(value.opt(it)) } + is JSONArray -> List(value.length()) { plain(value.opt(it)) } + else -> value + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/recommendation/RecommendationsApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/recommendation/RecommendationsApiImpl.kt new file mode 100644 index 00000000..c408e824 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/recommendation/RecommendationsApiImpl.kt @@ -0,0 +1,81 @@ +package com.personalization.features.recommendation + +import com.personalization.api.managers.RecommendationsApi +import com.personalization.api.models.recommendations.RecommendationRequest +import com.personalization.api.models.recommendations.RecommendationResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.pathSegment +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.putList +import com.personalization.core.internal.requireAtLeast +import com.personalization.core.internal.requireNotBlank +import com.personalization.core.internal.stringOrNull +import com.personalization.core.internal.strings +import com.personalization.features.products.CatalogJson +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** [RecommendationsApi] over the namespaces' path ([NamespaceCalls]). */ +@OptIn(BridgeApi::class) +internal class RecommendationsApiImpl(private val calls: NamespaceCalls) : RecommendationsApi { + + override suspend fun get(code: String, request: RecommendationRequest): RecommendationResponse { + val (path, params) = calls.checked(GET) { PATH + pathSegment(requireNotBlank(code, "code")) to params(request) } + return calls.request(GET, NetworkMethod.GET(path), params, read = ::readRecommendations) + } + + override fun get(code: String, request: RecommendationRequest, listener: CompletionListener) = + calls.complete(listener) { get(code, request) } + + internal companion object { + const val GET = "recommendations.get" + const val PATH = "recommend/" + + /** The request's fields: `extended` and `with_locations` go only when true. */ + private fun params(request: RecommendationRequest): JSONObject = with(request) { + requireAtLeast(limit, 1, "limit") + if (withLocations && !extended) invalidArgument("withLocations needs extended") + JSONObject() + .putIfNotNull("item_id", itemId) + .putIfNotNull("category", categoryId) + .putIfNotNull("search_query", searchQuery) + .putList("exclude", excludedItemIds) + .putList("brands", brands) + .putList("locations", locations) + .putIfNotNull("limit", limit) + .putIfNotNull("extended", "true".takeIf { extended }) + .putIfNotNull("with_locations", "true".takeIf { withLocations }) + } + + /** + * The block's products. `recommends` holds whole products (`extended`) or their ids; [itemIds] is + * filled either way. A block on pause answers `{"state": "paused"}` without `recommends`: no + * products. Any other answer without `recommends` is null (`decoding`). + */ + fun readRecommendations(body: Any?): RecommendationResponse? { + if (body !is JSONObject) return null + val recommends = body.arrayOrNull(RECOMMENDS) + if (recommends == null && body.stringOrNull("state") != PAUSED) return null + // Whole products, or their ids alone (strings, or numbers from an older server). + val products = recommends?.mapObjects { CatalogJson.product(it) }.orEmpty() + val itemIds = products.map { it.id }.ifEmpty { recommends?.strings()?.filter { it.isNotBlank() }.orEmpty() } + return RecommendationResponse( + id = body.intOrNull("id"), + title = body.nonBlankStringOrNull("title"), + link = body.nonBlankStringOrNull("link"), + products = products, + itemIds = itemIds, + ) + } + + private const val RECOMMENDS = "recommends" + private const val PAUSED = "paused" + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/reviews/ReviewsApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/reviews/ReviewsApiImpl.kt new file mode 100644 index 00000000..0ede212c --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/reviews/ReviewsApiImpl.kt @@ -0,0 +1,286 @@ +package com.personalization.features.reviews + +import com.personalization.api.managers.ReviewsApi +import com.personalization.api.responses.reviews.CesCampaign +import com.personalization.api.responses.reviews.ClientReview +import com.personalization.api.responses.reviews.CsatCampaign +import com.personalization.api.responses.reviews.NpsCategory +import com.personalization.api.responses.reviews.PollChannel +import com.personalization.api.responses.reviews.PollReview +import com.personalization.api.responses.reviews.ProductRatingSummary +import com.personalization.api.responses.reviews.ProductReview +import com.personalization.api.responses.reviews.ProductReviewsResponse +import com.personalization.api.responses.reviews.ReviewState +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.doubleOrNull +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.longOrNull +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.objectOrNull +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.requireNotBlank +import com.personalization.core.internal.valueOfWire +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** + * [ReviewsApi] over the namespaces' path ([NamespaceCalls]). The polls' paths are under `api/v3/`, which + * the core sends to the host of API v3 (`Rees46Config.appDomain`); the reviews of products go to the API's. + */ +@OptIn(BridgeApi::class) +internal class ReviewsApiImpl(private val calls: NamespaceCalls) : ReviewsApi { + + override suspend fun createNps( + rate: Int, channel: String, category: String, orderId: String?, comment: String?, label: String?, + ): PollReview = create(CREATE_NPS, NPS_REVIEWS, rate, NPS_RATES, channel, CATEGORY, category, orderId, comment, label) + + override suspend fun createCsat( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String?, + ): PollReview = create(CREATE_CSAT, CSAT_REVIEWS, rate, CSAT_RATES, channel, CAMPAIGN, campaign, orderId, comment, label) + + override suspend fun createCes( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String?, + ): PollReview = create(CREATE_CES, CES_REVIEWS, rate, CES_RATES, channel, CAMPAIGN, campaign, orderId, comment, label) + + override suspend fun getNpsCategories(): List = + calls.request(GET_NPS_CATEGORIES, NetworkMethod.GET(NPS_CATEGORIES), read = listAt("categories", ::readNpsCategory)) + + override suspend fun getNpsChannels(): List = + calls.request(GET_NPS_CHANNELS, NetworkMethod.GET(NPS_CHANNELS), read = listAt("channels", ::readChannel)) + + override suspend fun getCsatCampaigns(): List = + calls.request(GET_CSAT_CAMPAIGNS, NetworkMethod.GET(CSAT_CAMPAIGNS), read = listAt("campaigns", ::readCsatCampaign)) + + override suspend fun getCesCampaigns(): List = + calls.request(GET_CES_CAMPAIGNS, NetworkMethod.GET(CES_CAMPAIGNS), read = listAt("campaigns", ::readCesCampaign)) + + override suspend fun getProductReviews(itemId: String, limit: Int?, offset: Int?): ProductReviewsResponse { + val params = calls.checked(GET_PRODUCT_REVIEWS) { + requireNotBlank(itemId, "itemId") + if (limit != null && limit !in LIMITS) invalidArgument("limit must be from ${LIMITS.first} to ${LIMITS.last}") + if (offset != null && offset < 0) invalidArgument("offset must not be negative") + JSONObject().put("product", itemId).putIfNotNull("limit", limit).putIfNotNull("offset", offset) + } + return calls.request(GET_PRODUCT_REVIEWS, NetworkMethod.GET(PRODUCT_REVIEWS), params, read = ::readProductReviews) + } + + override suspend fun getClientReviews(orderId: String): List { + val params = calls.checked(GET_CLIENT_REVIEWS) { JSONObject().put("order", requireNotBlank(orderId, "orderId")) } + return calls.request(GET_CLIENT_REVIEWS, NetworkMethod.GET(CLIENT_REVIEWS), params, read = listAt("reviews", ::readClientReview)) + } + + override fun createNps( + rate: Int, channel: String, category: String, orderId: String?, comment: String?, label: String?, + listener: CompletionListener, + ) = calls.complete(listener) { createNps(rate, channel, category, orderId, comment, label) } + + override fun createCsat( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String?, + listener: CompletionListener, + ) = calls.complete(listener) { createCsat(rate, channel, campaign, orderId, comment, label) } + + override fun createCes( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String?, + listener: CompletionListener, + ) = calls.complete(listener) { createCes(rate, channel, campaign, orderId, comment, label) } + + override fun getNpsCategories(listener: CompletionListener>) = calls.complete(listener) { getNpsCategories() } + + override fun getNpsChannels(listener: CompletionListener>) = calls.complete(listener) { getNpsChannels() } + + override fun getCsatCampaigns(listener: CompletionListener>) = calls.complete(listener) { getCsatCampaigns() } + + override fun getCesCampaigns(listener: CompletionListener>) = calls.complete(listener) { getCesCampaigns() } + + override fun getProductReviews(itemId: String, limit: Int?, offset: Int?, listener: CompletionListener) = + calls.complete(listener) { getProductReviews(itemId, limit, offset) } + + override fun getClientReviews(orderId: String, listener: CompletionListener>) = + calls.complete(listener) { getClientReviews(orderId) } + + /** + * One rating: [rate] on the scale [rates], what is rated as [subject] (`category` or `campaign`) with the + * code [code]. An empty or blank [orderId], [comment] or [label] is not sent; an empty channel or code is + * refused. + */ + private suspend fun create( + call: String, path: String, rate: Int, rates: IntRange, channel: String, subject: String, code: String, + orderId: String?, comment: String?, label: String?, + ): PollReview { + val params = calls.checked(call) { + if (rate !in rates) invalidArgument("rate must be from ${rates.first} to ${rates.last}") + JSONObject().put("rate", rate).put("channel", requireNotBlank(channel, "channel")).put(subject, requireNotBlank(code, subject)) + } + listOf("order_id" to orderId, "comment" to comment, "label" to label).forEach { (key, value) -> + if (!value.isNullOrBlank()) params.put(key, value) + } + return calls.request(call, NetworkMethod.POST(path), params, read = ::readPollReview) + } + + internal companion object { + const val CREATE_NPS = "reviews.createNps" + const val CREATE_CSAT = "reviews.createCsat" + const val CREATE_CES = "reviews.createCes" + const val GET_NPS_CATEGORIES = "reviews.getNpsCategories" + const val GET_NPS_CHANNELS = "reviews.getNpsChannels" + const val GET_CSAT_CAMPAIGNS = "reviews.getCsatCampaigns" + const val GET_CES_CAMPAIGNS = "reviews.getCesCampaigns" + const val GET_PRODUCT_REVIEWS = "reviews.getProductReviews" + const val GET_CLIENT_REVIEWS = "reviews.getClientReviews" + + const val NPS_REVIEWS = "api/v3/polls/nps/reviews" + const val CSAT_REVIEWS = "api/v3/polls/csat/reviews" + const val CES_REVIEWS = "api/v3/polls/ces/reviews" + const val NPS_CATEGORIES = "api/v3/polls/nps/categories" + const val NPS_CHANNELS = "api/v3/polls/nps/channels" + const val CSAT_CAMPAIGNS = "api/v3/polls/csat/campaigns" + const val CES_CAMPAIGNS = "api/v3/polls/ces/campaigns" + const val PRODUCT_REVIEWS = "reviews/product" + const val CLIENT_REVIEWS = "reviews/client" + + private const val CATEGORY = "category" + private const val CAMPAIGN = "campaign" + private val NPS_RATES = 0..10 + private val CSAT_RATES = 1..5 + private val CES_RATES = 1..7 + private val LIMITS = 1..100 + + /** The review a rating saved or updated: `payload.review.id`; null (`decoding`) without it. */ + fun readPollReview(body: Any?): PollReview? { + val id = (body as? JSONObject)?.objectOrNull("payload")?.objectOrNull("review")?.longOrNull("id") ?: return null + return PollReview(id) + } + + /** + * A reader of a list answer, `{"payload": {"": [...]}}`, its elements read with [element]: one it + * turns down is left out. An answer without a body is an empty list; one without the list is null + * (`decoding`). + */ + fun listAt(key: String, element: (JSONObject) -> T?): (Any?) -> List? = { body -> + when (body) { + null -> emptyList() + is JSONObject -> body.objectOrNull("payload")?.arrayOrNull(key)?.mapObjects(element) + else -> null + } + } + + /** A category by its code and name, left out without one of them. */ + fun readNpsCategory(json: JSONObject): NpsCategory? { + val code = json.nonBlankStringOrNull("code") ?: return null + val name = json.nonBlankStringOrNull("name") ?: return null + return NpsCategory( + code = code, + name = name, + detractorQuestion = json.nonBlankStringOrNull("detractor_question"), + passiveQuestion = json.nonBlankStringOrNull("passive_question"), + promoterQuestion = json.nonBlankStringOrNull("promoter_question"), + detractorSuccess = json.nonBlankStringOrNull("detractor_success"), + passiveSuccess = json.nonBlankStringOrNull("passive_success"), + promoterSuccess = json.nonBlankStringOrNull("promoter_success"), + buttonLabel = json.nonBlankStringOrNull("button_label"), + ) + } + + /** A channel by its code and name, left out without one of them. */ + fun readChannel(json: JSONObject): PollChannel? { + val code = json.nonBlankStringOrNull("code") ?: return null + val name = json.nonBlankStringOrNull("name") ?: return null + return PollChannel(code = code, name = name) + } + + /** A CSAT campaign by its code and name, left out without one of them. */ + fun readCsatCampaign(json: JSONObject): CsatCampaign? { + val code = json.nonBlankStringOrNull("code") ?: return null + val name = json.nonBlankStringOrNull("name") ?: return null + return CsatCampaign( + code = code, + name = name, + dissatisfiedQuestion = json.nonBlankStringOrNull("dissatisfied_question"), + neutralQuestion = json.nonBlankStringOrNull("neutral_question"), + satisfiedQuestion = json.nonBlankStringOrNull("satisfied_question"), + dissatisfiedSuccess = json.nonBlankStringOrNull("dissatisfied_success"), + neutralSuccess = json.nonBlankStringOrNull("neutral_success"), + satisfiedSuccess = json.nonBlankStringOrNull("satisfied_success"), + buttonLabel = json.nonBlankStringOrNull("button_label"), + ) + } + + /** A CES campaign by its code and name, left out without one of them. */ + fun readCesCampaign(json: JSONObject): CesCampaign? { + val code = json.nonBlankStringOrNull("code") ?: return null + val name = json.nonBlankStringOrNull("name") ?: return null + return CesCampaign( + code = code, + name = name, + difficultQuestion = json.nonBlankStringOrNull("difficult_question"), + neutralQuestion = json.nonBlankStringOrNull("neutral_question"), + easyQuestion = json.nonBlankStringOrNull("easy_question"), + difficultSuccess = json.nonBlankStringOrNull("difficult_success"), + neutralSuccess = json.nonBlankStringOrNull("neutral_success"), + easySuccess = json.nonBlankStringOrNull("easy_success"), + buttonLabel = json.nonBlankStringOrNull("button_label"), + ) + } + + /** + * `payload.summary` and `payload.reviews`; without either, or without the summary's count, the answer is + * null (`decoding`). An answer without a body is a product without reviews. + */ + fun readProductReviews(body: Any?): ProductReviewsResponse? { + if (body == null) return ProductReviewsResponse(ProductRatingSummary(count = 0), emptyList()) + val payload = (body as? JSONObject)?.objectOrNull("payload") ?: return null + val summary = payload.objectOrNull("summary")?.let(::readSummary) ?: return null + val reviews = payload.arrayOrNull("reviews")?.mapObjects(::readProductReview) ?: return null + return ProductReviewsResponse(summary, reviews) + } + + /** The summary; `ratings` keeps the keys that are whole numbers (`"1"`…`"5"` in the answer) with a whole count. */ + private fun readSummary(json: JSONObject): ProductRatingSummary? { + val count = json.intOrNull("count") ?: return null + val ratings = json.objectOrNull("ratings")?.let { counts -> + counts.keys().asSequence().mapNotNull { key -> + val rating = key.trim().toIntOrNull() ?: return@mapNotNull null + counts.intOrNull(key)?.let { rating to it } + }.toMap() + }.orEmpty() + return ProductRatingSummary(count = count, averageRating = json.doubleOrNull("average_rating"), ratings = ratings) + } + + /** A review, left out without its id, rating or time. */ + private fun readProductReview(json: JSONObject): ProductReview? { + val id = json.longOrNull("id") ?: return null + val rating = json.intOrNull("rating") ?: return null + val createdAt = json.nonBlankStringOrNull("created_at") ?: return null + return ProductReview( + id = id, + rating = rating, + comment = json.nonBlankStringOrNull("comment"), + author = json.nonBlankStringOrNull("author"), + createdAt = createdAt, + ) + } + + /** A review of the customer, left out without its id, product, order, rating or time; a state this release does not know is null. */ + fun readClientReview(json: JSONObject): ClientReview? { + val id = json.longOrNull("id") ?: return null + val itemId = json.nonBlankStringOrNull("product") ?: return null + val orderId = json.nonBlankStringOrNull("order") ?: return null + val rating = json.intOrNull("rating") ?: return null + val createdAt = json.nonBlankStringOrNull("created_at") ?: return null + return ClientReview( + id = id, + itemId = itemId, + orderId = orderId, + rating = rating, + comment = json.nonBlankStringOrNull("comment"), + state = valueOfWire(json.nonBlankStringOrNull("state"), ReviewState.entries) { it.value }, + createdAt = createdAt, + ) + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/search/AgentJson.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/search/AgentJson.kt new file mode 100644 index 00000000..c211d8e4 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/search/AgentJson.kt @@ -0,0 +1,78 @@ +package com.personalization.features.search + +import com.personalization.api.models.search.AgentDialogResponse +import com.personalization.api.models.search.AgentMessage +import com.personalization.api.models.search.AgentMessageRole +import com.personalization.api.models.search.AgentProduct +import com.personalization.api.models.search.AgentResponse +import com.personalization.api.models.search.AgentSession +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.doubleOrNull +import com.personalization.core.internal.longOrNull +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.objectOrNull +import com.personalization.core.internal.stringOrNull +import org.json.JSONObject + +/** + * Reading the search agent's answers (`api/v3/storefront/search/agent`) into the `Agent*` models, + * tolerantly: a session, a message or a product without its id is left out, and a role the SDK does not + * know reads as it is. + */ +internal object AgentJson { + + /** The sessions and the chosen one; an answer that is not an object is null (`decoding`). */ + fun dialog(body: Any?): AgentDialogResponse? { + if (body !is JSONObject) return null + return AgentDialogResponse( + sessions = body.arrayOrNull("sessions")?.mapObjects(::session).orEmpty(), + session = body.objectOrNull("session")?.let(::session), + ) + } + + /** The session and the agent's answer; null (`decoding`) without either. */ + fun answer(body: Any?): AgentResponse? { + if (body !is JSONObject) return null + val session = body.objectOrNull("session")?.let(::session) ?: return null + val message = body.objectOrNull("message")?.let(::message) ?: return null + return AgentResponse(session = session, message = message) + } + + private fun session(json: JSONObject): AgentSession? { + val id = json.longOrNull("id") ?: return null + return AgentSession( + id = id, + title = json.stringOrNull("title"), + updatedAt = json.stringOrNull("updated_at"), + messages = json.arrayOrNull("messages")?.mapObjects(::message).orEmpty(), + ) + } + + private fun message(json: JSONObject): AgentMessage? { + val id = json.longOrNull("id") ?: return null + return AgentMessage( + id = id, + role = json.nonBlankStringOrNull("role")?.let(::AgentMessageRole), + content = json.stringOrNull("content"), + createdAt = json.stringOrNull("created_at"), + products = json.arrayOrNull("products")?.mapObjects(::product).orEmpty(), + ) + } + + private fun product(json: JSONObject): AgentProduct? { + val id = json.nonBlankStringOrNull("id") ?: return null + return AgentProduct( + id = id, + name = json.stringOrNull("name"), + price = json.doubleOrNull("price"), + // The server sends 0.0 for a product without an old price. + oldPrice = json.doubleOrNull("oldprice")?.takeIf { it != 0.0 }, + priceFormatted = json.stringOrNull("price_formatted"), + oldPriceFormatted = json.stringOrNull("oldprice_formatted"), + picture = json.stringOrNull("picture"), + url = json.stringOrNull("url"), + reason = json.stringOrNull("reason"), + ) + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/search/SearchApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/search/SearchApiImpl.kt new file mode 100644 index 00000000..6156ceb9 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/search/SearchApiImpl.kt @@ -0,0 +1,232 @@ +package com.personalization.features.search + +import com.personalization.api.managers.SearchApi +import com.personalization.api.models.search.AgentDialogResponse +import com.personalization.api.models.search.AgentResponse +import com.personalization.api.models.search.Query +import com.personalization.api.models.search.SearchBlankResponse +import com.personalization.api.models.search.SearchFullRequest +import com.personalization.api.models.search.SearchFullResponse +import com.personalization.api.models.search.SearchInstantResponse +import com.personalization.api.models.search.SearchRedirect +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.booleanOrNull +import com.personalization.core.internal.doubleOrNull +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.objectOrNull +import com.personalization.core.internal.putFilters +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.putList +import com.personalization.core.internal.putNumber +import com.personalization.core.internal.requireAtLeast +import com.personalization.core.internal.requireNotBlank +import com.personalization.core.internal.requirePriceRange +import com.personalization.core.internal.stringOrNull +import com.personalization.features.products.CatalogJson +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONArray +import org.json.JSONObject + +/** + * [SearchApi] over the namespaces' path ([NamespaceCalls]). [agentSearch] tells whether the last `/init` + * answer turned the search agent on. + */ +@OptIn(BridgeApi::class) +internal class SearchApiImpl( + private val calls: NamespaceCalls, + private val agentSearch: () -> Boolean = { false }, +) : SearchApi { + + override val agentEnabled: Boolean + get() = agentSearch() + + override suspend fun blank(): SearchBlankResponse = + calls.request(BLANK, NetworkMethod.GET(BLANK_PATH), read = ::readBlank) + + override suspend fun instant( + query: String, + locations: List?, + excludedMerchants: List?, + excludedBrands: List?, + ): SearchInstantResponse { + val params = calls.checked(INSTANT) { + JSONObject() + .put(TYPE, INSTANT_SEARCH) + .put(SEARCH_QUERY, requireNotBlank(query, "query")) + .putList("locations", locations) + .putList("excluded_merchants", excludedMerchants.takeUnless { locations.isNullOrEmpty() }) + .putList("excluded_brands", excludedBrands) + } + return calls.request(INSTANT, NetworkMethod.GET(SEARCH_PATH), params, read = ::readInstant) + } + + override suspend fun full(query: String, request: SearchFullRequest): SearchFullResponse { + val params = calls.checked(FULL) { + fullParams(request, JSONObject().put(TYPE, FULL_SEARCH).put(SEARCH_QUERY, requireNotBlank(query, "query"))) + } + return calls.request(FULL, NetworkMethod.GET(SEARCH_PATH), params, read = ::readFull) + } + + override suspend fun agentDialog(sessionId: Long?, locations: List?): AgentDialogResponse { + val params = JSONObject().putIfNotNull(SESSION_ID, sessionId).putList(LOCATION, locations) + return calls.request(AGENT_DIALOG, NetworkMethod.GET(AGENT_PATH), params, read = AgentJson::dialog) + } + + override suspend fun agent(message: String, sessionId: Long?, locations: List?): AgentResponse { + val params = calls.checked(AGENT) { + requireNotBlank(message, "message") + if (message.codePointCount(0, message.length) > MESSAGE_MAX_LENGTH) { + invalidArgument("message must not be longer than $MESSAGE_MAX_LENGTH characters") + } + JSONObject().put(MESSAGE, message).putIfNotNull(SESSION_ID, sessionId).putList(LOCATION, locations) + } + return calls.request(AGENT, NetworkMethod.POST(AGENT_PATH), params, readTimeoutMs = AGENT_READ_TIMEOUT_MS, read = AgentJson::answer) + } + + override fun blank(listener: CompletionListener) = calls.complete(listener) { blank() } + + override fun instant( + query: String, + locations: List?, + excludedMerchants: List?, + excludedBrands: List?, + listener: CompletionListener, + ) = calls.complete(listener) { instant(query, locations, excludedMerchants, excludedBrands) } + + override fun full(query: String, request: SearchFullRequest, listener: CompletionListener) = + calls.complete(listener) { full(query, request) } + + override fun agentDialog(sessionId: Long?, locations: List?, listener: CompletionListener) = + calls.complete(listener) { agentDialog(sessionId, locations) } + + override fun agent(message: String, sessionId: Long?, locations: List?, listener: CompletionListener) = + calls.complete(listener) { agent(message, sessionId, locations) } + + internal companion object { + const val BLANK = "search.blank" + const val INSTANT = "search.instant" + const val FULL = "search.full" + const val BLANK_PATH = "search/blank" + const val SEARCH_PATH = "search" + private const val TYPE = "type" + private const val SEARCH_QUERY = "search_query" + private const val INSTANT_SEARCH = "instant_search" + private const val FULL_SEARCH = "full_search" + + const val AGENT_DIALOG = "search.agentDialog" + const val AGENT = "search.agent" + + /** The search agent, on the host of API v3 (`Rees46Config.appDomain`). */ + const val AGENT_PATH = "api/v3/storefront/search/agent" + + /** The agent may take 40 seconds and two more attempts: its answer is read for longer than the common 10. */ + const val AGENT_READ_TIMEOUT_MS = 60_000L + private const val MESSAGE_MAX_LENGTH = 500 + private const val MESSAGE = "message" + private const val SESSION_ID = "session_id" + private const val LOCATION = "location" + + /** The fields of [request] after their checks; the sort's direction goes as `order`, as the API's documentation names it. */ + private fun fullParams(request: SearchFullRequest, params: JSONObject): JSONObject = with(request) { + requirePriceRange(priceMin, priceMax) + requireAtLeast(categoryLimit, 1, "categoryLimit") + requireAtLeast(brandLimit, 1, "brandLimit") + requireAtLeast(limit, 1, "limit") + requireAtLeast(page, 1, "page") + params + .putList("categories", categoryIds) + .putList("brands", brands) + .putList("excluded_brands", excludedBrands) + .putList("merchants", merchants) + .putList("excluded_merchants", excludedMerchants.takeUnless { locations.isNullOrEmpty() }) + .putList("locations", locations) + .putNumber("price_min", priceMin) + .putNumber("price_max", priceMax) + .putList("colors", colors) + .putList("fashion_sizes", fashionSizes) + .putList("exclude", excludedItemIds) + .putFilters("filters", filters) + .putIfNotNull("sort_by", sortBy?.value) + .putIfNotNull("order", sortDir?.value) + .putIfNotNull("no_clarification", "true".takeIf { disableClarification }) + .putIfNotNull("category_limit", categoryLimit) + .putIfNotNull("brand_limit", brandLimit) + .putIfNotNull("limit", limit) + .putIfNotNull("page", page) + } + + /** + * An empty search. The server leaves out what is empty, and answers `[]` when everything is: so an + * empty array, or no body, is an empty result. + */ + fun readBlank(body: Any?): SearchBlankResponse? { + if (body == null || (body is JSONArray && body.length() == 0)) return SearchBlankResponse() + if (body !is JSONObject) return null + return SearchBlankResponse( + products = CatalogJson.products(body).orEmpty(), + lastProducts = body.booleanOrNull("last_products") ?: false, + lastQueries = queries(body, "last_queries"), + suggests = queries(body, "suggests"), + popularCategories = CatalogJson.popularItems(body, "popular_categories"), + popularBrands = CatalogJson.popularItems(body, "popular_brands"), + popularLinks = CatalogJson.popularItems(body, "popular_links"), + ) + } + + /** An instant search's results; an answer without `products` is null (`decoding`). */ + fun readInstant(body: Any?): SearchInstantResponse? { + if (body !is JSONObject) return null + return SearchInstantResponse( + searchQuery = body.stringOrNull("search_query"), + searchQueryOriginal = body.stringOrNull("search_query_original"), + clarification = body.booleanOrNull("clarification"), + productsTotal = body.intOrNull("products_total"), + products = CatalogJson.products(body) ?: return null, + categories = CatalogJson.categories(body), + queries = queries(body, "queries"), + locations = CatalogJson.locations(body), + redirect = body.objectOrNull("search_query_redirects")?.let { redirect -> + SearchRedirect( + query = redirect.stringOrNull("query"), + url = redirect.stringOrNull("redirect_link"), + deeplink = redirect.stringOrNull("deep_link"), + ) + }, + ) + } + + /** A full search's results; an answer without `products` is null (`decoding`). */ + fun readFull(body: Any?): SearchFullResponse? { + if (body !is JSONObject) return null + return SearchFullResponse( + searchQuery = body.stringOrNull("search_query"), + searchQueryOriginal = body.stringOrNull("search_query_original"), + clarification = body.booleanOrNull("clarification"), + productsTotal = body.intOrNull("products_total"), + products = CatalogJson.products(body) ?: return null, + categories = CatalogJson.categories(body), + brands = CatalogJson.brands(body), + locations = CatalogJson.locations(body), + filters = CatalogJson.filters(body), + industrialFilters = CatalogJson.industrialFilters(body), + priceRange = CatalogJson.priceRange(body), + priceRanges = CatalogJson.priceRanges(body), + priceMedian = body.doubleOrNull("price_median"), + ) + } + + /** Queries; one without a name is left out. */ + private fun queries(json: JSONObject, key: String): List? = json.arrayOrNull(key)?.mapObjects { query -> + Query( + name = query.stringOrNull("name") ?: return@mapObjects null, + url = query.stringOrNull("url"), + score = query.doubleOrNull("score"), + ) + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/segments/SegmentsApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/segments/SegmentsApiImpl.kt new file mode 100644 index 00000000..62715604 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/segments/SegmentsApiImpl.kt @@ -0,0 +1,80 @@ +package com.personalization.features.segments + +import com.personalization.api.managers.SegmentsApi +import com.personalization.api.models.segments.Segment +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.requireContact +import com.personalization.core.internal.stringOrNull +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONArray +import org.json.JSONObject + +/** + * [SegmentsApi] over the namespaces' path ([NamespaceCalls]). [abGroup] is the device's A/B group the SDK + * keeps, null for an instance never initialized. [contextChanged] tells popups v3 that the segments + * changed, once the server took the change, so their list is asked for again. + */ +@OptIn(BridgeApi::class) +internal class SegmentsApiImpl( + private val calls: NamespaceCalls, + private val abGroup: () -> String?, + private val contextChanged: (type: String, signature: String) -> Unit = { _, _ -> }, +) : SegmentsApi { + + override suspend fun add(segmentId: Int, email: String?, phone: String?) = change(ADD, ADD_METHOD, segmentId, email, phone) + + override suspend fun remove(segmentId: Int, email: String?, phone: String?) = change(REMOVE, REMOVE_METHOD, segmentId, email, phone) + + override suspend fun get(): List = calls.request(GET, NetworkMethod.GET(GET_PATH), read = ::readSegments) + + override fun getAbGroup(): String = abGroup().orEmpty() + + override fun add(segmentId: Int, email: String?, phone: String?, listener: CompletionListener) = + calls.complete(listener) { add(segmentId, email, phone) } + + override fun remove(segmentId: Int, email: String?, phone: String?, listener: CompletionListener) = + calls.complete(listener) { remove(segmentId, email, phone) } + + override fun get(listener: CompletionListener>) = calls.complete(listener) { get() } + + /** Adds the customer to the segment or takes them out ([method]): `segments/add` or `segments/remove`. */ + private suspend fun change(call: String, method: String, segmentId: Int, email: String?, phone: String?) { + val params = calls.checked(call) { + if (segmentId <= 0) invalidArgument("segmentId must be above 0") + requireContact(email, "email") + requireContact(phone, "phone") + JSONObject().put("segment_id", segmentId).putIfNotNull("email", email).putIfNotNull("phone", phone) + } + val signature = "$method $params" + calls.request(call, NetworkMethod.POST("$SEGMENTS/$method"), params) { Unit } + contextChanged(SEGMENTS, signature) + } + + internal companion object { + const val ADD = "segments.add" + const val REMOVE = "segments.remove" + const val GET = "segments.get" + const val SEGMENTS = "segments" + const val ADD_METHOD = "add" + const val REMOVE_METHOD = "remove" + const val GET_PATH = "segments/get" + + /** + * The customer's segments: an array of `{id, type}`; a segment without an id is left out, and an + * answer without a body is no segment. An answer that is not an array is null (`decoding`). + */ + fun readSegments(body: Any?): List? = when (body) { + null -> emptyList() + is JSONArray -> body.mapObjects { segment -> + segment.intOrNull("id")?.let { Segment(id = it, type = segment.stringOrNull("type")) } + } + else -> null + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/sliders/SlidersApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/sliders/SlidersApiImpl.kt new file mode 100644 index 00000000..cf85228a --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/sliders/SlidersApiImpl.kt @@ -0,0 +1,76 @@ +package com.personalization.features.sliders + +import com.personalization.api.managers.SlidersApi +import com.personalization.api.models.sliders.Slider +import com.personalization.api.models.sliders.SliderBanner +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.nonBlankStringOrNull +import com.personalization.core.internal.objectOrNull +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.putList +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** [SlidersApi] over the namespaces' path ([NamespaceCalls]). */ +@OptIn(BridgeApi::class) +internal class SlidersApiImpl(private val calls: NamespaceCalls) : SlidersApi { + + override suspend fun get(code: String, tags: List?, locationId: String?): Slider { + val params = calls.checked(GET) { + if (code.isBlank()) invalidArgument("code is empty") + // Tags go joined by commas: a tag with one would read as two. + if (tags?.any { it.isBlank() || it.contains(',') } == true) invalidArgument("tags has an empty tag or one with a comma") + JSONObject().put(CODE, code).putList(TAGS, tags).putIfNotNull(LOCATION, locationId) + } + return calls.request(GET, NetworkMethod.GET(PATH), params) { body -> readSlider(body, code) } + } + + override fun get(code: String, tags: List?, locationId: String?, listener: CompletionListener) = + calls.complete(listener) { get(code, tags, locationId) } + + internal companion object { + const val GET = "sliders.get" + const val PATH = "slider" + + private const val CODE = "code" + private const val TAGS = "tags" + private const val LOCATION = "location" + + /** + * `payload.properties` and `payload.slides`; null (`decoding`) without the list of banners. Without + * its own code the slider and its banners take [asked], the code it was asked for. A banner without + * an id, which its events need, is left out. + */ + fun readSlider(body: Any?, asked: String): Slider? { + val payload = (body as? JSONObject)?.objectOrNull("payload") ?: return null + val slides = payload.arrayOrNull("slides") ?: return null + val properties = payload.objectOrNull("properties") + val code = properties?.nonBlankStringOrNull(CODE) ?: asked + return Slider( + code = code, + width = properties?.intOrNull("width") ?: 0, + height = properties?.intOrNull("height") ?: 0, + banners = slides.mapObjects { banner -> readBanner(banner, code) }, + ) + } + + private fun readBanner(banner: JSONObject, sliderCode: String): SliderBanner? { + val id = banner.nonBlankStringOrNull("banner_id") ?: return null + return SliderBanner( + id = id, + code = banner.nonBlankStringOrNull("recommended_code") ?: sliderCode, + imageUrl = banner.nonBlankStringOrNull("image_url"), + url = banner.nonBlankStringOrNull("url"), + deeplinkIos = banner.nonBlankStringOrNull("deeplink_ios"), + deeplinkAndroid = banner.nonBlankStringOrNull("deeplink_android"), + html = banner.nonBlankStringOrNull("html"), + ) + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/stories/StoriesApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/stories/StoriesApiImpl.kt new file mode 100644 index 00000000..e9a29a10 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/stories/StoriesApiImpl.kt @@ -0,0 +1,167 @@ +package com.personalization.features.stories + +import com.personalization.api.managers.StoriesApi +import com.personalization.api.models.stories.StoriesBlock +import com.personalization.api.models.stories.Story +import com.personalization.api.models.stories.StoryButtonElement +import com.personalization.api.models.stories.StoryElement +import com.personalization.api.models.stories.StoryProduct +import com.personalization.api.models.stories.StoryProductElement +import com.personalization.api.models.stories.StoryProductsElement +import com.personalization.api.models.stories.StorySlide +import com.personalization.api.models.stories.StorySlideType +import com.personalization.api.models.stories.StoryTextBlockElement +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.arrayOrNull +import com.personalization.core.internal.booleanOrNull +import com.personalization.core.internal.doubleOrNull +import com.personalization.core.internal.intOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.mapObjects +import com.personalization.core.internal.objectOrNull +import com.personalization.core.internal.pathSegment +import com.personalization.core.internal.stringOrNull +import com.personalization.core.internal.valueOrNull +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** [StoriesApi] over the namespaces' path ([NamespaceCalls]). */ +@OptIn(BridgeApi::class) +internal class StoriesApiImpl(private val calls: NamespaceCalls) : StoriesApi { + + override suspend fun get(code: String): StoriesBlock { + calls.checked(GET) { if (code.isBlank()) invalidArgument("code is empty") } + return calls.request(GET, NetworkMethod.GET(path(code)), read = ::readBlock) + } + + override fun get(code: String, listener: CompletionListener) = calls.complete(listener) { get(code) } + + internal companion object { + const val GET = "stories.get" + const val PATH = "stories/" + + /** `stories/{code}`, the code encoded as one segment of the path. */ + fun path(code: String): String = PATH + pathSegment(code) + + /* + * Read as the Flutter SDK reads the same answer, and the answer of API v3 with it: numbers may come + * as strings, ids as numbers; a field that is missing takes its default. Only an answer that is not + * a JSON object is `decoding`. + */ + + fun readBlock(body: Any?): StoriesBlock? { + if (body !is JSONObject) return null + return StoriesBlock( + id = body.stringOrNull("id").orEmpty(), + stories = body.arrayOrNull("stories")?.mapObjects(::readStory).orEmpty(), + ) + } + + private fun readStory(story: JSONObject) = Story( + id = story.stringOrNull("id").orEmpty(), + name = story.stringOrNull("name").orEmpty(), + avatar = story.stringOrNull("avatar").orEmpty(), + viewed = story.booleanOrNull("viewed") ?: false, + pinned = story.booleanOrNull("pinned") ?: false, + startPosition = story.intOrNull("start_position") ?: 0, + slides = story.arrayOrNull("slides")?.mapObjects(::readSlide).orEmpty(), + ) + + private fun readSlide(slide: JSONObject) = StorySlide( + id = slide.stringOrNull("id").orEmpty(), + type = when (slide.stringOrNull("type")) { + "image" -> StorySlideType.IMAGE + "video" -> StorySlideType.VIDEO + else -> StorySlideType.PRODUCT + }, + background = slide.stringOrNull("background").orEmpty(), + backgroundColor = slide.stringOrNull("background_color").orEmpty(), + preview = slide.stringOrNull("preview").orEmpty(), + duration = slide.intOrNull("duration")?.takeIf { it > 0 } ?: StorySlide.DEFAULT_DURATION, + elements = slide.arrayOrNull("elements")?.mapObjects(::readElement).orEmpty(), + ) + + /** The element by its `type`; null — left out — for `header`, `poll` and the types the SDK does not know. */ + private fun readElement(element: JSONObject): StoryElement? = when (element.stringOrNull("type")) { + "button" -> StoryButtonElement( + title = element.text("title"), + link = element.text("link"), + linkAndroid = element.text("link_android"), + linkIos = element.text("link_ios"), + background = element.text("background"), + color = element.text("color"), + textBold = element.flag("text_bold") || element.flag("bold"), + ) + "product" -> StoryProductElement( + title = element.text("title"), + item = element.objectOrNull("item")?.takeIf { it.length() > 0 }?.let(::readProduct), + ) + "products" -> element.objectOrNull("labels").let { labels -> + StoryProductsElement( + showLabel = labels?.text("show_carousel").orEmpty(), + hideLabel = labels?.text("hide_carousel").orEmpty(), + products = element.arrayOrNull("products")?.mapObjects(::readProduct).orEmpty(), + ) + } + "text_block" -> StoryTextBlockElement( + text = element.text("text_input"), + fontSize = element.doubleOrNull("font_size") ?: StoryTextBlockElement.DEFAULT_FONT_SIZE, + fontType = element.text("font_type"), + bold = element.flag("bold") || element.flag("text_bold"), + italic = element.flag("italic"), + textAlign = element.text("text_align"), + textColor = element.text("text_color"), + backgroundColor = element.text("text_background_color"), + backgroundOpacity = opacity(element.valueOrNull("text_background_color_opacity")), + lineSpacing = element.doubleOrNull("text_line_spacing") ?: 0.0, + yOffset = element.doubleOrNull("y_offset") ?: 0.0, + promocode = element.stringOrNull("promocode")?.takeIf { it.isNotEmpty() }, + ) + else -> null + } + + private fun readProduct(product: JSONObject): StoryProduct { + val price = product.doubleOrNull("price") ?: 0.0 + return StoryProduct( + id = product.text("id"), + name = product.text("name"), + brand = product.text("brand"), + picture = product.text("picture"), + imageUrl = product.text("image_url"), + price = price, + priceFormatted = product.text("price_formatted"), + oldPrice = product.doubleOrNull("oldprice")?.takeIf { it > price }, + oldPriceFormatted = product.text("oldprice_formatted"), + discountPercent = product.doubleOrNull("discount_percent") ?: 0.0, + promocode = product.text("promocode"), + priceWithPromocode = product.doubleOrNull("price_with_promocode") ?: 0.0, + priceWithPromocodeFormatted = product.text("price_with_promocode_formatted"), + currency = product.text("currency"), + url = product.text("url"), + deeplinkAndroid = product.text("deeplink_android"), + deeplinkIos = product.text("deeplink_ios"), + ) + } + + /** + * An opacity from 0 to 1. A string is percent, with the sign or without (`"50%"`, `"50"`), as the + * dashboard sends it; a number above 1 is percent too, otherwise a fraction. + */ + fun opacity(value: Any?): Double { + val number = when (value) { + is Number -> value.toDouble() + is String -> value.replace("%", "").trim().toDoubleOrNull() + else -> null + } + if (number == null || !number.isFinite() || number <= 0) return 0.0 + val fraction = if (value is String || number > 1) number / 100 else number + return fraction.coerceIn(0.0, 1.0) + } + + private fun JSONObject.text(key: String): String = stringOrNull(key).orEmpty() + + private fun JSONObject.flag(key: String): Boolean = booleanOrNull(key) ?: false + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/subscriptions/SubscriptionsApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/subscriptions/SubscriptionsApiImpl.kt new file mode 100644 index 00000000..e6dc4c33 --- /dev/null +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/subscriptions/SubscriptionsApiImpl.kt @@ -0,0 +1,188 @@ +package com.personalization.features.subscriptions + +import com.personalization.api.managers.SubscriptionsApi +import com.personalization.api.models.subscriptions.BackInStockProperties +import com.personalization.api.models.subscriptions.SubscriptionStatus +import com.personalization.api.models.subscriptions.SubscriptionsUpdateRequest +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.booleanOrNull +import com.personalization.core.internal.invalidArgument +import com.personalization.core.internal.putIfNotNull +import com.personalization.core.internal.requireContact +import com.personalization.core.internal.requireNotBlank +import com.personalization.sdk.domain.models.NetworkMethod +import org.json.JSONObject + +/** + * [SubscriptionsApi] over the namespaces' path ([NamespaceCalls]). [contextChanged] tells popups v3 that + * the subscriptions changed, once the server took the change, so their list is asked for again. + */ +@OptIn(BridgeApi::class) +internal class SubscriptionsApiImpl( + private val calls: NamespaceCalls, + private val contextChanged: (type: String, signature: String) -> Unit = { _, _ -> }, +) : SubscriptionsApi { + + override suspend fun manage(request: SubscriptionsUpdateRequest) { + val params = calls.checked(MANAGE) { manageParams(request) } + val signature = params.toString() + send(MANAGE, MANAGE_PATH, params) + contextChanged(MANAGE_PATH, signature) + } + + override suspend fun check(): SubscriptionStatus = + calls.request(CHECK, NetworkMethod.GET(CHECK_PATH), read = ::readStatus) + + override suspend fun subscribeForPriceDrop(itemId: String, currentPrice: Double, email: String?, phone: String?) { + val params = calls.checked(SUBSCRIBE_PRICE) { + if (!(currentPrice.isFinite() && currentPrice > 0)) invalidArgument("currentPrice must be above 0") + itemParams(itemId, email, phone).put("price", currentPrice) + } + send(SUBSCRIBE_PRICE, SUBSCRIBE_PRICE_PATH, params) + } + + override suspend fun unsubscribeFromPriceDrop(itemIds: List, email: String?, phone: String?) { + val params = calls.checked(UNSUBSCRIBE_PRICE) { itemIdsParams(itemIds, email, phone) } + send(UNSUBSCRIBE_PRICE, UNSUBSCRIBE_PRICE_PATH, params) + } + + override suspend fun subscribeForBackInStock(itemId: String, properties: BackInStockProperties?, email: String?, phone: String?) { + val params = calls.checked(SUBSCRIBE_STOCK) { itemParams(itemId, email, phone) } + properties?.let { + JSONObject() + .putIfNotNull("fashion_size", it.fashionSize) + .putIfNotNull("fashion_color", it.fashionColor) + .putIfNotNull("barcode", it.barcode) + }?.takeIf { it.length() > 0 }?.let { params.put("properties", it) } + send(SUBSCRIBE_STOCK, SUBSCRIBE_STOCK_PATH, params) + } + + override suspend fun unsubscribeFromBackInStock(itemIds: List, email: String?, phone: String?) { + val params = calls.checked(UNSUBSCRIBE_STOCK) { itemIdsParams(itemIds, email, phone) } + send(UNSUBSCRIBE_STOCK, UNSUBSCRIBE_STOCK_PATH, params) + } + + override fun manage(request: SubscriptionsUpdateRequest, listener: CompletionListener) = + calls.complete(listener) { manage(request) } + + override fun check(listener: CompletionListener) = calls.complete(listener) { check() } + + override fun subscribeForPriceDrop(itemId: String, currentPrice: Double, email: String?, phone: String?, listener: CompletionListener) = + calls.complete(listener) { subscribeForPriceDrop(itemId, currentPrice, email, phone) } + + override fun unsubscribeFromPriceDrop(itemIds: List, email: String?, phone: String?, listener: CompletionListener) = + calls.complete(listener) { unsubscribeFromPriceDrop(itemIds, email, phone) } + + override fun subscribeForBackInStock( + itemId: String, + properties: BackInStockProperties?, + email: String?, + phone: String?, + listener: CompletionListener, + ) = calls.complete(listener) { subscribeForBackInStock(itemId, properties, email, phone) } + + override fun unsubscribeFromBackInStock(itemIds: List, email: String?, phone: String?, listener: CompletionListener) = + calls.complete(listener) { unsubscribeFromBackInStock(itemIds, email, phone) } + + /** Sends [params] to [path]; any `2xx` but `{"status": "error"}` is done. */ + private suspend fun send(call: String, path: String, params: JSONObject) { + calls.request(call, NetworkMethod.POST(path), params) { Unit } + } + + internal companion object { + const val MANAGE = "subscriptions.manage" + const val CHECK = "subscriptions.check" + const val SUBSCRIBE_PRICE = "subscriptions.subscribeForPriceDrop" + const val UNSUBSCRIBE_PRICE = "subscriptions.unsubscribeFromPriceDrop" + const val SUBSCRIBE_STOCK = "subscriptions.subscribeForBackInStock" + const val UNSUBSCRIBE_STOCK = "subscriptions.unsubscribeFromBackInStock" + const val MANAGE_PATH = "subscriptions/manage" + const val CHECK_PATH = "subscriptions/check" + const val SUBSCRIBE_PRICE_PATH = "subscriptions/subscribe_for_product_price" + const val UNSUBSCRIBE_PRICE_PATH = "subscriptions/unsubscribe_from_product_price" + const val SUBSCRIBE_STOCK_PATH = "subscriptions/subscribe_for_product_available" + const val UNSUBSCRIBE_STOCK_PATH = "subscriptions/unsubscribe_from_product_available" + + /** The 24 flags: a channel's kinds of mailings, as the API names them. */ + private fun flags(request: SubscriptionsUpdateRequest): List> = with(request) { + listOf( + "email_bulk" to emailBulk, "email_chain" to emailChain, "email_transactional" to emailTransactional, + "sms_bulk" to smsBulk, "sms_chain" to smsChain, "sms_transactional" to smsTransactional, + "web_push_bulk" to webPushBulk, "web_push_chain" to webPushChain, "web_push_transactional" to webPushTransactional, + "mobile_push_bulk" to mobilePushBulk, "mobile_push_chain" to mobilePushChain, + "mobile_push_transactional" to mobilePushTransactional, + "telegram_bulk" to telegramBulk, "telegram_chain" to telegramChain, "telegram_transactional" to telegramTransactional, + "whatsapp_bulk" to whatsappBulk, "whatsapp_chain" to whatsappChain, "whatsapp_transactional" to whatsappTransactional, + "max_bulk" to maxBulk, "max_chain" to maxChain, "max_transactional" to maxTransactional, + "wallet_bulk" to walletBulk, "wallet_chain" to walletChain, "wallet_transactional" to walletTransactional, + ) + } + + /** The fields of `manage` after their checks: a contact is not empty, and at least one flag is given. */ + private fun manageParams(request: SubscriptionsUpdateRequest): JSONObject = with(request) { + requireContact(email, "email") + requireContact(phone, "phone") + requireContact(externalId, "externalId") + requireContact(loyaltyId, "loyaltyId") + requireContact(telegramId, "telegramId") + val flags = flags(request).filter { it.second != null } + if (flags.isEmpty()) invalidArgument("The request changes no subscription") + val params = JSONObject() + .putIfNotNull("email", email) + .putIfNotNull("phone", phone) + .putIfNotNull("external_id", externalId) + .putIfNotNull("loyalty_id", loyaltyId) + .putIfNotNull("telegram_id", telegramId) + flags.forEach { (name, value) -> params.put(name, value) } + params + } + + /** A product's fields: its id (`item_id`), which must not be empty, and the contacts. */ + private fun itemParams(itemId: String, email: String?, phone: String?): JSONObject { + val params = JSONObject().put("item_id", requireNotBlank(itemId, "itemId")) + return contacts(params, email, phone) + } + + /** The products' ids as one string joined with commas (`item_ids`); an empty list is every product, an empty id fails. */ + private fun itemIdsParams(itemIds: List, email: String?, phone: String?): JSONObject { + if (itemIds.any { it.isBlank() }) invalidArgument("itemIds must not hold an empty id") + return contacts(JSONObject().put("item_ids", itemIds.joinToString(",")), email, phone) + } + + private fun contacts(params: JSONObject, email: String?, phone: String?): JSONObject { + requireContact(email, "email") + requireContact(phone, "phone") + return params.putIfNotNull("email", email).putIfNotNull("phone", phone) + } + + /** The subscriptions; a flag the answer leaves out is false, and an answer that is not an object is null (`decoding`). */ + fun readStatus(body: Any?): SubscriptionStatus? { + if (body !is JSONObject) return null + fun flag(name: String) = body.booleanOrNull(name) ?: false + return SubscriptionStatus( + exists = flag("exists"), + emailBulk = flag("email_bulk"), emailChain = flag("email_chain"), emailTransactional = flag("email_transactional"), + smsBulk = flag("sms_bulk"), smsChain = flag("sms_chain"), smsTransactional = flag("sms_transactional"), + webPushBulk = flag("web_push_bulk"), webPushChain = flag("web_push_chain"), + webPushTransactional = flag("web_push_transactional"), + mobilePushBulk = flag("mobile_push_bulk"), mobilePushChain = flag("mobile_push_chain"), + mobilePushTransactional = flag("mobile_push_transactional"), + telegramBulk = flag("telegram_bulk"), telegramChain = flag("telegram_chain"), + telegramTransactional = flag("telegram_transactional"), + whatsappBulk = flag("whatsapp_bulk"), whatsappChain = flag("whatsapp_chain"), + whatsappTransactional = flag("whatsapp_transactional"), + maxBulk = flag("max_bulk"), maxChain = flag("max_chain"), maxTransactional = flag("max_transactional"), + walletBulk = flag("wallet_bulk"), walletChain = flag("wallet_chain"), walletTransactional = flag("wallet_transactional"), + hasWebPush = flag("web_push"), + hasMobilePush = flag("mobile_push"), + emailInvalid = flag("email_invalid"), + emailBlacklisted = flag("email_blacklisted"), + emailBounced = flag("email_bounced"), + emailSuppressed = flag("email_suppressed"), + emailConfirmed = flag("email_confirmed"), + ) + } + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/tracking/impl/TrackingApiImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/tracking/impl/TrackingApiImpl.kt index 9fd2b6dd..0a7405c2 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/features/tracking/impl/TrackingApiImpl.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/tracking/impl/TrackingApiImpl.kt @@ -11,10 +11,14 @@ import com.personalization.api.models.tracking.TrackingItem import com.personalization.api.models.tracking.TrackingSource import com.personalization.api.models.tracking.putSource import com.personalization.api.params.ProductItemParams +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener import com.personalization.core.SdkError import com.personalization.core.internal.CoreDispatchers import com.personalization.core.internal.LegacyDelivery import com.personalization.core.internal.LegacyErrors +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.invalidArgument import com.personalization.logs.LogCodes import com.personalization.logs.SdkLogs import com.personalization.sdk.domain.usecases.trackingSource.SetTrackingSourceUseCase @@ -42,6 +46,11 @@ internal class TrackingApiImpl @Inject constructor( * True on the new core, whose queue keeps events; the legacy core sends them as before. */ private val checksArguments: () -> Boolean = { false }, + /** + * The path of the bridge-only events, [bannerView] and [bannerClick]: the new core's queue. Without the + * instance's core they fail with `notInitialized`. + */ + private val events: NamespaceCalls = NamespaceCalls(core = { null }, dispatchers = { CoreDispatchers.DEFAULT }, shopId = { null }), ) : TrackingApi { /** @@ -250,6 +259,26 @@ internal class TrackingApiImpl @Inject constructor( setTrackingSourceUseCase(type = source.type.value, code = source.code) } + @BridgeApi + override fun bannerView(bannerId: String, code: String, listener: CompletionListener?) = + banner(BANNER_VIEW, BANNER_VIEW_EVENT, bannerId, code, listener) + + @BridgeApi + override fun bannerClick(bannerId: String, code: String, listener: CompletionListener?) = + banner(BANNER_CLICK, BANNER_CLICK_EVENT, bannerId, code, listener) + + /** + * A banner's [event] for `track/slider`: `banner_id` as a number, `recommended_code` the slider's + * [code]; `recommended_by` the server does not read here. Only through the new core's queue. + */ + private fun banner(call: String, event: String, bannerId: String, code: String, listener: CompletionListener?) = + events.event(call, SLIDER_PATH, listener) { + val id = bannerId.takeIf { id -> id.isNotEmpty() && id.all { it in '0'..'9' } }?.toLongOrNull()?.takeIf { it in 1..MAX_BANNER_ID } + ?: invalidArgument("bannerId is not a positive whole number") + if (code.isBlank()) invalidArgument("code is empty") + JSONObject().put(EVENT_PARAM, event).put(BANNER_ID_PARAM, id).put(RECOMMENDED_CODE_PARAM, code) + } + private fun Params.withSource(source: TrackingSource?): Params = source?.let { putSource(it) } ?: this @@ -273,5 +302,17 @@ internal class TrackingApiImpl @Inject constructor( const val STORY_VIEW_EVENT = "view" const val STORY_CLICK_EVENT = "click" const val ITEMS_PARAM = "items" + + const val BANNER_VIEW = "tracking.bannerView" + const val BANNER_CLICK = "tracking.bannerClick" + const val SLIDER_PATH = "track/slider" + const val BANNER_VIEW_EVENT = "view" + const val BANNER_CLICK_EVENT = "click" + const val EVENT_PARAM = "event" + const val BANNER_ID_PARAM = "banner_id" + const val RECOMMENDED_CODE_PARAM = "recommended_code" + + /** `banner_id` is an unsigned 32-bit number on the server. */ + const val MAX_BANNER_ID = 4_294_967_295L } } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImpl.kt b/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImpl.kt index ae2f6c2b..c8071417 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImpl.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/network/NetworkRepositoryImpl.kt @@ -26,7 +26,14 @@ class NetworkRepositoryImpl @Inject constructor( private lateinit var baseUrl: String - private val legacyCore = LegacyCore(userSettingsRepository) { baseUrl } + /** + * The host of API v3 (`Rees46Config.appDomain`) for the legacy core's paths under `api/v3/`; + * `app.rees46.ru` without one. The new core gets its own in [useCoreV2]. + */ + @Volatile + internal var appDomain: String? = null + + private val legacyCore = LegacyCore(userSettingsRepository, appUrl = { CoreHttpClient.appUrlOf(appDomain) }) { baseUrl } /** The core the requests go to: the legacy one until [useCoreV2]. */ @Volatile @@ -79,16 +86,19 @@ class NetworkRepositoryImpl @Inject constructor( /** * Sends this instance's requests through the new core from now on. [attach] runs before the core * takes any request: it gives the core its `/init`, so no request goes without waiting for it. + * [appDomain] is the host of API v3 (`Rees46Config.appDomain`), `app.rees46.ru` without one. */ internal fun useCoreV2( shopId: String, connectivity: ConnectivityMonitor, dispatchers: CoreDispatchers = CoreDispatchers.DEFAULT, + appDomain: String? = null, client: CoreHttpClient = CoreHttpClient( baseUrl = { baseUrl }, settings = userSettingsRepository, connectivity = connectivity, shopId = shopId, + appUrl = { CoreHttpClient.appUrlOf(appDomain) }, ), attach: (CoreV2) -> Unit = {}, ): CoreV2 = CoreV2(client, shopId, dispatchers).also { diff --git a/personalization-sdk/src/main/kotlin/com/personalization/sdk/domain/usecases/network/SendNetworkMethodUseCase.kt b/personalization-sdk/src/main/kotlin/com/personalization/sdk/domain/usecases/network/SendNetworkMethodUseCase.kt index c719b0f0..d393b3d0 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/sdk/domain/usecases/network/SendNetworkMethodUseCase.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/sdk/domain/usecases/network/SendNetworkMethodUseCase.kt @@ -1,6 +1,7 @@ package com.personalization.sdk.domain.usecases.network import com.personalization.api.OnApiCallbackListener +import com.personalization.core.internal.Core import com.personalization.sdk.data.repositories.network.NetworkRepositoryImpl import com.personalization.sdk.domain.repositories.NetworkRepository import javax.inject.Inject @@ -17,6 +18,10 @@ class SendNetworkMethodUseCase @Inject constructor( internal val queuesEvents: Boolean get() = (networkRepository as? NetworkRepositoryImpl)?.core?.isV2 == true + /** The instance's core, legacy or new; null for a repository of a test. */ + internal val core: Core? + get() = (networkRepository as? NetworkRepositoryImpl)?.core + /** * Direct query execution */ diff --git a/personalization-sdk/src/test/java/com/personalization/Rees46ConfigJavaTest.java b/personalization-sdk/src/test/java/com/personalization/Rees46ConfigJavaTest.java index 71dfaebd..d0790fd4 100644 --- a/personalization-sdk/src/test/java/com/personalization/Rees46ConfigJavaTest.java +++ b/personalization-sdk/src/test/java/com/personalization/Rees46ConfigJavaTest.java @@ -49,5 +49,16 @@ public void theDeviceIdAndTheAdvertisingIdComeLast() { assertEquals("did-from-rn", config.getDeviceId()); assertTrue(config.getSendAdvertisingId()); + assertEquals("app.rees46.ru", config.getAppDomain()); + } + + @Test + public void theAppDomainComesLast() { + Rees46Config config = new Rees46Config( + "shop", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.WARNING, null, + null, false, "app.cluster.example"); + + assertEquals("app.cluster.example", config.getAppDomain()); + assertEquals("api.rees46.ru", config.getApiDomain()); } } diff --git a/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt index b1477ed2..1934e23a 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt @@ -306,7 +306,8 @@ class BridgeInitTest { Boolean::class.javaPrimitiveType, String::class.java, String::class.java, Boolean::class.javaPrimitiveType, ) - private val newParameters = oldParameters.filterIndexed { index, _ -> index != 9 } + /** Today's constructor: without `coreV2`, with `appDomain` last. */ + private val newParameters = oldParameters.filterIndexed { index, _ -> index != 9 } + String::class.java @Test fun `apps get no way to the new core, no constructor or copy takes it and Java does not see the bridges' entry`() { @@ -314,7 +315,7 @@ class BridgeInitTest { visible.forEach { constructor -> assertEquals(newParameters.take(constructor.parameterCount), constructor.parameterTypes.toList()) } - assertEquals((1..12).toList(), visible.map { it.parameterCount }.sorted()) + assertEquals((1..13).toList(), visible.map { it.parameterCount }.sorted()) val copies = Rees46Config::class.java.methods.filter { it.name == "copy" && !it.isSynthetic } assertEquals(listOf(newParameters), copies.map { it.parameterTypes.toList() }) val bridgeEntries = Rees46::class.java.methods.filter { it.name.startsWith("initializeBridge") } diff --git a/personalization-sdk/src/test/kotlin/com/personalization/Rees46ConfigAppDomainTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/Rees46ConfigAppDomainTest.kt new file mode 100644 index 00000000..e97845c4 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/Rees46ConfigAppDomainTest.kt @@ -0,0 +1,92 @@ +package com.personalization + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * `Rees46Config.appDomain`, the host of API v3, and what apps built against 2.52, the release before it, + * still find: its constructor in the form Kotlin compiles a call with defaults, its `copy` and its + * components. + */ +class Rees46ConfigAppDomainTest { + + /** The parameters of the 2.52 constructor and `copy`. */ + private val parameters = listOf( + String::class.java, String::class.java, String::class.java, Boolean::class.javaPrimitiveType, Boolean::class.javaPrimitiveType, + Boolean::class.javaPrimitiveType, String::class.java, Boolean::class.javaPrimitiveType, LogLevel::class.java, + String::class.java, String::class.java, Boolean::class.javaPrimitiveType, + ) + + private val marker = Class.forName("kotlin.jvm.internal.DefaultConstructorMarker") + + /** The mask of a call that passes only the parameters at [given]: every other one is left to its default. */ + private fun leaving(vararg given: Int): Int = given.fold((1 shl parameters.size) - 1) { mask, index -> mask and (1 shl index).inv() } + + @Test + fun `the host of API v3 is app rees46 ru unless the config says otherwise`() { + assertEquals("app.rees46.ru", Rees46Config("shop").appDomain) + assertEquals("app.cluster.example", Rees46Config("shop", appDomain = "app.cluster.example").appDomain) + assertFalse(Rees46Config("shop") == Rees46Config("shop", appDomain = "app.cluster.example")) + assertEquals("app.cluster.example", Rees46Config("shop", appDomain = "app.cluster.example").copy(shopId = "other").appDomain) + } + + @Test + fun `the 2 52 constructor is still there in its plain form, and takes the default host`() { + val plain = Rees46Config::class.java.getConstructor(*parameters.toTypedArray()) + assertFalse(plain.isSynthetic) + + val made = plain.newInstance("shop", "api.example", "flutter", false, true, false, "TAG", false, LogLevel.DEBUG, "key", "did-1", true) + + assertEquals( + Rees46Config("shop", "api.example", "flutter", false, true, false, "TAG", false, LogLevel.DEBUG, "key", "did-1", true), + made, + ) + assertEquals("app.rees46.ru", made.appDomain) + } + + @Test + fun `the 2 52 constructor is still there in the form of a call with defaults`() { + val withDefaults = Rees46Config::class.java.getDeclaredConstructor(*(parameters + Int::class.javaPrimitiveType + marker).toTypedArray()) + assertTrue(withDefaults.isSynthetic) + + // Rees46Config("shop") as 2.52 compiled it: every parameter but the shop left to its default. + val shopOnly = withDefaults.newInstance("shop", null, null, false, false, false, null, false, null, null, null, false, leaving(0), null) + assertEquals(Rees46Config("shop"), shopOnly) + + // Rees46Config("shop", stream = "flutter", logLevel = DEBUG, deviceId = "did-1", sendAdvertisingId = true). + val some = withDefaults.newInstance("shop", null, "flutter", false, false, false, null, false, LogLevel.DEBUG, null, "did-1", true, leaving(0, 2, 8, 10, 11), null) + assertEquals(Rees46Config("shop", stream = "flutter", logLevel = LogLevel.DEBUG, deviceId = "did-1", sendAdvertisingId = true), some) + + // A Boolean passed as false where its default is true stays false. + val off = withDefaults.newInstance("shop", null, null, false, false, false, null, false, null, null, null, false, leaving(0, 3, 5, 7), null) + assertEquals(Rees46Config("shop", autoSendPushToken = false, addTrailingSlash = false, enableAutoPopupPresentation = false), off) + } + + @Test + fun `the 2 52 copy is still there in both forms, and keeps the host`() { + val config = Rees46Config("shop", appDomain = "app.cluster.example") + + val copy = Rees46Config::class.java.getMethod("copy", *parameters.toTypedArray()) + assertTrue(copy.isSynthetic) + val copied = copy.invoke(config, "other", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.DEBUG, null, null, false) + assertEquals(Rees46Config("other", logLevel = LogLevel.DEBUG, appDomain = "app.cluster.example"), copied) + + // config.copy(shopId = "other") as 2.52 compiled it. + val withDefaults = Rees46Config::class.java.getDeclaredMethod( + "copy\$default", + *(listOf(Rees46Config::class.java) + parameters + Int::class.javaPrimitiveType + Any::class.java).toTypedArray(), + ) + val copiedWithDefaults = withDefaults.invoke(null, config, "other", null, null, false, false, false, null, false, null, null, null, false, leaving(0), null) + assertEquals(config.copy(shopId = "other"), copiedWithDefaults) + } + + @Test + fun `the components of 2 52 keep their places and the host comes after them`() { + val config = Rees46Config("shop", sendAdvertisingId = true, appDomain = "app.cluster.example") + + assertEquals(true, Rees46Config::class.java.getMethod("component12").invoke(config)) + assertEquals("app.cluster.example", Rees46Config::class.java.getMethod("component13").invoke(config)) + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/ContractFixtures.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/ContractFixtures.kt index 4c72f871..fd595319 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/ContractFixtures.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/ContractFixtures.kt @@ -1,5 +1,7 @@ package com.personalization.core.internal +import com.personalization.core.SdkError +import okhttp3.mockwebserver.MockResponse import org.json.JSONArray import org.json.JSONObject @@ -8,6 +10,14 @@ import org.json.JSONObject * `src/test/resources/contract//`. Every SDK checks its implementation against the same * cases; update them by copying the new files into a folder of the new contract version. Beside them, * `logging.md` of `sdk/core`, whose table of log codes the logs are checked against. + * + * The namespaces' files (`cart.json` and those after it) are written in the fixtures' format from their files + * of `contract/` and the server's answers in `questions.md`, ahead of the contract's own files, which take + * them over as they are. `cart.json`, `notifications.json`, `stories.json`, `predict.json`, `loyalty.json`, + * `sliders.json` and `reviews.json` are the files the iOS SDK tests by. In the `expect.result` of + * `stories.json`, `predict.json`, `loyalty.json` and `sliders.json` an object lists the fields the case + * checks. `sliders.json` also holds the banner events, `tracking.bannerView` and `bannerClick` (their + * `call.namespace` says so), until the contract's `tracking.json` has them. */ internal object ContractFixtures { const val VERSION = "0" @@ -24,6 +34,37 @@ internal object ContractFixtures { private fun load(name: String): JSONObject = JSONObject(text("$name.json")) + /** The cases of `.json` that pair a server's answer with what the method returns. */ + fun answers(name: String): List = cases(name).filter { it.has("response") } + + /** The cases of `.json` that pair a call with the request it makes. */ + fun requests(name: String): List = cases(name).filter { it.has("request") } + + /** + * The server's answer of a case (`response`) for a mock server; null for `"status": null`, no answer, + * which a test makes by other means (no network). + */ + fun mockResponse(case: JSONObject): MockResponse? { + val response = case.getJSONObject("response") + if (response.isNull("status")) return null + val body = response.opt("body") + return MockResponse().setResponseCode(response.getInt("status")) + .setBody(if (body == null || body == JSONObject.NULL) "" else body.toString()) + } + + /** The [SdkError] an `error` object of a case names: `{"type": "http", "code": 404}`. */ + fun errorOf(error: JSONObject): SdkError = when (val type = error.getString("type")) { + "notInitialized" -> SdkError.NotInitialized + "shopBlocked" -> SdkError.ShopBlocked + "invalidArgument" -> SdkError.InvalidArgument(error.optString("message")) + "network" -> SdkError.Network + "timeout" -> SdkError.Timeout + "http" -> SdkError.Http(error.getInt("code"), error.optString("serverCode").ifEmpty { null }) + "decoding" -> SdkError.Decoding + "cancelled" -> SdkError.Cancelled + else -> error("unknown SdkError type $type") + } + /** * A file of the contract copied beside the fixtures as it is, such as `logging.md` of `sdk/core`: what a * test reads the contract's own tables from, instead of a copy of them in the test. diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/ContractJsonTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/ContractJsonTest.kt new file mode 100644 index 00000000..dc86339a --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/ContractJsonTest.kt @@ -0,0 +1,41 @@ +package com.personalization.core.internal + +import com.personalization.api.models.products.Product +import org.json.JSONObject +import org.junit.Assert.assertThrows +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** The fixtures' comparison of a model with `expect.result` catches what differs, and only that. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class ContractJsonTest { + + private val product = Product(id = "37", name = "Shoes", url = "https://shop.example/p/37", price = 4990.0, currency = "USD", rating = 4) + + private fun expected(json: String) = JSONObject(json) + + @Test + fun `a model equals its fixture, numbers by value, null fields left out`() { + ContractJson.assertEquals( + "product", + expected("""{"id":"37","name":"Shoes","url":"https://shop.example/p/37","price":4990,"currency":"USD","rating":4,"isNew":false,"brand":null}"""), + ContractJson.of(product), + ) + } + + @Test + fun `a different value, a missing field and an extra field each fail`() { + val base = """"id":"37","name":"Shoes","url":"https://shop.example/p/37","currency":"USD","isNew":false""" + listOf( + """{$base,"price":4990.5,"rating":4}""", + """{$base,"price":4990}""", + """{$base,"price":4990,"rating":4,"brand":"Nike"}""", + """{$base,"price":4990,"rating":4,"categories":[]}""", + ).forEach { json -> + assertThrows(json, AssertionError::class.java) { ContractJson.assertEquals("product", expected(json), ContractJson.of(product)) } + } + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/CorePushTokensTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/CorePushTokensTest.kt index ea678bc9..9b2743c3 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/CorePushTokensTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/CorePushTokensTest.kt @@ -221,6 +221,28 @@ class CorePushTokensTest { assertEquals(2, sent.size) } + @Test + fun `a 2xx answer that says error is decoding and gives the week back, so the token goes again`() { + val tokens = tokens() + val heard = Heard() + tokens.set("t1", PushProvider.FCM, heard) + run() + answers.removeAt(0).onSuccess(JSONObject().put("status", "error").put("message", "Something went wrong")) + run() + + assertEquals(listOf("error:-1"), heard.calls) + assertEquals(listOf(SdkError.Decoding), heard.errors.toList()) + assertTrue(logged.any { it.code == LogCodes.PUSH_TOKEN_FAILED && it.context["error"] == "decoding" }) + assertTrue(logged.none { it.code == LogCodes.PUSH_TOKEN_SENT }) + + val again = Heard() + tokens.set("t1", PushProvider.FCM, again) + run() + assertEquals("the week was not taken", 2, sent.size) + ok() + assertEquals(listOf("success"), again.calls) + } + @Test fun `setPushToken waits for ready, says success without a request inside the week, and refuses an empty token or a refused shop`() { val tokens = tokens() diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/NamespaceCallsTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/NamespaceCallsTest.kt new file mode 100644 index 00000000..b33e3c24 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/NamespaceCallsTest.kt @@ -0,0 +1,370 @@ +package com.personalization.core.internal + +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import com.personalization.sdk.domain.models.NetworkMethod +import com.personalization.sdk.domain.repositories.UserSettingsRepository +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.SocketPolicy +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +/** + * The path of the namespaces' methods on the new core: one request with a result, its answer read into a + * model or an [SdkError] of the contract, the legacy core refused without a request, and the form with a + * [CompletionListener] ending once on the main thread. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class NamespaceCallsTest { + + private val server = MockWebServer() + private val connectivity = FakeConnectivity(connected = true) + private val settings = mockk(relaxed = true) { + every { getShopId() } returns SHOP + every { getDid() } returns "did-1" + every { getSid() } returns "sid-1" + every { getStream() } returns "android" + every { getSegmentForABTesting() } returns "A" + } + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val main = HeldMain() + private var core: Core? = null + private val calls = NamespaceCalls(core = { core }, dispatchers = { CoreDispatchers(main = { main }) }, shopId = { SHOP }) + + @Before + fun setUp() { + SdkLogs.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.register(SHOP, LogLevel.DEBUG, "SDK") + SdkLogs.handler = SdkLogHandler { logged += it } + server.start() + core = newCore() + } + + @After + fun tearDown() { + core?.release() + server.close() + SdkLogs.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + /** Puts [next] in the place of the current core, which is released. */ + private fun replaceCore(next: Core?) { + core?.release() + core = next + } + + private fun newCore(timeouts: CoreTimeouts = CoreTimeouts(), init: CoreInit? = null): CoreV2 { + val client = CoreHttpClient({ server.url("/").toString() }, settings, connectivity, SHOP, timeouts = timeouts) + return CoreV2(client, SHOP).also { + it.init = init ?: startedCoreInit(ApplicationProvider.getApplicationContext(), settings, connectivity, SHOP) + } + } + + /** Reads the answer as a list of `id`s under `items`; null when there is no such list. */ + private fun ids(body: Any?): List? = + (body as? JSONObject)?.arrayOrNull("items")?.mapObjects { it.nonBlankStringOrNull("id") } + + private fun get(read: (Any?) -> List? = ::ids): List = runBlocking { + withTimeout(10_000) { calls.request(CALL, NetworkMethod.GET(PATH), JSONObject().put("limit", 2), read = read) } + } + + private fun failure(read: (Any?) -> List? = ::ids): SdkException = try { + get(read) + fail("expected SdkException") + throw AssertionError() + } catch (e: SdkException) { + e + } + + // The request and its answer. + + @Test + fun `a 2xx answer is read into the method's value, and the request carries the method's and the common fields`() { + server.enqueue(MockResponse().setBody("""{"items":[{"id":"37"},{"id":38},{"name":"no id"}],"unknown":true}""")) + + assertEquals(listOf("37", "38"), get()) + + val url = server.takeRequest(5, TimeUnit.SECONDS)!!.requestUrl!! + assertEquals("/$PATH", url.encodedPath) + assertEquals( + mapOf("limit" to "2", "shop_id" to SHOP, "did" to "did-1", "sid" to "sid-1", "seance" to "sid-1", "segment" to "A", "stream" to "android"), + url.queryParameterNames.associateWith { url.queryParameter(it) }, + ) + } + + @Test + fun `an answer without a body reaches the reader as null, an empty object as itself`() { + val bodies = LinkedBlockingQueue() + server.enqueue(MockResponse().setResponseCode(204)) + server.enqueue(MockResponse().setBody("{}")) + + get { body -> bodies += body ?: "none"; emptyList() } + get { body -> bodies += body ?: "none"; emptyList() } + + assertEquals("none", bodies.poll()) + assertEquals("{}", bodies.poll()?.toString()) + } + + @Test + fun `an answer outside 2xx is http with its code and no server code, and nothing repeats it`() { + listOf(400, 402, 403, 404, 422, 500, 503).forEach { code -> + server.enqueue(MockResponse().setResponseCode(code).setBody("""{"status":"error","message":"Client not found"}""")) + + assertEquals(SdkError.Http(code), failure().error) + } + assertEquals(7, server.requestCount) + } + + @Test + fun `a 2xx answer that does not read into the model is decoding, logged without the server's text`() { + server.enqueue(MockResponse().setBody("""{"status":"error","message":"secret@example.com is not allowed"}""")) + server.enqueue(MockResponse().setBody("maintenance")) + server.enqueue(MockResponse().setBody("""[1,2]""")) + server.enqueue(MockResponse().setBody("""{"items":[]}""")) + + repeat(3) { assertEquals(SdkError.Decoding, failure().error) } + assertEquals(SdkError.Decoding, failure { throw IllegalStateException("a bug of the reader") }.error) + + val decoding = logged.filter { it.code == LogCodes.DECODING_FAILED } + assertTrue(decoding.isNotEmpty()) + assertTrue(decoding.all { it.level == LogLevel.WARNING }) + assertTrue(decoding.any { it.context["call"] == CALL && it.context["path"] == PATH }) + assertTrue(logged.none { "secret@example.com" in it.message || "secret@example.com" in it.context.toString() }) + } + + @Test + fun `without a network the call fails at once with network and sends nothing`() { + connectivity.set(false) + + assertEquals(SdkError.Network, failure().error) + assertEquals(0, server.requestCount) + } + + @Test + fun `an answer that does not come within the read timeout is timeout`() { + replaceCore(newCore(CoreTimeouts(readMs = 300))) + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + + val started = System.nanoTime() + assertEquals(SdkError.Timeout, failure().error) + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started) < 5_000) + assertEquals(1, server.requestCount) + } + + @Test + fun `a read timeout of the method's own holds for its request`() { + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + + val started = System.nanoTime() + val error = try { + runBlocking { calls.request(CALL, NetworkMethod.GET(PATH), readTimeoutMs = 300, read = ::ids) } + null + } catch (e: SdkException) { + e.error + } + + assertEquals(SdkError.Timeout, error) + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started) < 5_000) + } + + @Test + fun `an instance not ready within the read timeout fails with timeout and sends nothing`() { + // No /init is ever set: the instance never gets ready. + val client = CoreHttpClient({ server.url("/").toString() }, settings, connectivity, SHOP, timeouts = CoreTimeouts(readMs = 300)) + replaceCore(CoreV2(client, SHOP)) + + assertEquals(SdkError.Timeout, failure().error) + assertEquals(0, server.requestCount) + } + + @Test + fun `a refused shop fails with shopBlocked and sends nothing`() { + val noDid = mockk(relaxed = true) { + every { getShopId() } returns REFUSED_SHOP + every { getDid() } returns "" + } + val init = startedCoreInit(ApplicationProvider.getApplicationContext(), noDid, connectivity, REFUSED_SHOP) { + HttpResult.Failure(SdkError.Http(402)) + } + replaceCore(newCore(init = init)) + + assertEquals(SdkError.ShopBlocked, failure().error) + assertEquals(0, server.requestCount) + } + + // The core. + + @Test + fun `on the legacy core the call fails with notInitialized, says why and sends nothing`() { + replaceCore(LegacyCore(settings) { server.url("/").toString() }) + + val error = failure() + + assertEquals(SdkError.NotInitialized, error.error) + assertEquals("$CALL runs on the new core only: start the shop with Rees46.initializeBridge", error.message) + val line = logged.single { it.code == LogCodes.CORE_FLAG_MISMATCH } + assertEquals(LogLevel.WARNING, line.level) + assertEquals(mapOf("call" to CALL), line.context) + assertEquals(0, server.requestCount) + } + + @Test + fun `an instance not initialized or released fails with notInitialized and sends nothing`() { + val released = core + core = null + assertEquals(SdkError.NotInitialized, failure().error) + + core = released + released?.release() + assertEquals(SdkError.NotInitialized, failure().error) + + assertEquals(0, server.requestCount) + assertTrue(logged.none { it.code == LogCodes.CORE_FLAG_MISMATCH }) + } + + @Test + fun `release ends a request in flight with cancelled`() { + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + val outcome = runBlocking(Dispatchers.IO) { + val call = async { runCatching { calls.request(CALL, NetworkMethod.GET(PATH), read = ::ids) } } + server.takeRequest(5, TimeUnit.SECONDS) + core?.release() + withTimeout(5_000) { call.await() } + } + + assertEquals(SdkError.Cancelled, (outcome.exceptionOrNull() as SdkException).error) + assertTrue(logged.any { it.code == LogCodes.REQUEST_CANCELLED && it.context["path"] == PATH }) + } + + @Test + fun `cancelling the caller cancels the request and the caller gets its own cancellation`() { + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + val thrown = LinkedBlockingQueue() + runBlocking(Dispatchers.IO) { + val call = async { + try { + calls.request(CALL, NetworkMethod.GET(PATH), read = ::ids) + } catch (e: Throwable) { + thrown += e + throw e + } + } + server.takeRequest(5, TimeUnit.SECONDS) + call.cancel() + withTimeout(5_000) { call.join() } + } + + val error = thrown.poll(5, TimeUnit.SECONDS) + // The caller's own cancellation, not an SdkException. + assertTrue("$error", error is CancellationException) + assertTrue(logged.none { it.code == LogCodes.REQUEST_CANCELLED }) + // The instance goes on: the next call is answered. + server.enqueue(MockResponse().setBody("""{"items":[{"id":"1"}]}""")) + assertEquals(listOf("1"), get()) + } + + // The form with a listener. + + private fun complete(): List>, Boolean>> { + val ends = CopyOnWriteArrayList>, Boolean>>() + calls.complete(CompletionListener { result -> ends += result to (Looper.myLooper() == Looper.getMainLooper()) }) { + calls.request(CALL, NetworkMethod.GET(PATH), read = ::ids) + } + // Handed to the main thread: run it here, on the test's main thread, then wait for any second end. + while (ends.isEmpty() && main.runNext()) Unit + main.runNext(timeoutMs = 200) + return ends + } + + @Test + fun `the listener hears the value or the error once, on the main thread`() { + server.enqueue(MockResponse().setBody("""{"items":[{"id":"37"}]}""")) + server.enqueue(MockResponse().setResponseCode(404)) + + assertEquals(listOf(SdkResult.Success(listOf("37")) to true), complete()) + assertEquals(listOf(SdkResult.Failure(SdkError.Http(404)) to true), complete()) + + replaceCore(LegacyCore(settings) { server.url("/").toString() }) + assertEquals(listOf(SdkResult.Failure(SdkError.NotInitialized) to true), complete()) + } + + @Test + fun `release ends the listener's request with cancelled`() { + server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + val ends = CopyOnWriteArrayList>>() + calls.complete(CompletionListener { ends += it }) { calls.request(CALL, NetworkMethod.GET(PATH), read = ::ids) } + server.takeRequest(5, TimeUnit.SECONDS) + + core?.release() + while (ends.isEmpty() && main.runNext()) Unit + + assertEquals(listOf>>(SdkResult.Failure(SdkError.Cancelled)), ends) + } + + @Test + fun `a listener that throws is logged once and not called again`() { + server.enqueue(MockResponse().setBody("""{"items":[]}""")) + var heard = 0 + calls.complete(CompletionListener> { heard++; throw IllegalStateException("the app's bug") }) { + calls.request(CALL, NetworkMethod.GET(PATH), read = ::ids) + } + + while (heard == 0 && main.runNext()) Unit + main.runNext(timeoutMs = 200) + + assertEquals(1, heard) + assertEquals(1, logged.count { it.code == LogCodes.CALLBACK_FAILED && it.level == LogLevel.ERROR }) + } + + @Test + fun `a failure nobody expected still ends the listener's call`() { + val ends = CopyOnWriteArrayList>() + calls.complete(CompletionListener { ends += it }) { throw IllegalStateException("a bug") } + + while (ends.isEmpty() && main.runNext()) Unit + + assertEquals(1, ends.size) + assertTrue(ends.single() is SdkResult.Failure) + assertTrue(logged.any { it.code == LogCodes.SDK_LOG && it.level == LogLevel.ERROR }) + } + + private companion object { + const val SHOP = "namespace-shop" + const val REFUSED_SHOP = "namespace-refused-shop" + const val CALL = "test.get" + const val PATH = "products/test" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/NamespaceFixtures.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/NamespaceFixtures.kt new file mode 100644 index 00000000..875c06c6 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/NamespaceFixtures.kt @@ -0,0 +1,317 @@ +package com.personalization.core.internal + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.logs.SdkLogs +import com.personalization.sdk.domain.repositories.UserSettingsRepository +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import java.lang.reflect.Modifier +import java.util.concurrent.TimeUnit + +/** + * A namespace's methods against the contract's fixtures (`contract/0/.json`), over a new core + * that talks to a mock server: the request each call makes, the `invalidArgument` a call with wrong + * arguments ends with, without a request, and what it makes of each answer. A test class starts it in + * `@Before` and stops it in `@After`, builds its namespace over [calls], and says how to run a fixture's + * call ([Invoke]). A file that holds the calls of more than one namespace (`sliders.json` with the banner + * events) is checked one `namespace` at a time. The mock server stands for both hosts, the API's and that + * of API v3; [timeouts] are the client's. + */ +internal class NamespaceFixtures(private val shop: String, private val timeouts: CoreTimeouts = CoreTimeouts()) { + + /** Runs the method [method] of the namespace with the fixture's [args]; its value is what the method returns. */ + fun interface Invoke { + suspend fun invoke(method: String, args: JSONObject): Any? + } + + /** A method's result as JSON values in the contract's names: maps, lists, strings, numbers, booleans, null. */ + fun interface Json { + fun of(value: Any?): Any? + } + + val server = MockWebServer() + private val connectivity = FakeConnectivity(connected = true) + private val settings = mockk(relaxed = true) { + every { getShopId() } returns shop + every { getDid() } returns "did-1" + every { getSid() } returns "sid-1" + every { getStream() } returns "android" + every { getSegmentForABTesting() } returns "B" + } + private lateinit var core: CoreV2 + + /** The path the namespaces take, over the started core. */ + lateinit var calls: NamespaceCalls + private set + + fun start(context: Context = ApplicationProvider.getApplicationContext()) { + SdkLogs.reset() + server.start() + val client = CoreHttpClient( + { server.url("/").toString() }, settings, connectivity, shop, + timeouts = timeouts, appUrl = { server.url("/").toString() }, + ) + core = CoreV2(client, shop).also { it.init = startedCoreInit(context, settings, connectivity, shop) } + calls = NamespaceCalls(core = { core }, dispatchers = { CoreDispatchers.DEFAULT }, shopId = { shop }) + } + + fun stop() { + core.release() + server.close() + SdkLogs.reset() + } + + /** The outcome of [block], a call of a method's suspending form. */ + fun outcome(block: suspend () -> Any?): SdkResult = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { block() } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + /** The outcome of a [case]'s call, made with [invoke]. */ + private fun outcome(case: JSONObject, invoke: Invoke): SdkResult { + val call = case.getJSONObject("call") + return outcome { invoke.invoke(call.getString("method"), call.optJSONObject("args") ?: JSONObject()) } + } + + /** The cases of [file] with [kind] (`request`, `error`, `response`); of [namespace] only, when it is given. */ + private fun cases(file: String, kind: String, namespace: String?): List = + ContractFixtures.cases(file).filter { case -> + case.has(kind) && (namespace == null || case.getJSONObject("call").getString("namespace") == namespace) + } + + /** + * Every case of [file] that pairs a call with a request: the call sends that method, path and its own + * fields — the query of a `GET`, the body of a `POST` — and nothing of its own beside them; the common + * fields the core adds are there too. [answer] is what the server says to each request. Returns how many + * cases it checked. + */ + fun checkRequests( + file: String, + invoke: Invoke, + namespace: String? = null, + answer: () -> MockResponse = { MockResponse().setBody("{}") }, + ): Int { + val cases = cases(file, "request", namespace) + assertTrue("$file has no request cases", cases.isNotEmpty()) + cases.forEach { case -> + val name = case.getString("name") + server.enqueue(answer()) + outcome(case, invoke) + val recorded = server.takeRequest(5, TimeUnit.SECONDS) ?: throw AssertionError("$name sent no request") + checkRequest(name, case.getJSONObject("request"), recorded) + } + return cases.size + } + + /** Every case of [file] that pairs a call with an error fails with it and sends nothing. Returns how many it checked. */ + fun checkErrors(file: String, invoke: Invoke, namespace: String? = null): Int { + val cases = cases(file, "error", namespace).filter { !it.has("response") } + cases.forEach { case -> + val name = case.getString("name") + assertSameError(name, ContractFixtures.errorOf(case.getJSONObject("error")), outcome(case, invoke)) + assertNull("$name sent a request", server.takeRequest(100, TimeUnit.MILLISECONDS)) + } + return cases.size + } + + /** + * Every case of [file] that pairs an answer with what the method returns: the call fails with + * `expect.error`, or its value equals `expect.result` — as [ContractJson] writes it, or, when the test + * gives [json], as that writes it, with an object of `expect.result` listing only the fields the case + * checks ([assertMatches]). No answer (`"status": null`) is a request without a network. Returns how + * many cases it checked. + */ + fun checkAnswers(file: String, invoke: Invoke, namespace: String? = null, json: Json? = null): Int { + val cases = cases(file, "response", namespace) + assertTrue("$file has no answer cases", cases.isNotEmpty()) + cases.forEach { case -> + val name = case.getString("name") + val response = ContractFixtures.mockResponse(case) + connectivity.set(response != null) + response?.let(server::enqueue) + val expect = case.getJSONObject("expect") + + val outcome = outcome(case, invoke) + + if (expect.has("result")) { + if (outcome !is SdkResult.Success) fail("$name: $outcome") + val value = (outcome as SdkResult.Success).value + if (json == null) { + ContractJson.assertEquals(name, expect.opt("result"), ContractJson.of(value)) + } else { + assertMatches(name, normalize(expect.get("result")), normalize(json.of(value))) + } + } else { + assertSameError(name, ContractFixtures.errorOf(expect.getJSONObject("error")), outcome) + } + response?.let { server.takeRequest(5, TimeUnit.SECONDS) } + connectivity.set(true) + } + return cases.size + } + + private fun checkRequest(name: String, expected: JSONObject, recorded: RecordedRequest) { + assertEquals(name, expected.getString("method"), recorded.method) + val url = recorded.requestUrl!! + assertEquals(name, "/" + expected.getString("path"), url.encodedPath) + val own: Map = if (recorded.method == "GET") { + assertEquals("$name: common fields", COMMON_FIELDS, url.queryParameterNames intersect COMMON_FIELDS) + // A list goes as its key repeated (`promo_codes[]=A&promo_codes[]=B`): the fixtures write its values as a list. + (url.queryParameterNames - COMMON_FIELDS).associateWith { key -> + url.queryParameterValues(key).let { values -> if (key.endsWith("[]")) values else values.single() } + } + } else { + val body = JSONObject(recorded.body.readUtf8()) + val common = expected.optJSONArray("commonFields")?.let { array -> List(array.length()) { array.getString(it) }.toSet() } ?: COMMON_FIELDS + assertEquals("$name: common fields", common, body.keys().asSequence().toSet() intersect COMMON_FIELDS) + (body.keys().asSequence().toSet() - COMMON_FIELDS).associateWith { body.get(it) } + } + val fields = expected.optJSONObject(if (recorded.method == "GET") "query" else "body") ?: JSONObject() + assertEquals("$name: fields", fields.keys().asSequence().toSet(), own.keys) + fields.keys().forEach { key -> + ContractJson.assertEquals("$name: $key", fields.get(key), ContractJson.of(own[key])) + } + } + + /** The same error; `invalidArgument` by its kind only, since its message is the platform's. */ + private fun assertSameError(name: String, expected: SdkError, outcome: SdkResult) { + if (expected is SdkError.InvalidArgument) { + assertTrue("$name: $outcome", outcome is SdkResult.Failure && outcome.error is SdkError.InvalidArgument) + } else { + assertEquals(name, SdkResult.Failure(expected), outcome) + } + } + + companion object { + val COMMON_FIELDS = setOf("shop_id", "did", "sid", "seance", "segment", "stream") + + /** JSON and Kotlin values alike as maps, lists, strings, booleans, doubles and null: one number type, so `2` is `2.0`. */ + fun normalize(value: Any?): Any? = when (value) { + null, JSONObject.NULL -> null + is JSONObject -> value.keys().asSequence().associateWith { normalize(value.get(it)) } + is JSONArray -> (0 until value.length()).map { normalize(value.get(it)) } + is Map<*, *> -> value.entries.associate { (key, item) -> key.toString() to normalize(item) } + is Iterable<*> -> value.map(::normalize) + is Number -> value.toDouble() + else -> value + } + + /** + * [actual] matches [expected] as the fixtures read `expect.result`: an object lists the fields the case + * checks, and each must be there with a matching value; a list has as many items, each matching in turn; + * anything else is equal, `null` included. [at] is where in the result, for the message. + */ + fun assertMatches(name: String, expected: Any?, actual: Any?, at: String = "result") { + when (expected) { + is Map<*, *> -> { + assertTrue("$name: $at is $actual, not an object", actual is Map<*, *>) + val fields = actual as Map<*, *> + expected.forEach { (key, value) -> + assertTrue("$name: $at has no $key", fields.containsKey(key)) + assertMatches(name, value, fields[key], "$at.$key") + } + } + is List<*> -> { + assertTrue("$name: $at is $actual, not a list", actual is List<*>) + val items = actual as List<*> + assertEquals("$name: the size of $at", expected.size, items.size) + expected.forEachIndexed { index, item -> assertMatches(name, item, items[index], "$at[$index]") } + } + else -> assertEquals("$name: $at", expected, actual) + } + } + } +} + +/** + * The namespaces' models as the fixtures write them: each property under its own name, which is the + * contract's; a null property is left out; a list is an array, a map an object. Equality of two such + * values compares numbers by value, so `19990` equals `19990.0`. + */ +internal object ContractJson { + + fun of(value: Any?): Any? = when (value) { + null, JSONObject.NULL -> null + is String, is Boolean, is Number, is JSONObject, is JSONArray -> value + // An enum value by the contract's name: FEMALE is `female`, INSTANT_SEARCH is `instantSearch`. + is Enum<*> -> value.name.lowercase().split('_').let { words -> words.first() + words.drop(1).joinToString("") { it.replaceFirstChar(Char::uppercase) } } + is List<*> -> JSONArray().apply { value.forEach { put(of(it) ?: JSONObject.NULL) } } + is Map<*, *> -> JSONObject().apply { value.forEach { (key, item) -> of(item)?.let { put(key.toString(), it) } } } + // A method that returns nothing: `"result": null`. + is Unit -> null + else -> JSONObject().apply { + value.javaClass.declaredFields + .filter { !Modifier.isStatic(it.modifiers) && !it.isSynthetic } + .forEach { field -> + field.isAccessible = true + of(field.get(value))?.let { put(field.name, it) } + } + } + } + + fun assertEquals(name: String, expected: Any?, actual: Any?) { + val want = expected.takeUnless { it == JSONObject.NULL } + val got = actual.takeUnless { it == JSONObject.NULL } + when { + want == null || got == null -> org.junit.Assert.assertEquals(name, want, got) + want is Number && got is Number -> org.junit.Assert.assertEquals(name, want.toDouble(), got.toDouble(), 0.0) + want is JSONObject && got is JSONObject -> { + val wantKeys = want.keys().asSequence().filter { !want.isNull(it) }.toSet() + val gotKeys = got.keys().asSequence().filter { !got.isNull(it) }.toSet() + org.junit.Assert.assertEquals("$name: keys", wantKeys.sorted(), gotKeys.sorted()) + wantKeys.forEach { key -> assertEquals("$name.$key", want.get(key), got.get(key)) } + } + want is JSONArray && got is JSONArray -> { + org.junit.Assert.assertEquals("$name: size", want.length(), got.length()) + for (index in 0 until want.length()) assertEquals("$name[$index]", want.get(index), got.get(index)) + } + else -> org.junit.Assert.assertEquals(name, want.toString(), got.toString()) + } + } +} + +/* Reading a fixture's `args`: a key that is missing or `null` is null. */ + +internal fun JSONObject.argString(key: String): String? = if (isNull(key)) null else getString(key) + +internal fun JSONObject.argInt(key: String): Int? = if (isNull(key)) null else getInt(key) + +internal fun JSONObject.argLong(key: String): Long? = if (isNull(key)) null else getLong(key) + +internal fun JSONObject.argDouble(key: String): Double? = if (isNull(key)) null else getDouble(key) + +internal fun JSONObject.argBoolean(key: String): Boolean? = if (isNull(key)) null else getBoolean(key) + +internal fun JSONObject.argStrings(key: String): List? = + optJSONArray(key)?.let { array -> List(array.length()) { array.getString(it) } } + +/** A map of strings to lists of strings, such as `filters`. */ +internal fun JSONObject.argStringLists(key: String): Map>? = optJSONObject(key)?.let { map -> + map.keys().asSequence().associateWith { name -> map.getJSONArray(name).let { array -> List(array.length()) { array.getString(it) } } } +} + +/** A free-form map of a fixture's `args` as plain Kotlin values: maps, lists, strings, numbers, booleans and null. */ +internal fun JSONObject.argMap(key: String): Map? = optJSONObject(key)?.let { plainArg(it) as Map } + +private fun plainArg(value: Any?): Any? = when (value) { + null, JSONObject.NULL -> null + is JSONObject -> value.keys().asSequence().associateWith { plainArg(value.opt(it)) } + is JSONArray -> List(value.length()) { plainArg(value.opt(it)) } + else -> value +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/PushHubTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/PushHubTest.kt index 1ab40a21..48a1df97 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/PushHubTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/PushHubTest.kt @@ -71,6 +71,28 @@ class PushHubTest { assertEquals(listOf("second:TAKEN", "third:PARKED"), retried) } + @Test + fun `a parked repeat hears it was a repeat once the first is accepted, and only then`() { + val repeats = mutableListOf() + reserve("first") + PushHub.reserve(SHOP, PushEvent.CLICKED, "m-1", repeat = { repeats += "second" }) { retried += "second" } + + PushHub.confirm(SHOP, PushEvent.CLICKED, "m-1") + PushHub.confirm(SHOP, PushEvent.CLICKED, "m-1") + + assertEquals("once", listOf("second"), repeats) + assertEquals(emptyList(), retried) + + // Released instead: the repeat tries again and tells its own end; it is not told it was a repeat. + PushHub.reserve(SHOP, PushEvent.OPENED, "m-2") {} + PushHub.reserve(SHOP, PushEvent.OPENED, "m-2", repeat = { repeats += "opened" }) { retried += "opened" } + PushHub.release(SHOP, PushEvent.OPENED, "m-2") + PushHub.confirm(SHOP, PushEvent.OPENED, "m-2") + + assertEquals(listOf("second"), repeats) + assertEquals(listOf("opened"), retried) + } + private companion object { const val SHOP = "hub-shop" } diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/TolerantJsonTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/TolerantJsonTest.kt new file mode 100644 index 00000000..c3c0198a --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/TolerantJsonTest.kt @@ -0,0 +1,122 @@ +package com.personalization.core.internal + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The answers are read as the contract asks: missing and `null` are null, numbers may come as strings and + * strings as numbers, a value of the wrong kind is null, and an unknown value of a closed set is null. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class TolerantJsonTest { + + private val answer = JSONObject( + """ + { + "text": "37", "number": 37, "whole": 37.0, "fraction": 999.5, "big": 9007199254740993, + "textNumber": " 12 ", "textFraction": "2.5", "textWhole": "3.0", "blank": " ", "empty": "", + "nothing": null, "yes": true, "no": false, "one": 1, "zero": 0, "textYes": "TRUE", "textNo": "0", + "object": { "a": 1 }, "array": [ 1, "2", null, { "id": "x" }, 3.5, [ ] ], "huge": 1e300 + } + """.trimIndent() + ) + + @Test + fun `missing fields and null are null whatever the type asked`() { + listOf("absent", "nothing").forEach { key -> + assertNull(answer.valueOrNull(key)) + assertNull(answer.stringOrNull(key)) + assertNull(answer.intOrNull(key)) + assertNull(answer.longOrNull(key)) + assertNull(answer.doubleOrNull(key)) + assertNull(answer.booleanOrNull(key)) + assertNull(answer.objectOrNull(key)) + assertNull(answer.arrayOrNull(key)) + } + } + + @Test + fun `a string may come as a number, a whole one without a fraction`() { + assertEquals("37", answer.stringOrNull("text")) + assertEquals("37", answer.stringOrNull("number")) + assertEquals("37", answer.stringOrNull("whole")) + assertEquals("999.5", answer.stringOrNull("fraction")) + assertEquals("true", answer.stringOrNull("yes")) + assertNull(answer.stringOrNull("object")) + assertNull(answer.stringOrNull("array")) + assertEquals("", answer.stringOrNull("empty")) + assertNull(answer.nonBlankStringOrNull("empty")) + assertNull(answer.nonBlankStringOrNull("blank")) + assertEquals("37", answer.nonBlankStringOrNull("number")) + } + + @Test + fun `a number may come as a string, and a whole number is only a whole one`() { + assertEquals(37, answer.intOrNull("number")) + assertEquals(37, answer.intOrNull("whole")) + assertEquals(37, answer.intOrNull("text")) + assertEquals(12, answer.intOrNull("textNumber")) + assertEquals(3, answer.intOrNull("textWhole")) + assertNull(answer.intOrNull("fraction")) + assertNull(answer.intOrNull("textFraction")) + assertNull(answer.intOrNull("big")) + assertEquals(9007199254740993L, answer.longOrNull("big")) + assertNull(answer.intOrNull("yes")) + assertNull(answer.intOrNull("blank")) + + assertEquals(999.5, answer.doubleOrNull("fraction")!!, 0.0) + assertEquals(2.5, answer.doubleOrNull("textFraction")!!, 0.0) + assertEquals(37.0, answer.doubleOrNull("number")!!, 0.0) + assertEquals(1e300, answer.doubleOrNull("huge")!!, 0.0) + assertNull(answer.longOrNull("huge")) + assertNull(answer.doubleOrNull("object")) + } + + @Test + fun `a boolean may come as a string or as 1 and 0`() { + assertEquals(true, answer.booleanOrNull("yes")) + assertEquals(false, answer.booleanOrNull("no")) + assertEquals(true, answer.booleanOrNull("one")) + assertEquals(false, answer.booleanOrNull("zero")) + assertEquals(true, answer.booleanOrNull("textYes")) + assertEquals(false, answer.booleanOrNull("textNo")) + assertNull(answer.booleanOrNull("number")) + assertNull(answer.booleanOrNull("text")) + } + + @Test + fun `objects and arrays are read only as what they are`() { + assertEquals(1, answer.objectOrNull("object")?.intOrNull("a")) + assertNull(answer.objectOrNull("array")) + assertNull(answer.arrayOrNull("object")) + assertEquals(6, answer.arrayOrNull("array")?.length()) + } + + @Test + fun `an array keeps the elements it can read and leaves out the others`() { + val array = answer.getJSONArray("array") + + assertEquals(listOf("x"), array.mapObjects { it.stringOrNull("id") }) + assertEquals(listOf("1", "2", "3.5"), array.strings()) + assertEquals(emptyList(), JSONArray().strings()) + assertEquals(emptyList(), JSONArray("[{}, {}]").mapObjects { it.stringOrNull("id") }) + } + + @Test + fun `an unknown value of a closed set is null, not an error`() { + val values = listOf(Kind.INSTANT_SEARCH, Kind.DYNAMIC) + + assertEquals(Kind.INSTANT_SEARCH, valueOfWire("instant_search", values) { it.wire }) + assertNull(valueOfWire("agent_search", values) { it.wire }) + assertNull(valueOfWire(null, values) { it.wire }) + } + + private enum class Kind(val wire: String) { INSTANT_SEARCH("instant_search"), DYNAMIC("dynamic") } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/StoriesPredictLoyaltySlidersTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/StoriesPredictLoyaltySlidersTest.kt new file mode 100644 index 00000000..9d0c26fb --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/StoriesPredictLoyaltySlidersTest.kt @@ -0,0 +1,303 @@ +package com.personalization.features + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.SdkRegistry +import com.personalization.api.models.loyalty.LoyaltyLevel +import com.personalization.api.models.loyalty.LoyaltyMember +import com.personalization.api.models.loyalty.LoyaltyPromotion +import com.personalization.api.models.loyalty.LoyaltyRewardType +import com.personalization.api.models.loyalty.LoyaltyStatus +import com.personalization.api.models.predict.PurchaseProbability +import com.personalization.api.models.sliders.Slider +import com.personalization.api.models.sliders.SliderBanner +import com.personalization.api.models.stories.StoriesBlock +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.HeldMain +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue + +/** + * `sdk.stories`, `sdk.predict`, `sdk.loyalty` and `sdk.sliders` as a bridge calls them: on the new core + * they ask the server and answer in both forms; on the legacy core, where apps run, every method fails + * with `notInitialized`, sends nothing and says why in the log. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class StoriesPredictLoyaltySlidersTest { + + private lateinit var context: Context + private val server = MockWebServer() + private val paths = LinkedBlockingQueue() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val threads = TrackingThreads() + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.requestUrl?.encodedPath?.removePrefix("/") ?: return MockResponse().setResponseCode(400) + paths += path + return MockResponse().setBody(ANSWERS[path] ?: "{}") + } + } + server.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + server.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + private fun config() = Rees46Config( + shopId = SHOP, + apiDomain = server.url("/").toString().trimEnd('/'), + // `predict` asks API v3: the same server stands for the host of the shop's account. + appDomain = server.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + + private fun awaitState(sdk: SDK, state: SdkState) = runBlocking { + withTimeout(5_000) { sdk.instanceState.changes.first { it == state } } + } + + private fun outcome(block: suspend () -> T): SdkResult = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { block() } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + /** The paths the server got, after the calls so far had time to arrive. */ + private fun sent(): List { + threads.awaitIdle() + Thread.sleep(200) + return generateSequence { paths.poll() }.toList() + } + + /** An instance of [coreV2]'s core whose listener forms end on [main], which the test runs. */ + private fun sdk(main: HeldMain, coreV2: Boolean): SDK { + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } + sdk.initializeWith(context, config(), coreV2 = coreV2) + awaitState(sdk, SdkState.READY) + return sdk + } + + /** One method of the four namespaces, in its two forms: [suspending] and the one ending in [listener]. */ + private class Method( + val call: String, + val path: String, + val suspending: suspend (SDK) -> Any?, + val listener: (SDK, CompletionListener) -> Unit, + ) + + private val methods = listOf( + Method("stories.get", "stories/main", { it.stories.get("main") }, { sdk, l -> sdk.stories.get("main", l.of()) }), + Method("predict.getProbabilityToPurchase", "api/v3/cdp/users/probability-to-purchase", { it.predict.getProbabilityToPurchase() }, + { sdk, l -> sdk.predict.getProbabilityToPurchase(l.of()) }), + Method("loyalty.join", "loyalty/members/join", { it.loyalty.join("79991234567") }, + { sdk, l -> sdk.loyalty.join("79991234567", null, null, null, null, l.of()) }), + Method("loyalty.getStatus", "loyalty/members/status", { it.loyalty.getStatus("79991234567") }, + { sdk, l -> sdk.loyalty.getStatus("79991234567", l.of()) }), + Method("loyalty.getPromotions", "loyalty/promos/for-client", { it.loyalty.getPromotions() }, + { sdk, l -> sdk.loyalty.getPromotions(null, null, null, null, l.of()) }), + Method("sliders.get", "slider", { it.sliders.get("home") }, { sdk, l -> sdk.sliders.get("home", null, null, l.of()) }), + ) + + /** A listener of any result as one of [T]. */ + @Suppress("UNCHECKED_CAST") + private fun CompletionListener.of(): CompletionListener = this as CompletionListener + + @Test + fun `a bridge's instance gets each namespace's answer from the server`() { + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + + val results = methods.map { method -> outcome { method.suspending(sdk) } } + + assertEquals(EXPECTED.map { SdkResult.Success(it) }, results) + assertTrue(sent().containsAll(methods.map { it.path })) + } + + @Test + fun `the forms with a listener end once each, on the main thread`() { + val main = HeldMain() + val sdk = sdk(main, coreV2 = true) + val ends = CopyOnWriteArrayList, Boolean>>() + + methods.forEach { method -> method.listener(sdk, CompletionListener { ends += it to (Looper.myLooper() == Looper.getMainLooper()) }) } + while (ends.size < methods.size && main.runNext()) Unit + main.runNext(timeoutMs = 200) + + assertEquals(EXPECTED.map { SdkResult.Success(it) to true }.toSet(), ends.toSet()) + assertEquals(methods.size, ends.size) + } + + @Test + fun `an app's instance on the legacy core gets notInitialized from every method in both forms, sends nothing and logs each call`() { + val main = HeldMain() + val sdk = sdk(main, coreV2 = false) + sent() + + methods.forEach { method -> + val thrown = try { + runBlocking { method.suspending(sdk) } + null + } catch (e: SdkException) { + e + } + val ends = CopyOnWriteArrayList>() + method.listener(sdk, CompletionListener { ends += it }) + while (ends.isEmpty() && main.runNext()) Unit + + assertEquals(method.call, SdkError.NotInitialized, thrown?.error) + assertTrue(method.call, thrown?.message.orEmpty().contains("Rees46.initializeBridge")) + assertEquals(method.call, listOf>(SdkResult.Failure(SdkError.NotInitialized)), ends) + assertEquals(method.call, 2, logged.count { it.code == LogCodes.CORE_FLAG_MISMATCH && it.context["call"] == method.call }) + } + val sent = sent() + methods.forEach { method -> assertFalse(method.call, method.path in sent) } + } + + @Test + fun `on the legacy core wrong arguments are notInitialized too`() { + val sdk = sdk(HeldMain(), coreV2 = false) + + val outcomes = listOf( + outcome { sdk.stories.get("") }, + outcome { sdk.loyalty.join(" ", birthday = "17.05.1990") }, + outcome { sdk.loyalty.getPromotions(currentTime = "25:00") }, + outcome { sdk.sliders.get("home", tags = listOf("a,b")) }, + ) + + assertEquals(List(4) { SdkResult.Failure(SdkError.NotInitialized) }, outcomes) + } + + @Test + fun `an instance never initialized gets notInitialized`() { + val sdk = SDK() + + methods.forEach { method -> assertEquals(method.call, SdkResult.Failure(SdkError.NotInitialized), outcome { method.suspending(sdk) }) } + assertTrue(sent().isEmpty()) + } + + @Test + fun `a wrong argument is logged with its call, never with its value`() { + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + sent() + + val outcome = outcome { sdk.loyalty.join("79991234567", birthday = "17.05.1990") } + + assertEquals(SdkResult.Failure(SdkError.InvalidArgument("birthday must be an existing date YYYY-MM-DD")), outcome) + val line = logged.single { it.code == LogCodes.INVALID_ARGUMENT } + assertEquals("loyalty.join", line.context["call"]) + assertFalse(line.message.contains("17.05.1990") || line.message.contains("79991234567")) + assertFalse("loyalty/members/join" in sent()) + } + + @Test + fun `Java does not see the namespaces`() { + listOf("getStories", "getPredict", "getLoyalty", "getSliders").forEach { name -> + val getters = SDK::class.java.methods.filter { it.name == name } + assertTrue(name, getters.isNotEmpty() && getters.all { it.isSynthetic }) + } + } + + private companion object { + const val SHOP = "stories-predict-loyalty-sliders-shop" + + val ANSWERS = mapOf( + "init" to """{"did":"D1","seance":"S1"}""", + "stories/main" to """{"id":7,"stories":[]}""", + "api/v3/cdp/users/probability-to-purchase" to """{"status":"success","payload":{"probability":0.42,"client_id":9}}""", + "loyalty/members/join" to """{"status":"success","payload":{"identifier":"79991234567"}}""", + "loyalty/members/status" to """{"status":"success","payload":{"member":true,"level":{"code":"gold","name":"Gold","expiration_date":null}}}""", + "loyalty/promos/for-client" to """{"status":"success","payload":{"promotions":[{"id":1,"name":"A","reward_type":"discount"}]}}""", + "slider" to """{"status":"success","payload":{"properties":{"code":"home","width":10,"height":2},"slides":[{"banner_id":1,"recommended_code":"home"}]}}""", + ) + + /** What [methods] return from [ANSWERS], in their order. */ + val EXPECTED: List = listOf( + StoriesBlock("7", emptyList()), + PurchaseProbability(0.42, "9"), + LoyaltyMember("79991234567"), + LoyaltyStatus(true, LoyaltyLevel("gold", "Gold", null)), + listOf(LoyaltyPromotion(1, "A", null, null, null, null, null, null, LoyaltyRewardType.DISCOUNT)), + Slider("home", 10, 2, listOf(SliderBanner("1", "home", null, null, null, null, null))), + ) + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/cart/CartApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/cart/CartApiFixturesTest.kt new file mode 100644 index 00000000..4fa95f57 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/cart/CartApiFixturesTest.kt @@ -0,0 +1,138 @@ +package com.personalization.features.cart + +import androidx.test.core.app.ApplicationProvider +import com.personalization.api.responses.cart.CartItem +import com.personalization.core.BridgeApi +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.internal.ContractFixtures +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreHttpClient +import com.personalization.core.internal.CoreV2 +import com.personalization.core.internal.FakeConnectivity +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.startedCoreInit +import com.personalization.logs.SdkLogs +import com.personalization.sdk.domain.repositories.UserSettingsRepository +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.json.JSONArray +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.TimeUnit + +/** `cart.get` against the contract's fixtures (`contract/0/cart.json`): the request it makes and how it reads each answer. */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class CartApiFixturesTest { + + private val server = MockWebServer() + private val connectivity = FakeConnectivity(connected = true) + private val settings = mockk(relaxed = true) { + every { getShopId() } returns SHOP + every { getDid() } returns "did-1" + every { getSid() } returns "sid-1" + every { getStream() } returns "android" + every { getSegmentForABTesting() } returns "B" + } + private lateinit var core: CoreV2 + private lateinit var cart: CartApiImpl + + @Before + fun setUp() { + SdkLogs.reset() + server.start() + val client = CoreHttpClient({ server.url("/").toString() }, settings, connectivity, SHOP) + core = CoreV2(client, SHOP).also { + it.init = startedCoreInit(ApplicationProvider.getApplicationContext(), settings, connectivity, SHOP) + } + cart = CartApiImpl(NamespaceCalls(core = { core }, dispatchers = { CoreDispatchers.DEFAULT }, shopId = { SHOP })) + } + + @After + fun tearDown() { + core.release() + server.close() + SdkLogs.reset() + } + + private fun get(): SdkResult> = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { cart.get() } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + @Test + fun `get makes the contract's request, with no field of its own beside the common ones`() { + val cases = ContractFixtures.requests("cart") + assertTrue(cases.isNotEmpty()) + cases.forEach { case -> + val name = case.getString("name") + val expected = case.getJSONObject("request") + server.enqueue(MockResponse().setBody("""{"status":"success","data":{"items":[]}}""")) + + get() + + val url = server.takeRequest(5, TimeUnit.SECONDS)!!.let { recorded -> + assertEquals(name, expected.getString("method"), recorded.method) + recorded.requestUrl!! + } + assertEquals(name, "/" + expected.getString("path"), url.encodedPath) + val query = expected.getJSONObject("query") + assertEquals(name, query.keys().asSequence().toSet(), url.queryParameterNames - COMMON_FIELDS) + query.keys().forEach { key -> assertEquals(name, query.getString(key), url.queryParameter(key)) } + // The core adds the common fields; the core's own tests check their values. + assertEquals(name, COMMON_FIELDS, url.queryParameterNames intersect COMMON_FIELDS) + } + } + + @Test + fun `get reads every answer of the contract into its items or its error`() { + val cases = ContractFixtures.answers("cart") + assertTrue(cases.size >= 5) + cases.forEach { case -> + val name = case.getString("name") + val response = ContractFixtures.mockResponse(case) + // No answer: the request finds no network. + connectivity.set(response != null) + response?.let(server::enqueue) + val expect = case.getJSONObject("expect") + + val outcome = get() + + if (expect.has("result")) { + assertEquals(name, SdkResult.Success(items(expect.getJSONArray("result"))), outcome) + } else { + assertEquals(name, SdkResult.Failure(ContractFixtures.errorOf(expect.getJSONObject("error"))), outcome) + } + } + } + + @Test + fun `an answer without a body is an empty cart`() { + server.enqueue(MockResponse().setResponseCode(200)) + + assertEquals(SdkResult.Success(emptyList()), get()) + } + + private fun items(array: JSONArray): List = (0 until array.length()).map { index -> + val item = array.getJSONObject(index) + CartItem(id = item.getString("id"), quantity = item.getInt("quantity")) + } + + private companion object { + const val SHOP = "cart-shop" + val COMMON_FIELDS = setOf("shop_id", "did", "sid", "seance", "segment", "stream") + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/cart/CartNamespaceTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/cart/CartNamespaceTest.kt new file mode 100644 index 00000000..edd1d852 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/cart/CartNamespaceTest.kt @@ -0,0 +1,269 @@ +package com.personalization.features.cart + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.SdkRegistry +import com.personalization.api.responses.cart.CartItem +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.HeldMain +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +/** + * `sdk.cart` as a bridge calls it: on the new core it asks the server and answers in both forms; on the + * legacy core, where apps run, it fails with `notInitialized` and sends nothing. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class CartNamespaceTest { + + private lateinit var context: Context + private val server = MockWebServer() + private val paths = LinkedBlockingQueue() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val threads = TrackingThreads() + + /** The answer to `products/cart`; `/init` answers with a `did` unless [initAnswer] says otherwise. */ + @Volatile + private var cartAnswer: MockResponse = MockResponse().setBody(CART) + + @Volatile + private var initAnswer: MockResponse = MockResponse().setBody("""{"did":"D1","seance":"S1"}""") + + /** Holds the answer to `products/cart` while it is not null. */ + @Volatile + private var holdCart: CountDownLatch? = null + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.requestUrl?.encodedPath?.removePrefix("/") ?: return MockResponse().setResponseCode(400) + paths += path + return when (path) { + "init" -> initAnswer + CartApiImpl.PATH -> { + holdCart?.await(5, TimeUnit.SECONDS) + cartAnswer + } + else -> MockResponse().setBody("{}") + } + } + } + server.start() + } + + @After + fun tearDown() { + holdCart?.countDown() + SdkRegistry.all().forEach { it.release() } + server.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + private fun config() = Rees46Config( + shopId = SHOP, + apiDomain = server.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + + private fun awaitState(sdk: SDK, state: SdkState) = runBlocking { + withTimeout(5_000) { sdk.instanceState.changes.first { it == state } } + } + + private fun get(sdk: SDK): SdkResult> = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { sdk.cart.get() } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + /** The paths the server got, after the calls so far had time to arrive. */ + private fun sent(): List { + threads.awaitIdle() + Thread.sleep(200) + return generateSequence { paths.poll() }.toList() + } + + /** A bridge's instance whose listener forms end on [main], which the test runs. */ + private fun bridgeSdk(main: HeldMain): SDK { + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } + sdk.initializeWith(context, config(), coreV2 = true) + awaitState(sdk, SdkState.READY) + return sdk + } + + @Test + fun `a bridge's instance gets the cart from the server`() { + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + + assertEquals(SdkResult.Success(listOf(CartItem("37", 2), CartItem("38", 1))), get(sdk)) + assertTrue(CartApiImpl.PATH in sent()) + } + + @Test + fun `the form with a listener ends once, on the main thread`() { + val main = HeldMain() + val sdk = bridgeSdk(main) + val ends = CopyOnWriteArrayList>, Boolean>>() + + sdk.cart.get(CompletionListener { ends += it to (Looper.myLooper() == Looper.getMainLooper()) }) + while (ends.isEmpty() && main.runNext()) Unit + main.runNext(timeoutMs = 200) + + assertEquals(listOf(SdkResult.Success(listOf(CartItem("37", 2), CartItem("38", 1))) to true), ends) + } + + @Test + fun `an app's instance on the legacy core gets notInitialized in both forms and sends nothing`() { + val main = HeldMain() + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } + sdk.initializeWith(context, config(), coreV2 = false) + awaitState(sdk, SdkState.READY) + sent() + + val thrown = try { + runBlocking { sdk.cart.get() } + null + } catch (e: SdkException) { + e + } + val ends = CopyOnWriteArrayList>>() + sdk.cart.get(CompletionListener { ends += it }) + while (ends.isEmpty() && main.runNext()) Unit + + assertEquals(SdkError.NotInitialized, thrown?.error) + assertTrue("${thrown?.message}", thrown?.message.orEmpty().contains("Rees46.initializeBridge")) + assertEquals(listOf>>(SdkResult.Failure(SdkError.NotInitialized)), ends) + assertTrue(CartApiImpl.PATH !in sent()) + assertEquals(2, logged.count { it.code == LogCodes.CORE_FLAG_MISMATCH && it.context["call"] == CartApiImpl.GET }) + } + + @Test + fun `an instance never initialized gets notInitialized`() { + assertEquals(SdkResult.Failure(SdkError.NotInitialized), get(SDK())) + assertTrue(sent().isEmpty()) + } + + @Test + fun `a 403 to the cart is http and leaves the instance ready`() { + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + cartAnswer = MockResponse().setResponseCode(403) + + assertEquals(SdkResult.Failure(SdkError.Http(403)), get(sdk)) + assertEquals(SdkState.READY, sdk.state) + } + + @Test + fun `a refused shop gets shopBlocked without asking for the cart`() { + initAnswer = MockResponse().setResponseCode(402).setBody("""{"status":"error","message":"Restricted Mode"}""") + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.REFUSED) + + assertEquals(SdkResult.Failure(SdkError.ShopBlocked), get(sdk)) + assertTrue(CartApiImpl.PATH !in sent()) + } + + @Test + fun `release ends a call in flight with cancelled, and the calls after it fail with notInitialized`() { + val main = HeldMain() + val sdk = bridgeSdk(main) + holdCart = CountDownLatch(1) + val ends = CopyOnWriteArrayList>>() + + sdk.cart.get(CompletionListener { ends += it }) + // The request reached the server, which holds its answer. + assertTrue(generateSequence { paths.poll(5, TimeUnit.SECONDS) }.any { it == CartApiImpl.PATH }) + sdk.release() + while (ends.isEmpty() && main.runNext()) Unit + holdCart?.countDown() + + assertEquals(listOf>>(SdkResult.Failure(SdkError.Cancelled)), ends) + assertEquals(SdkResult.Failure(SdkError.NotInitialized), get(sdk)) + } + + @Test + fun `Java does not see the namespace`() { + val getters = SDK::class.java.methods.filter { it.name == "getCart" } + + assertTrue(getters.isNotEmpty() && getters.all { it.isSynthetic }) + } + + private companion object { + const val SHOP = "cart-namespace-shop" + const val CART = """{"status":"success","data":{"items":[{"uniqid":"37","quantity":2},{"uniqid":"38","quantity":1}]}}""" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/collection/CollectionsApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/collection/CollectionsApiFixturesTest.kt new file mode 100644 index 00000000..79416c70 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/collection/CollectionsApiFixturesTest.kt @@ -0,0 +1,48 @@ +package com.personalization.features.collection + +import com.personalization.core.BridgeApi +import com.personalization.core.internal.NamespaceFixtures +import okhttp3.mockwebserver.MockResponse +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** `sdk.collections` against the contract's fixtures (`contract/0/collections.json`). */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class CollectionsApiFixturesTest { + + private val fixtures = NamespaceFixtures("collections-shop") + private lateinit var collections: CollectionsApiImpl + + @Before + fun setUp() { + fixtures.start() + collections = CollectionsApiImpl(fixtures.calls) + } + + @After + fun tearDown() = fixtures.stop() + + private val invoke = NamespaceFixtures.Invoke { method, args -> + when (method) { + "get" -> collections.get(args.getString("collectionId")) + else -> error("no collections.$method") + } + } + + @Test + fun `get makes the contract's request, or fails with invalidArgument and sends nothing`() { + fixtures.checkRequests("collections", invoke) { MockResponse().setBody("""{"products":[]}""") } + fixtures.checkErrors("collections", invoke) + } + + @Test + fun `get reads each answer of the contract into its result or its error`() { + fixtures.checkAnswers("collections", invoke) + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/loyalty/LoyaltyApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/loyalty/LoyaltyApiFixturesTest.kt new file mode 100644 index 00000000..9c2c899f --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/loyalty/LoyaltyApiFixturesTest.kt @@ -0,0 +1,160 @@ +package com.personalization.features.loyalty + +import androidx.test.core.app.ApplicationProvider +import com.personalization.api.models.loyalty.LoyaltyMember +import com.personalization.api.models.loyalty.LoyaltyPromotion +import com.personalization.api.models.loyalty.LoyaltyRewardType +import com.personalization.api.models.loyalty.LoyaltyStatus +import com.personalization.api.models.profile.Gender +import com.personalization.core.BridgeApi +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.argBoolean +import com.personalization.core.internal.argStrings +import com.personalization.core.internal.argString +import com.personalization.core.internal.isBirthday +import com.personalization.core.internal.isCalendarDate +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.MockResponse +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.TimeUnit + +/** `loyalty.join`, `getStatus` and `getPromotions` against the contract's fixtures (`contract/0/loyalty.json`). */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class LoyaltyApiFixturesTest { + + private val fixtures = NamespaceFixtures(SHOP) + private lateinit var loyalty: LoyaltyApiImpl + + private val invoke = NamespaceFixtures.Invoke { method, args -> + when (method) { + "join" -> loyalty.join( + phone = args.getString("phone"), + firstName = args.argString("firstName"), + lastName = args.argString("lastName"), + gender = args.argString("gender")?.let { name -> Gender.entries.single { it.name.lowercase() == name } }, + birthday = args.argString("birthday"), + ) + "getStatus" -> loyalty.getStatus(args.getString("phone")) + "getPromotions" -> loyalty.getPromotions( + locationId = args.argString("locationId"), + promoCodes = args.argStrings("promoCodes"), + chargeBonuses = args.argBoolean("chargeBonuses"), + currentTime = args.argString("currentTime"), + ) + else -> error("unknown method $method") + } + } + + private val json = NamespaceFixtures.Json { value -> + when (value) { + is LoyaltyMember -> mapOf("identifier" to value.identifier) + is LoyaltyStatus -> mapOf( + "isMember" to value.isMember, + "level" to value.level?.let { mapOf("code" to it.code, "name" to it.name, "expirationDate" to it.expirationDate) }, + ) + is List<*> -> value.map { promotion(it as LoyaltyPromotion) } + else -> error("unexpected result $value") + } + } + + @Before + fun setUp() { + fixtures.start(ApplicationProvider.getApplicationContext()) + loyalty = LoyaltyApiImpl(fixtures.calls) + } + + @After + fun tearDown() = fixtures.stop() + + @Test + fun `each method makes the contract's request, promo codes as a Rails array`() { + assertEquals(5, fixtures.checkRequests(FILE, invoke, NAMESPACE)) + } + + @Test + fun `wrong arguments are invalidArgument without a request`() { + assertEquals(7, fixtures.checkErrors(FILE, invoke, NAMESPACE)) + } + + @Test + fun `every answer of the contract reads into the method's model or its error`() { + assertTrue(fixtures.checkAnswers(FILE, invoke, NAMESPACE, json) >= 15) + } + + @Test + fun `an empty list of promo codes is not sent, and chargeBonuses false is`() { + fixtures.server.enqueue(MockResponse().setBody("""{"status":"success","payload":{"promotions":[]}}""")) + + runBlocking { withTimeout(10_000) { loyalty.getPromotions(promoCodes = emptyList(), chargeBonuses = false) } } + + val url = fixtures.server.takeRequest(5, TimeUnit.SECONDS)!!.requestUrl!! + assertEquals(setOf("charge_bonuses"), url.queryParameterNames - NamespaceFixtures.COMMON_FIELDS) + assertEquals("false", url.queryParameter("charge_bonuses")) + } + + @Test + fun `a time outside HH colon MM of a day is invalidArgument without a request`() { + listOf("9:30", "24:00", "12:60", "12:30:00", "").forEach { time -> + val error = try { + runBlocking { loyalty.getPromotions(currentTime = time) } + null + } catch (e: SdkException) { + e.error + } + assertTrue("$time: $error", error is SdkError.InvalidArgument) + } + assertNull(fixtures.server.takeRequest(100, TimeUnit.MILLISECONDS)) + } + + @Test + fun `a promotion without a whole id is left out`() { + val body = JSONObject("""{"status":"success","payload":{"promotions":[{"name":"A"},{"id":"x"},{"id":2.0,"name":"B"}]}}""") + + assertEquals(listOf(2L), LoyaltyApiImpl.readPromotions(body)?.map { it.id }) + } + + @Test + fun `a birthday is an existing date of the calendar as YYYY-MM-DD`() { + listOf("1990-05-17", "2000-02-29", "0999-12-31", "3000-01-01").forEach { assertTrue(it, isCalendarDate(it)) } + listOf( + "1990-5-17", "17.05.1990", "1990-02-30", "2001-02-29", "1900-02-29", "1990-13-01", "1990-00-10", "1990-05-00", + "1990-05-17T00:00", " 1990-05-17", "", "1990-05-17", + ).forEach { assertFalse(it, isCalendarDate(it)) } + // profile.set takes the years 1000 to 2999 only. + listOf("1000-01-01", "2999-12-31").forEach { assertTrue(it, isBirthday(it)) } + listOf("0999-12-31", "3000-01-01", "2001-02-29").forEach { assertFalse(it, isBirthday(it)) } + } + + private fun promotion(promotion: LoyaltyPromotion): Map = mapOf( + "id" to promotion.id, "name" to promotion.name, "description" to promotion.description, + "startDate" to promotion.startDate, "finishDate" to promotion.finishDate, "stream" to promotion.stream, + "badgeLabel" to promotion.badgeLabel, "badgeColor" to promotion.badgeColor, + "rewardType" to when (promotion.rewardType) { + LoyaltyRewardType.DISCOUNT -> "discount" + LoyaltyRewardType.BONUSES_EARN -> "bonusesEarn" + LoyaltyRewardType.BONUSES_USAGE -> "bonusesUsage" + null -> null + }, + ) + + private companion object { + const val SHOP = "loyalty-shop" + const val FILE = "loyalty" + const val NAMESPACE = "loyalty" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/notifications/NotificationsApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/notifications/NotificationsApiFixturesTest.kt new file mode 100644 index 00000000..33a168dc --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/notifications/NotificationsApiFixturesTest.kt @@ -0,0 +1,273 @@ +package com.personalization.features.notifications + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.PushProvider +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkRegistry +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.ContractFixtures +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.PushHub +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.logs.SdkLogs +import com.personalization.push.PushTokenManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +/** + * `sdk.notifications` against the contract's fixtures (`contract/0/notifications.json`) on a bridge's + * instance and a local server: the request each call makes, the calls refused before one, and how + * `setPushToken` reads each answer. + * + * A case of one platform says so with `platform` (`android`, `ios`): the cases of iOS are skipped, and so is + * one whose provider Android's [PushProvider] cannot name (`apns`, which only a major release may add). + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class NotificationsApiFixturesTest { + + private lateinit var context: Context + private val server = MockWebServer() + private val requests = LinkedBlockingQueue>() + private val seen = CopyOnWriteArrayList() + private val defaultSources = PushTokenManager.sourceFactory + + /** The answer to `mobile_push_tokens`. */ + @Volatile + private var tokenAnswer: MockResponse = MockResponse().setBody("""{"status":"success"}""") + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + PushHub.reset() + PushTokenManager.sourceFactory = { emptyList() } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + network(connected = true) + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val url = request.requestUrl ?: return MockResponse().setResponseCode(400) + val path = url.encodedPath.removePrefix("/") + val text = request.body.readUtf8() + val body = if (request.method == "POST" && text.isNotEmpty()) JSONObject(text) else JSONObject() + requests += path to body + seen += path + return when (path) { + "init" -> MockResponse().setBody("""{"did":"D1","seance":"S1"}""") + "mobile_push_tokens" -> tokenAnswer + else -> MockResponse().setBody("{}") + } + } + } + server.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + server.shutdown() + PushTokenManager.sourceFactory = defaultSources + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + PushHub.reset() + } + + private fun network(connected: Boolean) { + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + if (connected) shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + } + + /** A bridge's instance, ready; its listeners end on the thread that ends the call. */ + private fun bridgeSdk(): SDK { + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { Dispatchers.Unconfined }) } + sdk.initializeWith( + context, + Rees46Config(shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, logLevel = LogLevel.DEBUG), + coreV2 = true, + ) + runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } + return sdk + } + + private fun forAndroid(case: JSONObject): Boolean = case.optString("platform").let { it.isEmpty() || it == "android" } + + /** Android's provider of a case; null for one it cannot name. */ + private fun provider(name: String): PushProvider? = PushProvider.fromId(name) + + /** Runs the case's call and returns how it ended; null when Android cannot make it. */ + private fun call(sdk: SDK, case: JSONObject): SdkResult? { + val call = case.getJSONObject("call") + assertEquals("notifications", call.getString("namespace")) + val args = call.getJSONObject("args") + return when (val method = call.getString("method")) { + "setPushToken" -> { + val provider = provider(args.getString("provider")) ?: return null + try { + runBlocking { withTimeout(10_000) { sdk.notifications.setPushToken(args.getString("token"), provider) } } + SdkResult.Success(Unit) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + } + else -> { + val ends = LinkedBlockingQueue>() + val listener = CompletionListener { ends += it } + val code = args.getString("code") + val type = args.getString("type") + when (method) { + "trackDelivered" -> sdk.notifications.trackDelivered(code, type, listener) + "trackOpened" -> sdk.notifications.trackOpened(code, type, listener) + "trackClicked" -> sdk.notifications.trackClicked(code, type, listener) + "trackClosed" -> sdk.notifications.trackClosed(code, type, listener) + else -> throw AssertionError("unknown method $method") + } + ends.poll(5, TimeUnit.SECONDS) ?: throw AssertionError("$method did not end") + } + } + } + + /** The path a case's call sends to. */ + private fun pathOf(case: JSONObject): String = when (val method = case.getJSONObject("call").getString("method")) { + "setPushToken" -> "mobile_push_tokens" + else -> "track/" + method.removePrefix("track").lowercase() + } + + /** The next request to [path], skipping others; null when none came in time. */ + private fun next(path: String): JSONObject? { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (true) { + val left = deadline - System.nanoTime() + if (left <= 0) return null + val request = requests.poll(left, TimeUnit.NANOSECONDS) ?: return null + if (request.first == path) return request.second + } + } + + @Test + fun `each call makes the contract's request`() { + val sdk = bridgeSdk() + val cases = ContractFixtures.requests("notifications").filter(::forAndroid) + assertTrue(cases.size >= 6) + cases.forEach { case -> + val name = case.getString("name") + val expected = case.getJSONObject("request") + val outcome = call(sdk, case) + assertEquals(name, SdkResult.Success(Unit), outcome) + // The events wait in the queue: it goes now. + runBlocking { withTimeout(5_000) { sdk.flush() } } + + assertEquals(name, "POST", expected.getString("method")) + val body = next(expected.getString("path")) ?: throw AssertionError("$name: no request to ${expected.getString("path")}") + val fields = expected.getJSONObject("body") + fields.keys().forEach { key -> assertEquals("$name: $key", fields.get(key), body.opt(key)) } + // The core adds the common fields; the core's own tests check their values. + assertEquals(name, SHOP, body.optString("shop_id")) + assertEquals(name, "D1", body.optString("did")) + } + } + + @Test + fun `a call refused by the contract sends nothing and ends in its error`() { + val sdk = bridgeSdk() + val cases = ContractFixtures.cases("notifications").filter { it.has("error") && forAndroid(it) } + assertTrue(cases.size >= 3) + var made = 0 + cases.forEach { case -> + val name = case.getString("name") + seen.clear() + val outcome = call(sdk, case) + if (outcome == null) { + // A provider of the other platform: Android's type has no such value, so the call cannot be made. + assertTrue(name, PushProvider.entries.none { it.id == case.getJSONObject("call").getJSONObject("args").getString("provider") }) + return@forEach + } + made++ + val expected = ContractFixtures.errorOf(case.getJSONObject("error")) + + assertTrue("$name: $outcome", outcome is SdkResult.Failure && outcome.error.javaClass == expected.javaClass) + runBlocking { withTimeout(5_000) { sdk.flush() } } + assertFalse(name, pathOf(case) in seen) + } + assertTrue(made >= 3) + } + + @Test + fun `setPushToken reads every answer of the contract into success or its error`() { + val sdk = bridgeSdk() + val cases = ContractFixtures.answers("notifications").filter(::forAndroid) + assertTrue(cases.size >= 6) + cases.forEach { case -> + val name = case.getString("name") + val response = ContractFixtures.mockResponse(case) + // No answer: the request finds no network. + network(connected = response != null) + response?.let { tokenAnswer = it } + val expect = case.getJSONObject("expect") + + val outcome = call(sdk, case) + + if (expect.has("result")) { + assertTrue(name, expect.isNull("result")) + assertEquals(name, SdkResult.Success(Unit), outcome) + } else { + assertEquals(name, SdkResult.Failure(ContractFixtures.errorOf(expect.getJSONObject("error"))), outcome) + } + } + network(connected = true) + } + + private companion object { + const val SHOP = "notifications-fixtures-shop" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/notifications/NotificationsNamespaceTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/notifications/NotificationsNamespaceTest.kt new file mode 100644 index 00000000..8141fb14 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/notifications/NotificationsNamespaceTest.kt @@ -0,0 +1,471 @@ +package com.personalization.features.notifications + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.PushProvider +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.SdkRegistry +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.PushCallbacks +import com.personalization.core.PushEvent +import com.personalization.core.PushToken +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.HeldMain +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.PushHub +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageKeys +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import com.personalization.push.PushTokenManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +/** + * `sdk.notifications` as a bridge calls it: on the new core the push events go through the queue once per + * message, without the push callbacks, and the token by the rules of `core/push.md`; on the legacy core, + * where apps run, every call sends nothing and fails with `notInitialized`. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class NotificationsNamespaceTest { + + private lateinit var context: Context + private val server = MockWebServer() + private val requests = LinkedBlockingQueue>() + private val seen = CopyOnWriteArrayList>() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val defaultSources = PushTokenManager.sourceFactory + private val threads = TrackingThreads() + + @Volatile + private var initAnswer: MockResponse = MockResponse().setBody("""{"did":"D1","seance":"S1"}""") + + @Volatile + private var tokenAnswer: MockResponse = MockResponse().setBody("""{"status":"success"}""") + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + PushHub.reset() + PushHub.main = Executor { it.run() } + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + PushTokenManager.sourceFactory = { emptyList() } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val url = request.requestUrl ?: return MockResponse().setResponseCode(400) + val path = url.encodedPath.removePrefix("/") + val text = request.body.readUtf8() + val body = if (request.method == "POST" && text.isNotEmpty()) JSONObject(text) else JSONObject() + requests += path to body + seen += path to body + return when (path) { + "init" -> initAnswer + "mobile_push_tokens" -> tokenAnswer + else -> MockResponse().setBody("{}") + } + } + } + server.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + server.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + PushTokenManager.sourceFactory = defaultSources + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + SdkLogs.handlerExecutor = defaultExecutor + QueueStore.reset() + PushHub.reset() + } + + private fun config() = Rees46Config( + shopId = SHOP, + apiDomain = server.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + + private fun awaitState(sdk: SDK, state: SdkState) = runBlocking { + withTimeout(5_000) { sdk.instanceState.changes.first { it == state } } + } + + /** An instance whose listeners end on [main]: the test runs it, or they end on the calling thread. */ + private fun sdk(coreV2: Boolean = true, main: HeldMain? = null): SDK { + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main ?: Dispatchers.Unconfined }) } + sdk.initializeWith(context, config(), coreV2 = coreV2) + awaitState(sdk, SdkState.READY) + return sdk + } + + private fun flush(sdk: SDK) = runBlocking { withTimeout(5_000) { sdk.flush() } } + + /** Calls [track] with a listener and returns how it ended. */ + private fun ended(track: (CompletionListener) -> Unit): SdkResult { + val ends = LinkedBlockingQueue>() + track(CompletionListener { ends += it }) + return ends.poll(5, TimeUnit.SECONDS) ?: throw AssertionError("the call did not end") + } + + private fun setPushToken(sdk: SDK, token: String, provider: PushProvider): SdkResult = try { + runBlocking { withTimeout(10_000) { sdk.notifications.setPushToken(token, provider) } } + SdkResult.Success(Unit) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + /** The next request to one of [paths], skipping others; null when none came in [timeoutMs]. */ + private fun next(vararg paths: String, timeoutMs: Long = 5_000): Pair? { + val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs) + while (true) { + val left = deadline - System.nanoTime() + if (left <= 0) return null + val request = requests.poll(left, TimeUnit.NANOSECONDS) ?: return null + if (request.first in paths) return request + } + } + + private fun partition() = context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE) + + // The new core: push events. + + @Test + fun `each event goes through the queue to its own path with code, type, shop and did, and no sid`() { + val sdk = sdk() + val calls = listOf) -> Unit>>( + "track/delivered" to { code, listener -> sdk.notifications.trackDelivered(code, "bulk", listener) }, + "track/opened" to { code, listener -> sdk.notifications.trackOpened(code, "bulk", listener) }, + "track/clicked" to { code, listener -> sdk.notifications.trackClicked(code, "bulk", listener) }, + "track/closed" to { code, listener -> sdk.notifications.trackClosed(code, "bulk", listener) }, + ) + calls.forEach { (path, track) -> + assertEquals(path, SdkResult.Success(Unit), ended { track("m-$path", it) }) + flush(sdk) + + val (sent, body) = next(*calls.map { it.first }.toTypedArray(), "track/received") ?: throw AssertionError("no request for $path") + assertEquals(path, sent) + assertEquals("m-$path", body.getString("code")) + assertEquals("bulk", body.getString("type")) + assertEquals(SHOP, body.getString("shop_id")) + assertEquals("D1", body.getString("did")) + assertFalse("no sid in a push event", body.has("sid") || body.has("seance")) + } + } + + @Test + fun `an event goes without a listener too`() { + val sdk = sdk() + + sdk.notifications.trackClosed("m-quiet", "chain") + flush(sdk) + + assertEquals("m-quiet", next("track/closed")?.second?.getString("code")) + } + + @Test + fun `a repeat of an event sends nothing and ends in success, as one handlePush took`() { + val sdk = sdk() + + assertEquals(SHOP, Rees46.handlePush(mapOf("id" to "m-1", "type" to "bulk", "shop_id" to SHOP), PushEvent.CLICKED)) + assertEquals(SdkResult.Success(Unit), ended { sdk.notifications.trackClicked("m-1", "bulk", it) }) + assertEquals(SdkResult.Success(Unit), ended { sdk.notifications.trackClicked("m-1", "bulk", it) }) + // Another event of the message is its own. + assertEquals(SdkResult.Success(Unit), ended { sdk.notifications.trackDelivered("m-1", "bulk", it) }) + flush(sdk) + + val events = seen.map { it.first }.filter { it.startsWith("track/") } + assertEquals(listOf("track/clicked", "track/delivered"), events) + } + + @Test + fun `the events the app reports call no push callback and no bridge listener`() { + val sdk = sdk() + val heard = CopyOnWriteArrayList() + sdk.notifications.setCallbacks(PushCallbacks(onDelivered = { heard += "own" }, onClicked = { heard += "own" })) + Rees46.setPushCallbacks(PushCallbacks(onDelivered = { heard += "facade" }, onClicked = { heard += "facade" })) + val bridge = Rees46.onPushEvent { _, _ -> heard += "bridge" } + + assertEquals(SdkResult.Success(Unit), ended { sdk.notifications.trackDelivered("m-2", "bulk", it) }) + assertEquals(SdkResult.Success(Unit), ended { sdk.notifications.trackClicked("m-2", "bulk", it) }) + flush(sdk) + bridge.cancel() + + assertEquals(emptyList(), heard) + } + + @Test + fun `a tap sets the source of the next tracking events for a type the source knows`() { + val sdk = sdk() + + assertEquals(SdkResult.Success(Unit), ended { sdk.notifications.trackClicked("m-9", "chain", it) }) + sdk.tracking.productView("37") + flush(sdk) + + val view = next("push")?.second ?: throw AssertionError("no push") + assertEquals("chain", view.getJSONObject("source").getString("from")) + assertEquals("m-9", view.getJSONObject("source").getString("code")) + assertFalse(view.has("from") || view.has("code")) + } + + @Test + fun `an empty code or type is invalidArgument, logged, and nothing goes`() { + val sdk = sdk() + + val emptyCode = ended { sdk.notifications.trackDelivered(" ", "bulk", it) } + val emptyType = ended { sdk.notifications.trackOpened("m-3", "", it) } + flush(sdk) + + assertTrue("$emptyCode", (emptyCode as? SdkResult.Failure)?.error is SdkError.InvalidArgument) + assertTrue("$emptyType", (emptyType as? SdkResult.Failure)?.error is SdkError.InvalidArgument) + assertTrue(seen.none { it.first.startsWith("track/") }) + val refusals = logged.filter { it.code == LogCodes.INVALID_ARGUMENT } + assertEquals(listOf("empty_code", "empty_type"), refusals.map { it.context["reason"] }) + assertEquals(listOf(NotificationsApiImpl.TRACK_DELIVERED, NotificationsApiImpl.TRACK_OPENED), refusals.map { it.context["call"] }) + } + + @Test + fun `a refused shop gets shopBlocked and nothing goes`() { + initAnswer = MockResponse().setResponseCode(402).setBody("""{"status":"error","message":"Restricted Mode"}""") + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { Dispatchers.Unconfined }) } + sdk.initializeWith(context, config(), coreV2 = true) + awaitState(sdk, SdkState.REFUSED) + + assertEquals(SdkResult.Failure(SdkError.ShopBlocked), ended { sdk.notifications.trackClicked("m-4", "bulk", it) }) + assertNull("no source for a tap the queue refused", partition().getString(StorageKeys.TRACKING_SOURCE_TYPE, null)) + assertEquals(SdkResult.Failure(SdkError.ShopBlocked), setPushToken(sdk, "t-refused", PushProvider.FCM)) + assertTrue(seen.none { it.first.startsWith("track/") || it.first == "mobile_push_tokens" }) + } + + @Test + fun `after release every call fails with notInitialized and sends nothing`() { + val sdk = sdk() + sdk.notifications.setPushToken("t-before", PushProvider.FCM, CompletionListener { }) + assertEquals("t-before", next("mobile_push_tokens")?.second?.getString("token")) + sdk.release() + + assertEquals(SdkResult.Failure(SdkError.NotInitialized), ended { sdk.notifications.trackClicked("m-5", "bulk", it) }) + assertEquals(SdkResult.Failure(SdkError.NotInitialized), setPushToken(sdk, "t-after", PushProvider.FCM)) + assertNull(sdk.notifications.getPushToken(PushProvider.FCM)) + assertTrue(seen.none { it.first.startsWith("track/") }) + assertTrue(seen.none { it.second.optString("token") == "t-after" }) + } + + @Test + fun `the form with a listener ends once, on the main thread`() { + val main = HeldMain() + val sdk = sdk(main = main) + val ends = CopyOnWriteArrayList, Boolean>>() + + sdk.notifications.trackClicked("m-6", "bulk", CompletionListener { ends += it to (Looper.myLooper() == Looper.getMainLooper()) }) + sdk.notifications.setPushToken("t-main", PushProvider.FCM, CompletionListener { ends += it to (Looper.myLooper() == Looper.getMainLooper()) }) + while (ends.size < 2 && main.runNext()) Unit + main.runNext(timeoutMs = 200) + + assertEquals(listOf(SdkResult.Success(Unit) to true, SdkResult.Success(Unit) to true), ends) + } + + // The new core: the token and the callbacks. + + @Test + fun `setPushToken sends the token of its provider at once, and the same token again this week sends nothing`() { + val sdk = sdk() + + assertEquals(SdkResult.Success(Unit), setPushToken(sdk, "fcm-1", PushProvider.FCM)) + val fcm = next("mobile_push_tokens")?.second ?: throw AssertionError("no token") + assertEquals("fcm-1", fcm.getString("token")) + assertEquals("android", fcm.getString("platform")) + assertEquals("firebase", fcm.getString("push_provider")) + assertEquals("D1", fcm.getString("did")) + + assertEquals(SdkResult.Success(Unit), setPushToken(sdk, "hms-1", PushProvider.HMS)) + assertEquals("huawei", next("mobile_push_tokens")?.second?.getString("push_provider")) + + assertEquals(SdkResult.Success(Unit), setPushToken(sdk, "fcm-1", PushProvider.FCM)) + assertNull("sent this week", next("mobile_push_tokens", timeoutMs = 300)) + assertEquals(PushToken("fcm-1", PushProvider.FCM), sdk.notifications.getPushToken(PushProvider.FCM)) + assertEquals(PushToken("hms-1", PushProvider.HMS), sdk.notifications.getPushToken(PushProvider.HMS)) + } + + @Test + fun `setPushToken on a 2xx answer that says error is decoding, and the same token goes again since the week stays free`() { + val sdk = sdk() + tokenAnswer = MockResponse().setBody("""{"status":"error","message":"Something went wrong"}""") + + assertEquals(SdkResult.Failure(SdkError.Decoding), setPushToken(sdk, "fcm-2", PushProvider.FCM)) + assertEquals("fcm-2", next("mobile_push_tokens")?.second?.getString("token")) + assertNull("not recorded as sent", partition().getString(StorageKeys.pushToken("fcm"), null)) + + tokenAnswer = MockResponse().setBody("""{"status":"success"}""") + assertEquals(SdkResult.Success(Unit), setPushToken(sdk, "fcm-2", PushProvider.FCM)) + assertEquals("sent again", "fcm-2", next("mobile_push_tokens")?.second?.getString("token")) + assertEquals("fcm-2", partition().getString(StorageKeys.pushToken("fcm"), null)) + } + + @Test + fun `getPushToken without a provider is the one the shop sent last, or the device's, FCM first`() { + val sdk = sdk() + assertNull("no token yet", sdk.notifications.getPushToken()) + + DeviceStorage(context).savePushToken("hms", "hms-device") + assertEquals(PushToken("hms-device", PushProvider.HMS), sdk.notifications.getPushToken()) + DeviceStorage(context).savePushToken("fcm", "fcm-device") + assertEquals("none sent: FCM before HMS", PushToken("fcm-device", PushProvider.FCM), sdk.notifications.getPushToken()) + + // The shop sent its HMS token after its FCM one. + partition().edit() + .putString(StorageKeys.pushToken("fcm"), "fcm-device").putLong(StorageKeys.pushTokenDate("fcm"), 1_000L) + .putString(StorageKeys.pushToken("hms"), "hms-device").putLong(StorageKeys.pushTokenDate("hms"), 2_000L) + .commit() + assertEquals(PushToken("hms-device", PushProvider.HMS), sdk.notifications.getPushToken()) + assertEquals(PushToken("fcm-device", PushProvider.FCM), sdk.notifications.getPushToken(PushProvider.FCM)) + } + + @Test + fun `setCallbacks sets the shop's push callbacks, which a push then reaches`() { + val sdk = sdk() + val clicked = CopyOnWriteArrayList() + val callbacks = PushCallbacks(onClicked = { clicked += it.code }) + + sdk.notifications.setCallbacks(callbacks) + assertSame(callbacks, sdk.pushCallbacks) + assertEquals(SHOP, Rees46.handlePush(mapOf("id" to "m-7", "type" to "bulk", "shop_id" to SHOP), PushEvent.CLICKED)) + flush(sdk) + + assertEquals(listOf("m-7"), clicked) + } + + // The legacy core. + + @Test + fun `an app's instance on the legacy core refuses every call, logs why and sends nothing`() { + val main = HeldMain() + val sdk = sdk(coreV2 = false, main = main) + threads.awaitIdle() + seen.clear() + val ends = CopyOnWriteArrayList>() + + sdk.notifications.trackDelivered("m-8", "bulk", CompletionListener { ends += it }) + sdk.notifications.trackOpened("m-8", "bulk", CompletionListener { ends += it }) + sdk.notifications.trackClicked("m-8", "bulk", CompletionListener { ends += it }) + sdk.notifications.trackClosed("m-8", "bulk", CompletionListener { ends += it }) + sdk.notifications.setPushToken("t-legacy", PushProvider.FCM, CompletionListener { ends += it }) + while (ends.size < 5 && main.runNext()) Unit + val thrown = try { + runBlocking { sdk.notifications.setPushToken("t-legacy", PushProvider.FCM) } + null + } catch (e: SdkException) { + e + } + val token = sdk.notifications.getPushToken() + sdk.notifications.setCallbacks(PushCallbacks(onClicked = { })) + threads.awaitIdle() + Thread.sleep(200) + + assertEquals(List(5) { SdkResult.Failure(SdkError.NotInitialized) }, ends) + assertEquals(SdkError.NotInitialized, thrown?.error) + assertTrue("${thrown?.message}", thrown?.message.orEmpty().contains("Rees46.initializeBridge")) + assertNull(token) + assertNull("the legacy core keeps its callbacks as they were", sdk.pushCallbacks) + assertTrue("$seen", seen.none { it.first.startsWith("track/") || it.first == "mobile_push_tokens" }) + val mismatches = logged.filter { it.code == LogCodes.CORE_FLAG_MISMATCH && it.context["call"].toString().startsWith("notifications.") } + val calls = mismatches.map { it.context["call"] }.toSet() + assertEquals( + setOf( + NotificationsApiImpl.TRACK_DELIVERED, NotificationsApiImpl.TRACK_OPENED, NotificationsApiImpl.TRACK_CLICKED, + NotificationsApiImpl.TRACK_CLOSED, NotificationsApiImpl.SET_PUSH_TOKEN, NotificationsApiImpl.GET_PUSH_TOKEN, + NotificationsApiImpl.SET_CALLBACKS, + ), + calls, + ) + assertTrue(mismatches.all { it.level == LogLevel.WARNING }) + } + + @Test + fun `an instance never initialized refuses every call`() { + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { Dispatchers.Unconfined }) } + + assertEquals(SdkResult.Failure(SdkError.NotInitialized), ended { sdk.notifications.trackDelivered("m-9", "bulk", it) }) + assertEquals(SdkResult.Failure(SdkError.NotInitialized), setPushToken(sdk, "t-none", PushProvider.FCM)) + assertNull(sdk.notifications.getPushToken()) + sdk.notifications.setCallbacks(PushCallbacks()) + assertTrue(seen.isEmpty()) + } + + @Test + fun `Java does not see the namespace`() { + val getters = SDK::class.java.methods.filter { it.name == "getNotifications" } + + assertTrue(getters.isNotEmpty() && getters.all { it.isSynthetic }) + } + + private companion object { + const val SHOP = "notifications-namespace-shop" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/predict/PredictApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/predict/PredictApiFixturesTest.kt new file mode 100644 index 00000000..971470d8 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/predict/PredictApiFixturesTest.kt @@ -0,0 +1,72 @@ +package com.personalization.features.predict + +import androidx.test.core.app.ApplicationProvider +import com.personalization.api.models.predict.PurchaseProbability +import com.personalization.core.BridgeApi +import com.personalization.core.internal.CoreHttpClient +import com.personalization.core.internal.NamespaceFixtures +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** `predict.getProbabilityToPurchase` against the contract's fixtures (`contract/0/predict.json`). */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class PredictApiFixturesTest { + + private val fixtures = NamespaceFixtures(SHOP) + private lateinit var predict: PredictApiImpl + + private val invoke = NamespaceFixtures.Invoke { method, _ -> + check(method == "getProbabilityToPurchase") { "unknown method $method" } + predict.getProbabilityToPurchase() + } + + @Before + fun setUp() { + fixtures.start(ApplicationProvider.getApplicationContext()) + predict = PredictApiImpl(fixtures.calls) + } + + @After + fun tearDown() = fixtures.stop() + + @Test + fun `the request goes to API v3 with no field of its own, the customer is the device's did`() { + assertEquals(1, fixtures.checkRequests(FILE, invoke, NAMESPACE)) + assertTrue(PredictApiImpl.PATH.startsWith(CoreHttpClient.API_V3_PATH)) + } + + @Test + fun `every answer of the contract reads into the probability or its error, the codes of API v3 among them`() { + val json = NamespaceFixtures.Json { value -> + (value as PurchaseProbability).let { mapOf("probability" to it.probability, "clientId" to it.clientId) } + } + + assertTrue(fixtures.checkAnswers(FILE, invoke, NAMESPACE, json) >= 12) + } + + @Test + fun `an answer without a body, not an object or without a payload is decoding`() { + assertEquals(null, PredictApiImpl.readProbability(null)) + assertEquals(null, PredictApiImpl.readProbability(org.json.JSONArray())) + assertEquals(null, PredictApiImpl.readProbability(JSONObject("""{"probability":0.4,"client_id":1}"""))) + assertEquals( + PurchaseProbability(0.73, "12345678901"), + PredictApiImpl.readProbability(JSONObject("""{"status":"success","payload":{"probability":"0.73","client_id":12345678901}}""")), + ) + } + + private companion object { + const val SHOP = "predict-shop" + const val FILE = "predict" + const val NAMESPACE = "predict" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/predict/PredictManagerTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/predict/PredictManagerTest.kt new file mode 100644 index 00000000..b99a9cc9 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/predict/PredictManagerTest.kt @@ -0,0 +1,212 @@ +package com.personalization.features.predict + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkRegistry +import com.personalization.api.params.PurchasePredictParams +import com.personalization.api.responses.predict.PurchasePredictResponse +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +/** + * The released `predictManager.getProbabilityToPurchase` on both cores: it asks `GET + * api/v3/cdp/users/probability-to-purchase` on `Rees46Config.appDomain`, never the API host's + * `predict/probability-to-purchase` (which answers `503`), reads the answer's `payload` into + * [PurchasePredictResponse] and reports a failure through `onError(code, message)` as before. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class PredictManagerTest { + + private lateinit var context: Context + private val api = MockWebServer() + private val app = MockWebServer() + private val apiRequests = LinkedBlockingQueue() + private val appRequests = LinkedBlockingQueue() + private val threads = TrackingThreads() + + @Volatile + private var appAnswer: MockResponse = MockResponse().setBody("{}") + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + QueueStore.reset() + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + api.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + apiRequests += request + val path = request.requestUrl?.encodedPath?.removePrefix("/") + return when (path) { + "init" -> MockResponse().setBody("""{"did":"D1","seance":"S1"}""") + OLD_PATH -> MockResponse().setResponseCode(503) + else -> MockResponse().setBody("{}") + } + } + } + app.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + appRequests += request + return appAnswer + } + } + api.start() + app.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + api.shutdown() + app.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + QueueStore.reset() + } + + private fun config() = Rees46Config( + shopId = SHOP, + apiDomain = api.url("/").toString().trimEnd('/'), + appDomain = app.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + + private fun sdk(coreV2: Boolean): SDK { + val sdk = SDK() + sdk.initializeWith(context, config(), coreV2 = coreV2) + runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } + return sdk + } + + /** The one callback [sdk]'s call ends in: the response, or `code:message`. */ + private fun call(sdk: SDK, params: PurchasePredictParams = PurchasePredictParams()): Any { + val ends = LinkedBlockingQueue() + sdk.predictManager.getProbabilityToPurchase( + params = params, + onSuccess = { ends += it }, + onError = { code, message -> ends += "$code:$message" }, + ) + val end = ends.poll(10, TimeUnit.SECONDS) + assertNotNull("no callback", end) + threads.awaitIdle() + assertNull("one callback only", ends.poll(300, TimeUnit.MILLISECONDS)) + return end!! + } + + private fun bothCores(block: (coreV2: Boolean, SDK) -> Unit) { + listOf(false, true).forEach { coreV2 -> + SdkRegistry.all().forEach { it.release() } + SdkRegistry.reset() + Rees46.reset() + appRequests.clear() + apiRequests.clear() + block(coreV2, sdk(coreV2)) + } + } + + @Test + fun `it asks API v3 on the shop's appDomain with the device's did and no contacts, and reads the payload`() = bothCores { coreV2, sdk -> + appAnswer = MockResponse().setBody("""{"status":"success","payload":{"probability":0.37,"client_id":81412233}}""") + + val end = call(sdk, PurchasePredictParams(email = "buyer@example.com", phone = "70000000000", telegramId = "1", loyaltyId = "L1")) + + assertEquals("core v2: $coreV2", PurchasePredictResponse(probability = 0.37, clientId = "81412233"), end) + val request = appRequests.single() + assertEquals("GET", request.method) + assertEquals("/$PATH", request.requestUrl?.encodedPath) + val query = request.requestUrl!! + assertEquals(SHOP, query.queryParameter("shop_id")) + assertEquals("D1", query.queryParameter("did")) + listOf("email", "phone", "telegram_id", "loyalty_id").forEach { assertNull("core v2: $coreV2, $it", query.queryParameter(it)) } + assertTrue("core v2: $coreV2", apiRequests.none { it.requestUrl?.encodedPath?.removePrefix("/") in setOf(OLD_PATH, PATH) }) + } + + @Test + fun `a customer the server does not know is probability 0 with an empty client id`() = bothCores { coreV2, sdk -> + appAnswer = MockResponse().setBody("""{"status":"success","payload":{"probability":0,"client_id":null}}""") + + assertEquals("core v2: $coreV2", PurchasePredictResponse(probability = 0.0, clientId = ""), call(sdk)) + } + + @Test + fun `an answer outside 2xx is onError with its code and body`() = bothCores { coreV2, sdk -> + listOf(400, 402, 403, 404).forEach { code -> + val body = """{"status":"fail","message":"error $code"}""" + appAnswer = MockResponse().setResponseCode(code).setBody(body) + + assertEquals("core v2: $coreV2", "$code:$body", call(sdk)) + } + } + + @Test + fun `a 2xx without a numeric probability is onError -1`() = bothCores { coreV2, sdk -> + listOf( + """{"status":"success","payload":{"client_id":5}}""", + """{"status":"success","payload":{"probability":"high","client_id":5}}""", + """{"probability":0.4,"client_id":5}""", + "", + ).forEach { body -> + appAnswer = MockResponse().setBody(body) + + val end = call(sdk) + + assertTrue("core v2: $coreV2, $body: $end", end is String && end.startsWith("-1:")) + } + } + + private companion object { + const val SHOP = "predict-manager-shop" + const val PATH = "api/v3/cdp/users/probability-to-purchase" + const val OLD_PATH = "predict/probability-to-purchase" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/products/CatalogNamespacesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/products/CatalogNamespacesTest.kt new file mode 100644 index 00000000..afc90d97 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/products/CatalogNamespacesTest.kt @@ -0,0 +1,248 @@ +package com.personalization.features.products + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.SdkRegistry +import com.personalization.api.models.products.Product +import com.personalization.api.models.products.ProductsListRequest +import com.personalization.api.models.recommendations.RecommendationRequest +import com.personalization.api.models.search.SearchFullRequest +import com.personalization.api.models.search.SearchInstantResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.HeldMain +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.features.collection.CollectionsApiImpl +import com.personalization.features.recommendation.RecommendationsApiImpl +import com.personalization.features.search.SearchApiImpl +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue + +/** + * The catalog's namespaces — `sdk.products`, `sdk.collections`, `sdk.recommendations`, `sdk.search` — as a + * bridge calls them: on the new core they ask the server and answer in both forms; on the legacy core, + * where apps run, every method fails with `notInitialized`, whatever its arguments, and sends nothing. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class CatalogNamespacesTest { + + private lateinit var context: Context + private val server = MockWebServer() + private val paths = LinkedBlockingQueue() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val threads = TrackingThreads() + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.requestUrl?.encodedPath?.removePrefix("/") ?: return MockResponse().setResponseCode(400) + paths += path + return when (path) { + "init" -> MockResponse().setBody("""{"did":"D1","seance":"S1"}""") + ProductsApiImpl.INFO_PATH -> MockResponse().setBody(PRODUCT) + CollectionsApiImpl.PATH + "12" -> MockResponse().setBody("""{"products":[$PRODUCT]}""") + RecommendationsApiImpl.PATH + "block-1" -> MockResponse().setBody("""{"id":1,"recommends":[$PRODUCT]}""") + SearchApiImpl.SEARCH_PATH -> MockResponse().setBody("""{"search_query":"shoes","products":[$PRODUCT]}""") + else -> MockResponse().setBody("{}") + } + } + } + server.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + server.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + private fun config() = Rees46Config( + shopId = SHOP, + apiDomain = server.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + + private fun awaitState(sdk: SDK, state: SdkState) = runBlocking { + withTimeout(5_000) { sdk.instanceState.changes.first { it == state } } + } + + private fun outcome(block: suspend () -> T): SdkResult = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { block() } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + /** The paths the server got, after the calls so far had time to arrive. */ + private fun sent(): List { + threads.awaitIdle() + Thread.sleep(200) + return generateSequence { paths.poll() }.toList() + } + + @Test + fun `a bridge's instance gets each namespace's answer from the server`() { + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + + assertEquals(SdkResult.Success(SHOES), outcome { sdk.products.getInfo("37") }) + assertEquals(SdkResult.Success(listOf(SHOES)), outcome { sdk.collections.get("12").products }) + assertEquals(SdkResult.Success(listOf("37")), outcome { sdk.recommendations.get("block-1").itemIds }) + assertEquals(SdkResult.Success(listOf(SHOES)), outcome { sdk.search.full("shoes").products }) + val sent = sent() + assertTrue(sent.toString(), sent.containsAll(listOf("products/get", "collection/12", "recommend/block-1", "search"))) + } + + @Test + fun `the form with a listener ends once, on the main thread`() { + val main = HeldMain() + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } + sdk.initializeWith(context, config(), coreV2 = true) + awaitState(sdk, SdkState.READY) + val ends = CopyOnWriteArrayList, Boolean>>() + + sdk.search.instant("shoes", null, null, null, CompletionListener { ends += it to (Looper.myLooper() == Looper.getMainLooper()) }) + while (ends.isEmpty() && main.runNext()) Unit + main.runNext(timeoutMs = 200) + + assertEquals(1, ends.size) + assertEquals(SearchInstantResponse(searchQuery = "shoes", products = listOf(SHOES)), (ends[0].first as SdkResult.Success).value) + assertTrue(ends[0].second) + } + + @Test + fun `an app's instance on the legacy core gets notInitialized from every method, whatever its arguments, and sends nothing`() { + val main = HeldMain() + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } + sdk.initializeWith(context, config(), coreV2 = false) + awaitState(sdk, SdkState.READY) + sent() + val calls: Map Any?> = mapOf( + ProductsApiImpl.GET_INFO to { sdk.products.getInfo("") }, + ProductsApiImpl.GET_LIST to { sdk.products.getList(ProductsListRequest(limit = 0)) }, + ProductsApiImpl.GET_COUNTERS to { sdk.products.getCounters("37") }, + ProductsApiImpl.GET_CATEGORY to { sdk.products.getCategory("5") }, + CollectionsApiImpl.GET to { sdk.collections.get("") }, + RecommendationsApiImpl.GET to { sdk.recommendations.get("block-1", RecommendationRequest(limit = 0)) }, + SearchApiImpl.BLANK to { sdk.search.blank() }, + SearchApiImpl.INSTANT to { sdk.search.instant("") }, + SearchApiImpl.FULL to { sdk.search.full("shoes", SearchFullRequest(page = 0)) }, + ) + + calls.forEach { (call, block) -> assertEquals(call, SdkResult.Failure(SdkError.NotInitialized), outcome { block() }) } + val ends = CopyOnWriteArrayList>() + sdk.products.getInfo("37", CompletionListener { ends += it }) + while (ends.isEmpty() && main.runNext()) Unit + + assertEquals(listOf>(SdkResult.Failure(SdkError.NotInitialized)), ends) + assertTrue(sent().none { it != "init" }) + calls.keys.forEach { call -> + assertTrue(call, logged.any { it.code == LogCodes.CORE_FLAG_MISMATCH && it.context["call"] == call }) + } + } + + @Test + fun `an instance never initialized gets notInitialized`() { + val sdk = SDK() + + assertEquals(SdkResult.Failure(SdkError.NotInitialized), outcome { sdk.products.getInfo("37") }) + assertEquals(SdkResult.Failure(SdkError.NotInitialized), outcome { sdk.search.blank() }) + assertTrue(sent().isEmpty()) + } + + @Test + fun `a bridge's instance checks the arguments before any request`() { + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + sent() + + val outcome = outcome { sdk.products.getList(ProductsListRequest(priceMin = 10.0, priceMax = 1.0)) } + + assertTrue("$outcome", outcome is SdkResult.Failure && outcome.error is SdkError.InvalidArgument) + assertTrue(sent().isEmpty()) + } + + @Test + fun `Java does not see the namespaces`() { + listOf("getProducts", "getCollections", "getRecommendations", "getSearch").forEach { name -> + val getters = SDK::class.java.methods.filter { it.name == name } + assertTrue(name, getters.isNotEmpty() && getters.all { it.isSynthetic }) + } + } + + private companion object { + const val SHOP = "catalog-namespace-shop" + const val PRODUCT = """{"id":"37","name":"Shoes","url":"https://shop.example/p/37","price":4990,"currency":"USD"}""" + val SHOES = Product(id = "37", name = "Shoes", url = "https://shop.example/p/37", price = 4990.0, currency = "USD") + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/products/ProductsApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/products/ProductsApiFixturesTest.kt new file mode 100644 index 00000000..b22e8153 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/products/ProductsApiFixturesTest.kt @@ -0,0 +1,137 @@ +package com.personalization.features.products + +import com.personalization.api.models.products.CategoryRequest +import com.personalization.api.models.products.ProductsListRequest +import com.personalization.api.models.products.SortBy +import com.personalization.api.models.products.SortDirection +import com.personalization.api.responses.products.product.ProductParam +import com.personalization.core.SdkResult +import com.personalization.core.BridgeApi +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.argDouble +import com.personalization.core.internal.argInt +import com.personalization.core.internal.argString +import com.personalization.core.internal.argStringLists +import com.personalization.core.internal.argStrings +import okhttp3.mockwebserver.MockResponse +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** `sdk.products` against the contract's fixtures (`contract/0/products.json`): the requests and how each answer reads. */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class ProductsApiFixturesTest { + + private val fixtures = NamespaceFixtures("products-shop") + private lateinit var products: ProductsApiImpl + + @Before + fun setUp() { + fixtures.start() + products = ProductsApiImpl(fixtures.calls) + } + + @After + fun tearDown() = fixtures.stop() + + private val invoke = NamespaceFixtures.Invoke { method, args -> + when (method) { + "getInfo" -> products.getInfo(args.getString("itemId")) + "getList" -> products.getList(args.optJSONObject("request")?.let(::listRequest) ?: ProductsListRequest()) + "getCounters" -> products.getCounters(args.getString("itemId")) + "getCategory" -> products.getCategory( + args.getString("categoryId"), + args.optJSONObject("request")?.let(::categoryRequest) ?: CategoryRequest(), + ) + else -> error("no products.$method") + } + } + + @Test + fun `every method makes the contract's request, or fails with invalidArgument and sends nothing`() { + fixtures.checkRequests("products", invoke) { MockResponse().setBody("""{"products":[]}""") } + fixtures.checkErrors("products", invoke) + } + + @Test + fun `every method reads each answer of the contract into its result or its error`() { + fixtures.checkAnswers("products", invoke) + } + + /** + * The product card (`products/get`) sends `params` as an object of the parameter's name → `{"value", "searchable"}`, + * not as the lists' `[{"key", "values"}]`: the shape of the live answer, anonymized. + */ + @Test + fun `a product card's params come as an object of the parameter's name, read in the card's order`() { + fixtures.server.enqueue( + MockResponse().setBody( + """{"uniqid":"1001","id":"1001","name":"Наушники","url":"https://shop.example/product/1001","price":"69990.0", + "currency":"₽","params":{"merchant":{"value":["Shop"],"searchable":true}, + "stickers":{"value":["{\"slug\": \"0_0_24\", \"title\": \"0-0-24\"}"],"searchable":true}, + "Цвет":{"value":["Белый"],"searchable":true},"Время автономной работы, ч":{"value":[5, 30.5],"searchable":false}, + "Модель":{"value":"A1","searchable":true},"Серия":["S1","S2"],"":{"value":["no key"]}}, + "locations":{"7":{"price":69990,"stock_quantity":9999,"discount_percent":30}}}""", + ), + ) + + val card = (fixtures.outcome { products.getInfo("1001") } as SdkResult.Success).value as com.personalization.api.models.products.Product + + assertEquals( + listOf( + ProductParam("merchant", listOf("Shop")), + ProductParam("stickers", listOf("""{"slug": "0_0_24", "title": "0-0-24"}""")), + ProductParam("Цвет", listOf("Белый")), + ProductParam("Время автономной работы, ч", listOf("5", "30.5")), + ProductParam("Модель", listOf("A1")), + ProductParam("Серия", listOf("S1", "S2")), + ), + card.params, + ) + assertEquals(69990.0, card.price, 0.0) + } + + @Test + fun `an answer without a body is no product card`() { + fixtures.server.enqueue(MockResponse().setResponseCode(200)) + + assertEquals(SdkResult.Success(null), fixtures.outcome { products.getInfo("37") }) + } + + private fun listRequest(json: JSONObject) = ProductsListRequest( + categoryIds = json.argStrings("categoryIds"), + brands = json.argStrings("brands"), + merchants = json.argStrings("merchants"), + locations = json.argStrings("locations"), + priceMin = json.argDouble("priceMin"), + priceMax = json.argDouble("priceMax"), + filters = json.argStringLists("filters"), + sortBy = json.argString("sortBy")?.let(::SortBy), + sortDir = json.argString("sortDir")?.let(::sortDirection), + limit = json.argInt("limit"), + page = json.argInt("page"), + ) + + private fun categoryRequest(json: JSONObject) = CategoryRequest( + brands = json.argStrings("brands"), + locations = json.argStrings("locations"), + filters = json.argStringLists("filters"), + priceMin = json.argDouble("priceMin"), + priceMax = json.argDouble("priceMax"), + sortBy = json.argString("sortBy")?.let(::SortBy), + sortDir = json.argString("sortDir")?.let(::sortDirection), + limit = json.argInt("limit"), + page = json.argInt("page"), + ) + + companion object { + fun sortDirection(value: String): SortDirection = SortDirection.entries.first { it.value == value } + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/profile/ClientNamespacesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/profile/ClientNamespacesTest.kt new file mode 100644 index 00000000..af897b07 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/profile/ClientNamespacesTest.kt @@ -0,0 +1,224 @@ +package com.personalization.features.profile + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.SdkRegistry +import com.personalization.api.models.profile.Gender +import com.personalization.api.models.profile.Profile +import com.personalization.api.models.profile.ProfileUpdateRequest +import com.personalization.api.models.segments.Segment +import com.personalization.api.models.subscriptions.SubscriptionStatus +import com.personalization.api.models.subscriptions.SubscriptionsUpdateRequest +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.HeldMain +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.features.segments.SegmentsApiImpl +import com.personalization.features.subscriptions.SubscriptionsApiImpl +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue + +/** + * The customer's namespaces — `sdk.profile`, `sdk.subscriptions`, `sdk.segments` — as a bridge calls them: + * on the new core they ask the server and answer in both forms; on the legacy core, where apps run, every + * method that asks the server fails with `notInitialized`, whatever its arguments, and sends nothing. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class ClientNamespacesTest { + + private lateinit var context: Context + private val server = MockWebServer() + private val paths = LinkedBlockingQueue() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val threads = TrackingThreads() + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.requestUrl?.encodedPath?.removePrefix("/") ?: return MockResponse().setResponseCode(400) + paths += path + return when (path) { + "init" -> MockResponse().setBody("""{"did":"D1","seance":"S1"}""") + ProfileApiImpl.GET_PATH -> MockResponse().setBody("""{"id":"7","gender":"m"}""") + SubscriptionsApiImpl.CHECK_PATH -> MockResponse().setBody("""{"exists":true,"email_bulk":true}""") + SegmentsApiImpl.GET_PATH -> MockResponse().setBody("""[{"id":5,"type":"static"}]""") + else -> MockResponse().setBody("""{"status":"success"}""") + } + } + } + server.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + server.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + private fun config() = Rees46Config( + shopId = SHOP, + apiDomain = server.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + + private fun awaitState(sdk: SDK, state: SdkState) = runBlocking { + withTimeout(5_000) { sdk.instanceState.changes.first { it == state } } + } + + private fun outcome(block: suspend () -> T): SdkResult = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { block() } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + /** The paths the server got, after the calls so far had time to arrive. */ + private fun sent(): List { + threads.awaitIdle() + Thread.sleep(200) + return generateSequence { paths.poll() }.toList() + } + + @Test + fun `a bridge's instance gets each namespace's answer from the server`() { + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + + assertEquals(SdkResult.Success(Profile(id = "7", gender = Gender.MALE)), outcome { sdk.profile.get() }) + assertEquals(SdkResult.Success(Unit), outcome { sdk.profile.set(ProfileUpdateRequest(location = "msk")) }) + assertEquals(SdkResult.Success(SubscriptionStatus(exists = true, emailBulk = true)), outcome { sdk.subscriptions.check() }) + assertEquals(SdkResult.Success(listOf(Segment(5, "static"))), outcome { sdk.segments.get() }) + assertEquals(sdk.getSegment(), sdk.segments.getAbGroup()) + assertTrue(sdk.segments.getAbGroup() in setOf("A", "B")) + val sent = sent() + assertTrue(sent.toString(), sent.containsAll(listOf("profile", "profile/set", "subscriptions/check", "segments/get"))) + } + + @Test + fun `an app's instance on the legacy core gets notInitialized from every request, whatever its arguments, and sends nothing`() { + val main = HeldMain() + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } + sdk.initializeWith(context, config(), coreV2 = false) + awaitState(sdk, SdkState.READY) + sent() + val calls: Map Any?> = mapOf( + ProfileApiImpl.GET to { sdk.profile.get() }, + ProfileApiImpl.SET to { sdk.profile.set(ProfileUpdateRequest()) }, + ProfileApiImpl.GET_LAST_ORDER to { sdk.profile.getLastOrder() }, + SubscriptionsApiImpl.MANAGE to { sdk.subscriptions.manage(SubscriptionsUpdateRequest()) }, + SubscriptionsApiImpl.CHECK to { sdk.subscriptions.check() }, + SubscriptionsApiImpl.SUBSCRIBE_PRICE to { sdk.subscriptions.subscribeForPriceDrop("37", 0.0) }, + SubscriptionsApiImpl.UNSUBSCRIBE_PRICE to { sdk.subscriptions.unsubscribeFromPriceDrop(listOf("")) }, + SubscriptionsApiImpl.SUBSCRIBE_STOCK to { sdk.subscriptions.subscribeForBackInStock("") }, + SubscriptionsApiImpl.UNSUBSCRIBE_STOCK to { sdk.subscriptions.unsubscribeFromBackInStock(listOf("37")) }, + SegmentsApiImpl.ADD to { sdk.segments.add(0) }, + SegmentsApiImpl.REMOVE to { sdk.segments.remove(12) }, + SegmentsApiImpl.GET to { sdk.segments.get() }, + ) + + calls.forEach { (call, block) -> assertEquals(call, SdkResult.Failure(SdkError.NotInitialized), outcome { block() }) } + val ends = CopyOnWriteArrayList>() + sdk.segments.add(12, null, null, CompletionListener { ends += it }) + while (ends.isEmpty() && main.runNext()) Unit + + assertEquals(listOf>(SdkResult.Failure(SdkError.NotInitialized)), ends) + assertTrue(sent().none { it != "init" }) + calls.keys.forEach { call -> + assertTrue(call, logged.any { it.code == LogCodes.CORE_FLAG_MISMATCH && it.context["call"] == call }) + } + // The A/B group asks nothing of the server: it is there on either core. + assertEquals(sdk.getSegment(), sdk.segments.getAbGroup()) + } + + @Test + fun `an instance never initialized gets notInitialized, and an empty A-B group`() { + val sdk = SDK() + + assertEquals(SdkResult.Failure(SdkError.NotInitialized), outcome { sdk.profile.get() }) + assertEquals(SdkResult.Failure(SdkError.NotInitialized), outcome { sdk.subscriptions.check() }) + assertEquals(SdkResult.Failure(SdkError.NotInitialized), outcome { sdk.segments.get() }) + assertEquals("", sdk.segments.getAbGroup()) + assertTrue(sent().isEmpty()) + } + + @Test + fun `Java does not see the namespaces`() { + listOf("getProfile", "getSubscriptions", "getSegments").forEach { name -> + val getters = SDK::class.java.methods.filter { it.name == name } + assertTrue(name, getters.isNotEmpty() && getters.all { it.isSynthetic }) + } + } + + private companion object { + const val SHOP = "client-namespace-shop" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/profile/ProfileApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/profile/ProfileApiFixturesTest.kt new file mode 100644 index 00000000..fa936550 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/profile/ProfileApiFixturesTest.kt @@ -0,0 +1,124 @@ +package com.personalization.features.profile + +import com.personalization.api.models.profile.Gender +import com.personalization.api.models.profile.ProfileCar +import com.personalization.api.models.profile.ProfileKid +import com.personalization.api.models.profile.ProfileUpdateRequest +import com.personalization.core.BridgeApi +import com.personalization.core.SdkError +import com.personalization.core.SdkResult +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.argInt +import com.personalization.core.internal.argMap +import com.personalization.core.internal.argString +import okhttp3.mockwebserver.MockResponse +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.Date +import java.util.concurrent.CopyOnWriteArrayList + +/** `sdk.profile` against the contract's fixtures (`contract/0/profile.json`). */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class ProfileApiFixturesTest { + + private val fixtures = NamespaceFixtures("profile-shop") + private val changes = CopyOnWriteArrayList>() + private lateinit var profile: ProfileApiImpl + + @Before + fun setUp() { + fixtures.start() + profile = ProfileApiImpl(fixtures.calls) { type, signature -> changes += type to signature } + } + + @After + fun tearDown() = fixtures.stop() + + private val invoke = NamespaceFixtures.Invoke { method, args -> + when (method) { + "get" -> profile.get() + "set" -> profile.set(request(args.getJSONObject("request"))) + "getLastOrder" -> profile.getLastOrder() + else -> error("no profile.$method") + } + } + + @Test + fun `every method makes the contract's request, or fails with invalidArgument and sends nothing`() { + fixtures.checkRequests("profile", invoke) { MockResponse().setBody("[]") } + fixtures.checkErrors("profile", invoke) + } + + @Test + fun `every method reads each answer of the contract into its result or its error`() { + fixtures.checkAnswers("profile", invoke) + } + + @Test + fun `a custom property's value of a kind the API does not take is invalidArgument`() { + listOf(Date(), listOf(Date()), mapOf("at" to Date()), mapOf(1 to "a"), Double.NaN).forEach { value -> + val outcome = fixtures.outcome { profile.set(ProfileUpdateRequest(customProperties = mapOf("value" to value))) } + + assertTrue("$value: $outcome", outcome is SdkResult.Failure && outcome.error is SdkError.InvalidArgument) + } + assertEquals(0, fixtures.server.requestCount) + } + + @Test + fun `set tells popups v3 of the change once the server took it, and not when it failed`() { + fixtures.server.enqueue(MockResponse().setBody("""{"status":"success"}""")) + fixtures.server.enqueue(MockResponse().setResponseCode(400)) + + fixtures.outcome { profile.set(ProfileUpdateRequest(location = "msk")) } + fixtures.outcome { profile.set(ProfileUpdateRequest(location = "spb")) } + + assertEquals(listOf(ProfileApiImpl.SET_PATH to """{"location":"msk"}"""), changes) + } + + @Test + fun `an answer to getLastOrder without a body is no order`() { + fixtures.server.enqueue(MockResponse().setResponseCode(200)) + + assertEquals(SdkResult.Success(emptyList()), fixtures.outcome { profile.getLastOrder() }) + } + + private fun request(json: JSONObject) = ProfileUpdateRequest( + email = json.argString("email"), + phone = json.argString("phone"), + externalId = json.argString("externalId"), + loyaltyId = json.argString("loyaltyId"), + telegramId = json.argString("telegramId"), + fbId = json.argString("fbId"), + vkId = json.argString("vkId"), + firstName = json.argString("firstName"), + lastName = json.argString("lastName"), + gender = json.argString("gender")?.let(::gender), + birthday = json.argString("birthday"), + age = json.argInt("age"), + location = json.argString("location"), + kids = json.optJSONArray("kids")?.let { array -> + List(array.length()) { index -> + val kid = array.getJSONObject(index) + ProfileKid(gender = kid.argString("gender")?.let(::gender), birthday = kid.argString("birthday")) + } + }, + cars = json.optJSONArray("cars")?.let { array -> + List(array.length()) { index -> + val car = array.getJSONObject(index) + ProfileCar(brand = car.argString("brand"), model = car.argString("model"), vds = car.argString("vds")) + } + }, + customProperties = json.argMap("customProperties"), + ) + + private fun gender(name: String): Gender = Gender.entries.first { it.name.lowercase() == name } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/recommendation/RecommendationsApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/recommendation/RecommendationsApiFixturesTest.kt new file mode 100644 index 00000000..652ffb38 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/recommendation/RecommendationsApiFixturesTest.kt @@ -0,0 +1,87 @@ +package com.personalization.features.recommendation + +import com.personalization.api.models.recommendations.RecommendationRequest +import com.personalization.api.models.recommendations.RecommendationResponse +import com.personalization.core.SdkResult +import com.personalization.core.BridgeApi +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.argBoolean +import com.personalization.core.internal.argInt +import com.personalization.core.internal.argString +import com.personalization.core.internal.argStrings +import okhttp3.mockwebserver.MockResponse +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** `sdk.recommendations` against the contract's fixtures (`contract/0/recommendations.json`). */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class RecommendationsApiFixturesTest { + + private val fixtures = NamespaceFixtures("recommendations-shop") + private lateinit var recommendations: RecommendationsApiImpl + + @Before + fun setUp() { + fixtures.start() + recommendations = RecommendationsApiImpl(fixtures.calls) + } + + @After + fun tearDown() = fixtures.stop() + + private val invoke = NamespaceFixtures.Invoke { method, args -> + when (method) { + "get" -> recommendations.get( + args.getString("code"), + args.optJSONObject("request")?.let(::request) ?: RecommendationRequest(), + ) + else -> error("no recommendations.$method") + } + } + + @Test + fun `get makes the contract's request, or fails with invalidArgument and sends nothing`() { + fixtures.checkRequests("recommendations", invoke) { MockResponse().setBody("""{"recommends":[]}""") } + fixtures.checkErrors("recommendations", invoke) + } + + @Test + fun `get reads each answer of the contract into its result or its error`() { + fixtures.checkAnswers("recommendations", invoke) + } + + @Test + fun `a blank title or link of the block is no value, as on iOS`() { + fixtures.server.enqueue(MockResponse().setBody("""{"title":"","link":" ","recommends":["1"]}""")) + + val result = fixtures.outcome { recommendations.get("block-1") } + + assertTrue("$result", result is SdkResult.Success) + val response = (result as SdkResult.Success).value as RecommendationResponse + assertNull(response.title) + assertNull(response.link) + assertEquals(listOf("1"), response.itemIds) + } + + private fun request(json: JSONObject) = RecommendationRequest( + itemId = json.argString("itemId"), + categoryId = json.argString("categoryId"), + searchQuery = json.argString("searchQuery"), + excludedItemIds = json.argStrings("excludedItemIds"), + brands = json.argStrings("brands"), + locations = json.argStrings("locations"), + limit = json.argInt("limit"), + extended = json.argBoolean("extended") ?: true, + withLocations = json.argBoolean("withLocations") ?: false, + ) +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/reviews/ReviewsApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/reviews/ReviewsApiFixturesTest.kt new file mode 100644 index 00000000..59544d6c --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/reviews/ReviewsApiFixturesTest.kt @@ -0,0 +1,327 @@ +package com.personalization.features.reviews + +import androidx.test.core.app.ApplicationProvider +import com.personalization.api.responses.reviews.CesCampaign +import com.personalization.api.responses.reviews.ClientReview +import com.personalization.api.responses.reviews.CsatCampaign +import com.personalization.api.responses.reviews.NpsCategory +import com.personalization.api.responses.reviews.PollChannel +import com.personalization.api.responses.reviews.PollReview +import com.personalization.api.responses.reviews.ProductRatingSummary +import com.personalization.api.responses.reviews.ProductReview +import com.personalization.api.responses.reviews.ProductReviewsResponse +import com.personalization.api.responses.reviews.ReviewState +import com.personalization.core.BridgeApi +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.internal.ContractFixtures +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreHttpClient +import com.personalization.core.internal.CoreV2 +import com.personalization.core.internal.FakeConnectivity +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.startedCoreInit +import com.personalization.logs.SdkLogs +import com.personalization.sdk.domain.repositories.UserSettingsRepository +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.TimeUnit + +/** + * `sdk.reviews` against the contract's fixtures (`contract/0/reviews.json`): the request each call makes and + * on which host — the polls on the host of API v3, the reviews of products on the API's —, the calls it + * refuses before a request, and how it reads each answer. + * + * `reviews.json` is written in the fixtures' format from `contract/reviews.md` and the API's pages of + * `feedback/` ahead of the contract's own file, which takes it over as it is; the iOS SDK tests by the same + * file. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class ReviewsApiFixturesTest { + + /** The API's host (`apiDomain`) and the host of API v3 (`appDomain`). */ + private val api = MockWebServer() + private val app = MockWebServer() + private val connectivity = FakeConnectivity(connected = true) + private val settings = mockk(relaxed = true) { + every { getShopId() } returns SHOP + every { getDid() } returns "did-1" + every { getSid() } returns "sid-1" + every { getStream() } returns "android" + every { getSegmentForABTesting() } returns "B" + } + private lateinit var core: CoreV2 + private lateinit var reviews: ReviewsApiImpl + + /** What both hosts answer. */ + @Volatile + private var answer: MockResponse = MockResponse().setBody("{}") + + @Before + fun setUp() { + SdkLogs.reset() + val dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse = answer + } + api.dispatcher = dispatcher + app.dispatcher = dispatcher + api.start() + app.start() + reviews = reviewsWith { app.url("/").toString() } + } + + private fun reviewsWith(appUrl: () -> String): ReviewsApiImpl { + val client = CoreHttpClient({ api.url("/").toString() }, settings, connectivity, SHOP, appUrl = appUrl) + core = CoreV2(client, SHOP).also { + it.init = startedCoreInit(ApplicationProvider.getApplicationContext(), settings, connectivity, SHOP) + } + return ReviewsApiImpl(NamespaceCalls(core = { core }, dispatchers = { CoreDispatchers.DEFAULT }, shopId = { SHOP })) + } + + @After + fun tearDown() { + core.release() + api.close() + app.close() + SdkLogs.reset() + } + + private fun outcome(case: JSONObject): SdkResult = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { invoke(case.getJSONObject("call")) } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + /** The method a case calls, with its arguments by the contract's names. */ + private suspend fun invoke(call: JSONObject): Any { + assertEquals("reviews", call.getString("namespace")) + val args = call.getJSONObject("args") + return when (val method = call.getString("method")) { + "createNps" -> reviews.createNps( + args.getInt("rate"), args.getString("channel"), args.getString("category"), + args.text("orderId"), args.text("comment"), args.text("label"), + ) + "createCsat" -> reviews.createCsat( + args.getInt("rate"), args.getString("channel"), args.getString("campaign"), + args.text("orderId"), args.text("comment"), args.text("label"), + ) + "createCes" -> reviews.createCes( + args.getInt("rate"), args.getString("channel"), args.getString("campaign"), + args.text("orderId"), args.text("comment"), args.text("label"), + ) + "getNpsCategories" -> reviews.getNpsCategories() + "getNpsChannels" -> reviews.getNpsChannels() + "getCsatCampaigns" -> reviews.getCsatCampaigns() + "getCesCampaigns" -> reviews.getCesCampaigns() + "getProductReviews" -> reviews.getProductReviews(args.getString("itemId"), args.number("limit"), args.number("offset")) + "getClientReviews" -> reviews.getClientReviews(args.getString("orderId")) + else -> error("unknown method reviews.$method") + } + } + + @Test + fun `every call makes the contract's request on its host, with no field of its own beside the common ones`() { + val cases = ContractFixtures.requests("reviews") + assertTrue(cases.size >= 12) + var onApp = 0 + var onApi = 0 + cases.forEach { case -> + val name = case.getString("name") + val expected = case.getJSONObject("request") + val method = case.getJSONObject("call").getString("method") + val host = if (method in ON_APP_DOMAIN) app.also { onApp++ } else api.also { onApi++ } + + outcome(case) + + val recorded = requireNotNull(host.takeRequest(5, TimeUnit.SECONDS)) { "$name: no request on its host" } + val url = recorded.requestUrl!! + assertEquals(name, expected.getString("method"), recorded.method) + assertEquals(name, "/" + expected.getString("path"), url.encodedPath) + if (expected.getString("method") == "GET") { + val query = expected.getJSONObject("query") + assertEquals(name, query.keys().asSequence().toSet(), url.queryParameterNames - COMMON_FIELDS) + query.keys().forEach { key -> assertEquals(name, query.getString(key), url.queryParameter(key)) } + // The core adds the common fields; the core's own tests check their values. + assertEquals(name, COMMON_FIELDS, url.queryParameterNames intersect COMMON_FIELDS) + } else { + val body = JSONObject(recorded.body.readUtf8()) + val fields = expected.getJSONObject("body") + assertEquals(name, fields.keys().asSequence().toSet(), body.keys().asSequence().toSet() - COMMON_FIELDS) + // The JSON types too: the rating goes as a number. + fields.keys().forEach { key -> assertEquals("$name: $key", fields.get(key), body.get(key)) } + assertEquals(name, COMMON_FIELDS, body.keys().asSequence().toSet() intersect COMMON_FIELDS) + } + } + // Nothing went to the other host. + assertEquals(onApp, app.requestCount) + assertEquals(onApi, api.requestCount) + } + + @Test + fun `a call the contract refuses fails with invalidArgument and sends nothing`() { + val cases = ContractFixtures.cases("reviews").filter { it.has("error") } + assertTrue(cases.size >= 10) + cases.forEach { case -> + assertEquals(case.getString("name"), "invalidArgument", case.getJSONObject("error").getString("type")) + + val outcome = outcome(case) + + assertTrue("${case.getString("name")}: $outcome", (outcome as? SdkResult.Failure)?.error is SdkError.InvalidArgument) + } + assertEquals(0, app.requestCount + api.requestCount) + } + + @Test + fun `every answer of the contract reads into its result or its error`() { + val cases = ContractFixtures.answers("reviews") + assertTrue(cases.size >= 20) + cases.forEach { case -> + val name = case.getString("name") + val response = ContractFixtures.mockResponse(case) + // No answer: the request finds no network. + connectivity.set(response != null) + response?.let { answer = it } + val expect = case.getJSONObject("expect") + + val outcome = outcome(case) + + if (expect.has("result")) { + val method = case.getJSONObject("call").getString("method") + assertEquals(name, SdkResult.Success(expected(method, expect.get("result"))), outcome) + } else { + assertEquals(name, SdkResult.Failure(ContractFixtures.errorOf(expect.getJSONObject("error"))), outcome) + } + } + } + + @Test + fun `an answer without a body is an empty result, and decoding for a rating, which has none`() { + answer = MockResponse().setResponseCode(200) + + assertEquals(emptyList(), runBlocking { reviews.getNpsCategories() }) + assertEquals(emptyList(), runBlocking { reviews.getNpsChannels() }) + assertEquals(emptyList(), runBlocking { reviews.getCsatCampaigns() }) + assertEquals(emptyList(), runBlocking { reviews.getCesCampaigns() }) + assertEquals(emptyList(), runBlocking { reviews.getClientReviews("ORDER-1") }) + assertEquals( + ProductReviewsResponse(ProductRatingSummary(count = 0, averageRating = null, ratings = emptyMap()), emptyList()), + runBlocking { reviews.getProductReviews("SKU-1") }, + ) + assertEquals(SdkError.Decoding, failure { reviews.createNps(9, "android_app", "delivery") }) + } + + @Test + fun `the host of API v3 is app rees46 ru unless appDomain names another`() { + assertEquals("https://app.rees46.ru/", CoreHttpClient.appUrlOf(null)) + assertEquals("https://app.rees46.ru/", CoreHttpClient.appUrlOf(" ")) + assertEquals("https://app.cluster.example/", CoreHttpClient.appUrlOf("app.cluster.example")) + assertEquals("https://app.cluster.example/", CoreHttpClient.appUrlOf("https://app.cluster.example/")) + } + + @Test + fun `an appDomain that makes no URL fails the poll's request with invalidArgument, and the API's requests still go`() { + core.release() + reviews = reviewsWith { CoreHttpClient.appUrlOf("ftp://app.example") } + answer = MockResponse().setBody("""{"status":"success","payload":{"reviews":[]}}""") + + val error = failure { reviews.createNps(9, "android_app", "delivery") } + + assertTrue("$error", error is SdkError.InvalidArgument) + assertEquals(emptyList(), runBlocking { reviews.getClientReviews("ORDER-1") }) + assertEquals(0, app.requestCount) + assertNotNull(api.takeRequest(5, TimeUnit.SECONDS)) + } + + private fun failure(block: suspend () -> Any): SdkError? = try { + runBlocking { withTimeout(10_000) { block() } } + null + } catch (e: SdkException) { + e.error + } + + /** The value of a method by the contract's field names in a case's `result`. */ + private fun expected(method: String, result: Any): Any = when (method) { + "createNps", "createCsat", "createCes" -> PollReview((result as JSONObject).getLong("id")) + "getNpsCategories" -> (result as JSONArray).objects().map { + NpsCategory( + it.getString("code"), it.getString("name"), + it.text("detractorQuestion"), it.text("passiveQuestion"), it.text("promoterQuestion"), + it.text("detractorSuccess"), it.text("passiveSuccess"), it.text("promoterSuccess"), it.text("buttonLabel"), + ) + } + "getNpsChannels" -> (result as JSONArray).objects().map { PollChannel(it.getString("code"), it.getString("name")) } + "getCsatCampaigns" -> (result as JSONArray).objects().map { + CsatCampaign( + it.getString("code"), it.getString("name"), + it.text("dissatisfiedQuestion"), it.text("neutralQuestion"), it.text("satisfiedQuestion"), + it.text("dissatisfiedSuccess"), it.text("neutralSuccess"), it.text("satisfiedSuccess"), it.text("buttonLabel"), + ) + } + "getCesCampaigns" -> (result as JSONArray).objects().map { + CesCampaign( + it.getString("code"), it.getString("name"), + it.text("difficultQuestion"), it.text("neutralQuestion"), it.text("easyQuestion"), + it.text("difficultSuccess"), it.text("neutralSuccess"), it.text("easySuccess"), it.text("buttonLabel"), + ) + } + "getProductReviews" -> (result as JSONObject).let { response -> + val summary = response.getJSONObject("summary") + val ratings = summary.getJSONObject("ratings") + ProductReviewsResponse( + summary = ProductRatingSummary( + count = summary.getInt("count"), + averageRating = if (summary.isNull("averageRating")) null else summary.getDouble("averageRating"), + ratings = ratings.keys().asSequence().associate { it.toInt() to ratings.getInt(it) }, + ), + reviews = response.getJSONArray("reviews").objects().map { + ProductReview(it.getLong("id"), it.getInt("rating"), it.text("comment"), it.text("author"), it.getString("createdAt")) + }, + ) + } + "getClientReviews" -> (result as JSONArray).objects().map { + ClientReview( + id = it.getLong("id"), itemId = it.getString("itemId"), orderId = it.getString("orderId"), + rating = it.getInt("rating"), comment = it.text("comment"), + state = it.text("state")?.let { state -> ReviewState.entries.single { value -> value.value == state } }, + createdAt = it.getString("createdAt"), + ) + } + else -> error("unknown method reviews.$method") + } + + private fun JSONArray.objects(): List = List(length()) { getJSONObject(it) } + + private fun JSONObject.text(key: String): String? = if (isNull(key)) null else getString(key) + + private fun JSONObject.number(key: String): Int? = if (isNull(key)) null else getInt(key) + + private companion object { + const val SHOP = "reviews-shop" + val COMMON_FIELDS = setOf("shop_id", "did", "sid", "seance", "segment", "stream") + + /** The methods the contract sends to `appDomain`; the rest go to `apiDomain`. */ + val ON_APP_DOMAIN = setOf( + "createNps", "createCsat", "createCes", "getNpsCategories", "getNpsChannels", "getCsatCampaigns", "getCesCampaigns", + ) + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/reviews/ReviewsNamespaceTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/reviews/ReviewsNamespaceTest.kt new file mode 100644 index 00000000..24e11c70 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/reviews/ReviewsNamespaceTest.kt @@ -0,0 +1,300 @@ +package com.personalization.features.reviews + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.SdkRegistry +import com.personalization.api.managers.ReviewsApi +import com.personalization.api.responses.reviews.NpsCategory +import com.personalization.api.responses.reviews.PollReview +import com.personalization.api.responses.reviews.ProductRatingSummary +import com.personalization.api.responses.reviews.ProductReviewsResponse +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.HeldMain +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue + +/** + * `sdk.reviews` as a bridge calls it: on the new core the polls go to `Rees46Config.appDomain` and the reviews + * of products to `apiDomain`, in both forms; on the legacy core, where apps run, every method fails with + * `notInitialized` and sends nothing. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class ReviewsNamespaceTest { + + private lateinit var context: Context + + /** `apiDomain` and `appDomain`; [requests] gets what each received, as `api:` or `app:`. */ + private val api = MockWebServer() + private val app = MockWebServer() + private val requests = LinkedBlockingQueue>() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val threads = TrackingThreads() + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + api.dispatcher = recording(API) { path -> + when (path) { + "init" -> MockResponse().setBody("""{"did":"D1","seance":"S1"}""") + ReviewsApiImpl.PRODUCT_REVIEWS -> MockResponse().setBody(PRODUCT_REVIEWS) + else -> MockResponse().setBody("{}") + } + } + app.dispatcher = recording(APP) { path -> + when (path) { + ReviewsApiImpl.NPS_REVIEWS -> MockResponse().setBody("""{"status":"success","payload":{"review":{"id":1}}}""") + ReviewsApiImpl.NPS_CATEGORIES -> MockResponse().setBody(CATEGORIES) + else -> MockResponse().setResponseCode(404) + } + } + api.start() + app.start() + } + + private fun recording(host: String, answer: (String) -> MockResponse) = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.requestUrl?.encodedPath?.removePrefix("/") ?: return MockResponse().setResponseCode(400) + requests += "$host:$path" to request + return answer(path) + } + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + api.shutdown() + app.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + private fun config() = Rees46Config( + shopId = SHOP, + apiDomain = api.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + appDomain = app.url("/").toString().trimEnd('/'), + ) + + private fun awaitState(sdk: SDK, state: SdkState) = runBlocking { + withTimeout(5_000) { sdk.instanceState.changes.first { it == state } } + } + + private fun outcome(block: suspend () -> T): SdkResult = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { block() } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + /** What the hosts got, `host:path` with the request, after the calls so far had time to arrive. */ + private fun sent(): List> { + threads.awaitIdle() + Thread.sleep(200) + return generateSequence { requests.poll() }.toList() + } + + private fun bridgeSdk(): SDK = Rees46.initializeBridge(context, config()).also { awaitState(it, SdkState.READY) } + + @Test + fun `a bridge's instance sends the polls to appDomain and the reviews of products to apiDomain`() { + val sdk = bridgeSdk() + sent() + + assertEquals(SdkResult.Success(PollReview(1)), outcome { sdk.reviews.createNps(9, "android_app", "delivery", orderId = "ORDER-1") }) + assertEquals( + SdkResult.Success(ProductReviewsResponse(ProductRatingSummary(count = 0, averageRating = null, ratings = emptyMap()), emptyList())), + outcome { sdk.reviews.getProductReviews("SKU-1024", limit = 20) }, + ) + + // Whatever else the instance sends goes to apiDomain; nothing of the reviews goes twice or elsewhere. + val sent = sent().filter { (path, _) -> path.startsWith("$APP:") || path.contains("reviews/") }.toMap() + assertEquals(setOf("$APP:${ReviewsApiImpl.NPS_REVIEWS}", "$API:${ReviewsApiImpl.PRODUCT_REVIEWS}"), sent.keys) + val poll = JSONObject(sent.getValue("$APP:${ReviewsApiImpl.NPS_REVIEWS}").body.readUtf8()) + assertEquals(9, poll.get("rate")) + assertEquals("ORDER-1", poll.getString("order_id")) + // The common fields go to the host of API v3 too, with the did of this instance's /init. + assertEquals(SHOP, poll.getString("shop_id")) + assertEquals("D1", poll.getString("did")) + assertEquals("S1", poll.getString("sid")) + val product = sent.getValue("$API:${ReviewsApiImpl.PRODUCT_REVIEWS}").requestUrl!! + assertEquals("SKU-1024", product.queryParameter("product")) + assertEquals("20", product.queryParameter("limit")) + assertEquals("D1", product.queryParameter("did")) + } + + @Test + fun `the form with a listener ends once, on the main thread`() { + val main = HeldMain() + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } + sdk.initializeWith(context, config(), coreV2 = true) + awaitState(sdk, SdkState.READY) + val ends = CopyOnWriteArrayList>, Boolean>>() + + sdk.reviews.getNpsCategories(CompletionListener { ends += it to (Looper.myLooper() == Looper.getMainLooper()) }) + while (ends.isEmpty() && main.runNext()) Unit + main.runNext(timeoutMs = 200) + + assertEquals(listOf(SdkResult.Success(listOf(NpsCategory("delivery", "Доставка", promoterQuestion = "Что понравилось?"))) to true), ends) + } + + @Test + fun `an argument the contract refuses is invalidArgument, logged, and nothing is sent`() { + val sdk = bridgeSdk() + sent() + + val outcome = outcome { sdk.reviews.createCsat(6, "android_app", "support") } + + assertEquals(SdkResult.Failure(SdkError.InvalidArgument("rate must be from 1 to 5")), outcome) + assertTrue(sent().isEmpty()) + assertEquals(1, logged.count { it.code == LogCodes.INVALID_ARGUMENT && it.context["call"] == ReviewsApiImpl.CREATE_CSAT }) + } + + @Test + fun `an app's instance on the legacy core gets notInitialized from every method in both forms and sends nothing`() { + val main = HeldMain() + val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } + sdk.initializeWith(context, config(), coreV2 = false) + awaitState(sdk, SdkState.READY) + sent() + val reviews = sdk.reviews + + val thrown = SUSPENDING.map { (_, call) -> + try { + runBlocking { call(reviews) } + null + } catch (e: SdkException) { + e + } + } + val ends = CopyOnWriteArrayList>() + LISTENING.forEach { (_, call) -> call(reviews) { ends += it } } + while (ends.size < LISTENING.size && main.runNext()) Unit + + assertTrue(thrown.all { it != null && it.error == SdkError.NotInitialized && it.message.orEmpty().contains("Rees46.initializeBridge") }) + assertEquals(List(LISTENING.size) { SdkResult.Failure(SdkError.NotInitialized) }, ends.toList()) + assertTrue(sent().none { (path, _) -> path.startsWith("$APP:") || path.contains("reviews/") }) + val mismatches = logged.filter { it.code == LogCodes.CORE_FLAG_MISMATCH && it.context["call"].toString().startsWith("reviews.") } + .map { it.context["call"].toString() } + assertEquals((SUSPENDING + LISTENING).map { it.first }.sorted(), mismatches.sorted()) + // The core decides before the arguments: a refused one is notInitialized here too. + assertTrue(logged.none { it.code == LogCodes.INVALID_ARGUMENT }) + } + + @Test + fun `an instance never initialized gets notInitialized`() { + assertEquals(SdkResult.Failure(SdkError.NotInitialized), outcome { SDK().reviews.getNpsChannels() }) + assertTrue(sent().isEmpty()) + } + + @Test + fun `Java does not see the namespace`() { + val getters = SDK::class.java.methods.filter { it.name == "getReviews" } + + assertTrue(getters.isNotEmpty() && getters.all { it.isSynthetic }) + } + + private companion object { + const val SHOP = "reviews-namespace-shop" + const val API = "api" + const val APP = "app" + const val PRODUCT_REVIEWS = + """{"status":"success","payload":{"summary":{"count":0,"average_rating":null,"ratings":{}},"reviews":[]}}""" + const val CATEGORIES = + """{"status":"success","payload":{"categories":[{"code":"delivery","name":"Доставка","promoter_question":"Что понравилось?"}]}}""" + + /** Every method's suspending form by its name in the log, one of them with an argument the contract refuses. */ + val SUSPENDING: List Any>> = listOf( + ReviewsApiImpl.CREATE_NPS to { it.createNps(9, "android_app", "delivery") }, + ReviewsApiImpl.CREATE_CSAT to { it.createCsat(4, "android_app", "support") }, + ReviewsApiImpl.CREATE_CES to { it.createCes(99, "", "") }, + ReviewsApiImpl.GET_NPS_CATEGORIES to { it.getNpsCategories() }, + ReviewsApiImpl.GET_NPS_CHANNELS to { it.getNpsChannels() }, + ReviewsApiImpl.GET_CSAT_CAMPAIGNS to { it.getCsatCampaigns() }, + ReviewsApiImpl.GET_CES_CAMPAIGNS to { it.getCesCampaigns() }, + ReviewsApiImpl.GET_PRODUCT_REVIEWS to { it.getProductReviews("SKU-1") }, + ReviewsApiImpl.GET_CLIENT_REVIEWS to { it.getClientReviews("ORDER-1") }, + ) + + /** Every method's form with a listener by its name in the log; the listener gets what it ends with. */ + val LISTENING: List) -> Unit) -> Unit>> = listOf( + ReviewsApiImpl.CREATE_NPS to { r, end -> r.createNps(9, "android_app", "delivery", null, null, null, CompletionListener { end(it) }) }, + ReviewsApiImpl.CREATE_CSAT to { r, end -> r.createCsat(4, "android_app", "support", null, null, null, CompletionListener { end(it) }) }, + ReviewsApiImpl.CREATE_CES to { r, end -> r.createCes(5, "android_app", "returns", null, null, null, CompletionListener { end(it) }) }, + ReviewsApiImpl.GET_NPS_CATEGORIES to { r, end -> r.getNpsCategories(CompletionListener { end(it) }) }, + ReviewsApiImpl.GET_NPS_CHANNELS to { r, end -> r.getNpsChannels(CompletionListener { end(it) }) }, + ReviewsApiImpl.GET_CSAT_CAMPAIGNS to { r, end -> r.getCsatCampaigns(CompletionListener { end(it) }) }, + ReviewsApiImpl.GET_CES_CAMPAIGNS to { r, end -> r.getCesCampaigns(CompletionListener { end(it) }) }, + ReviewsApiImpl.GET_PRODUCT_REVIEWS to { r, end -> r.getProductReviews("SKU-1", null, null, CompletionListener { end(it) }) }, + ReviewsApiImpl.GET_CLIENT_REVIEWS to { r, end -> r.getClientReviews("ORDER-1", CompletionListener { end(it) }) }, + ) + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/search/AgentSearchNamespaceTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/search/AgentSearchNamespaceTest.kt new file mode 100644 index 00000000..c63c610d --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/search/AgentSearchNamespaceTest.kt @@ -0,0 +1,186 @@ +package com.personalization.features.search + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.SdkRegistry +import com.personalization.api.models.search.AgentDialogResponse +import com.personalization.api.models.search.AgentSession +import com.personalization.core.BridgeApi +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue + +/** + * The search agent as a bridge reaches it: `sdk.search.agentEnabled` follows the `/init` answer's + * `search.blank_mode`, and the agent's requests go to `Rees46Config.appDomain`; on the legacy core the + * agent's methods fail with `notInitialized` and `agentEnabled` stays false. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class AgentSearchNamespaceTest { + + private lateinit var context: Context + private val api = MockWebServer() + private val app = MockWebServer() + private val apiPaths = LinkedBlockingQueue() + private val appPaths = LinkedBlockingQueue() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val threads = TrackingThreads() + + @Volatile + private var initAnswer = """{"did":"D1","seance":"S1","search":{"enabled":true,"type":"instant","blank_mode":"agent"}}""" + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + api.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.requestUrl?.encodedPath?.removePrefix("/") ?: return MockResponse().setResponseCode(400) + apiPaths += path + return if (path == "init") MockResponse().setBody(initAnswer) else MockResponse().setBody("{}") + } + } + app.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + appPaths += request.requestUrl?.encodedPath?.removePrefix("/").orEmpty() + return MockResponse().setBody("""{"sessions":[{"id":12,"title":"Flash drive"}],"session":null}""") + } + } + api.start() + app.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + api.shutdown() + app.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + private fun config() = Rees46Config( + shopId = SHOP, + apiDomain = api.url("/").toString().trimEnd('/'), + appDomain = app.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + + private fun awaitState(sdk: SDK, state: SdkState) = runBlocking { + withTimeout(5_000) { sdk.instanceState.changes.first { it == state } } + } + + private fun outcome(block: suspend () -> T): SdkResult = try { + SdkResult.Success(runBlocking { withTimeout(10_000) { block() } }) + } catch (e: SdkException) { + SdkResult.Failure(e.error) + } + + @Test + fun `a bridge's instance knows the agent is on from init, and asks it on the shop's appDomain`() { + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + + assertTrue(sdk.search.agentEnabled) + assertEquals( + SdkResult.Success(AgentDialogResponse(sessions = listOf(AgentSession(id = 12, title = "Flash drive")))), + outcome { sdk.search.agentDialog() }, + ) + assertEquals(SearchApiImpl.AGENT_PATH, appPaths.poll()) + assertTrue(apiPaths.none { it == SearchApiImpl.AGENT_PATH }) + } + + @Test + fun `a blank mode other than agent, or none, is false`() { + initAnswer = """{"did":"D1","seance":"S1","search":{"blank_mode":"history"}}""" + val sdk = Rees46.initializeBridge(context, config()) + awaitState(sdk, SdkState.READY) + + assertFalse(sdk.search.agentEnabled) + } + + @Test + fun `an app's instance on the legacy core gets notInitialized from the agent, whatever its arguments, and agentEnabled is false`() { + val sdk = SDK() + sdk.initializeWith(context, config(), coreV2 = false) + awaitState(sdk, SdkState.READY) + + assertEquals(SdkResult.Failure(SdkError.NotInitialized), outcome { sdk.search.agentDialog(12) }) + assertEquals(SdkResult.Failure(SdkError.NotInitialized), outcome { sdk.search.agent("") }) + assertFalse(sdk.search.agentEnabled) + threads.awaitIdle() + assertTrue(appPaths.isEmpty()) + listOf(SearchApiImpl.AGENT_DIALOG, SearchApiImpl.AGENT).forEach { call -> + assertTrue(call, logged.any { it.code == LogCodes.CORE_FLAG_MISMATCH && it.context["call"] == call }) + } + } + + private companion object { + const val SHOP = "agent-namespace-shop" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/search/SearchApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/search/SearchApiFixturesTest.kt new file mode 100644 index 00000000..4d00cb5c --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/search/SearchApiFixturesTest.kt @@ -0,0 +1,181 @@ +package com.personalization.features.search + +import com.personalization.api.models.products.SortBy +import com.personalization.api.models.products.SortDirection +import com.personalization.api.models.search.SearchBlankResponse +import com.personalization.api.models.search.SearchFullRequest +import androidx.test.core.app.ApplicationProvider +import com.personalization.core.SdkError +import com.personalization.core.SdkResult +import com.personalization.core.internal.CoreDispatchers +import com.personalization.core.internal.CoreHttpClient +import com.personalization.core.internal.CoreTimeouts +import com.personalization.core.internal.CoreV2 +import com.personalization.core.internal.FakeConnectivity +import com.personalization.core.internal.NamespaceCalls +import com.personalization.core.internal.startedCoreInit +import com.personalization.sdk.domain.repositories.UserSettingsRepository +import io.mockk.every +import io.mockk.mockk +import okhttp3.mockwebserver.MockWebServer +import java.util.concurrent.TimeUnit +import com.personalization.core.BridgeApi +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.argBoolean +import com.personalization.core.internal.argDouble +import com.personalization.core.internal.argInt +import com.personalization.core.internal.argLong +import com.personalization.core.internal.argString +import com.personalization.core.internal.argStringLists +import com.personalization.core.internal.argStrings +import okhttp3.mockwebserver.MockResponse +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** `sdk.search` against the contract's fixtures (`contract/0/search.json`), the search agent among them. */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class SearchApiFixturesTest { + + private val fixtures = NamespaceFixtures("search-shop") + private lateinit var search: SearchApiImpl + + @Before + fun setUp() { + fixtures.start() + search = SearchApiImpl(fixtures.calls) + } + + @After + fun tearDown() = fixtures.stop() + + private val invoke = NamespaceFixtures.Invoke { method, args -> + when (method) { + "blank" -> search.blank() + "instant" -> search.instant( + args.getString("query"), + locations = args.argStrings("locations"), + excludedMerchants = args.argStrings("excludedMerchants"), + excludedBrands = args.argStrings("excludedBrands"), + ) + "full" -> search.full(args.getString("query"), args.optJSONObject("request")?.let(::fullRequest) ?: SearchFullRequest()) + "agentDialog" -> search.agentDialog(args.argLong("sessionId"), args.argStrings("locations")) + "agent" -> search.agent(args.getString("message"), args.argLong("sessionId"), args.argStrings("locations")) + else -> error("no search.$method") + } + } + + @Test + fun `every method makes the contract's request, or fails with invalidArgument and sends nothing`() { + fixtures.checkRequests("search", invoke) { MockResponse().setBody("{}") } + fixtures.checkErrors("search", invoke) + } + + @Test + fun `every method reads each answer of the contract into its result or its error`() { + fixtures.checkAnswers("search", invoke) + } + + @Test + fun `an empty search's answer without a body is an empty result`() { + fixtures.server.enqueue(MockResponse().setResponseCode(200)) + + assertEquals(SdkResult.Success(SearchBlankResponse()), fixtures.outcome { search.blank() }) + } + + @Test + fun `the agent's methods go to the host of API v3, and the other searches to the API's`() { + val app = MockWebServer().apply { start() } + val api = MockWebServer().apply { start() } + val settings = mockk(relaxed = true) { + every { getShopId() } returns "agent-shop" + every { getDid() } returns "did-1" + every { getSid() } returns "sid-1" + } + val connectivity = FakeConnectivity(connected = true) + val client = CoreHttpClient({ api.url("/").toString() }, settings, connectivity, "agent-shop", appUrl = { app.url("/").toString() }) + val core = CoreV2(client, "agent-shop").also { + it.init = startedCoreInit(ApplicationProvider.getApplicationContext(), settings, connectivity, "agent-shop") + } + val search = SearchApiImpl(NamespaceCalls(core = { core }, dispatchers = { CoreDispatchers.DEFAULT }, shopId = { "agent-shop" })) + try { + app.enqueue(MockResponse().setBody("""{"sessions":[]}""")) + app.enqueue(MockResponse().setBody("""{"session":{"id":1},"message":{"id":2}}""")) + api.enqueue(MockResponse().setBody("{}")) + + assertTrue(fixtures.outcome { search.agentDialog() } is SdkResult.Success) + assertTrue(fixtures.outcome { search.agent("hi") } is SdkResult.Success) + assertTrue(fixtures.outcome { search.blank() } is SdkResult.Success) + + assertEquals(listOf("GET", "POST").map { it to "/" + SearchApiImpl.AGENT_PATH }, List(2) { + app.takeRequest(5, TimeUnit.SECONDS)!!.let { it.method to it.requestUrl!!.encodedPath } + }) + assertEquals("/" + SearchApiImpl.BLANK_PATH, api.takeRequest(5, TimeUnit.SECONDS)!!.requestUrl!!.encodedPath) + assertEquals(2, app.requestCount) + assertEquals(1, api.requestCount) + } finally { + core.release() + app.close() + api.close() + } + } + + @Test + fun `the agent's answer is read for 60 seconds, longer than the client's read timeout, which the dialog keeps`() { + val slow = NamespaceFixtures("agent-timeout-shop", CoreTimeouts(readMs = 300)) + slow.start() + try { + val search = SearchApiImpl(slow.calls) + val late = { body: String -> MockResponse().setBody(body).setHeadersDelay(1, TimeUnit.SECONDS) } + slow.server.enqueue(late("""{"sessions":[]}""")) + slow.server.enqueue(late("""{"session":{"id":1},"message":{"id":2,"role":"assistant"}}""")) + + assertEquals(SdkResult.Failure(SdkError.Timeout), slow.outcome { search.agentDialog() }) + assertTrue(slow.outcome { search.agent("hi") } is SdkResult.Success) + } finally { + slow.stop() + } + } + + @Test + fun `agentEnabled is what the last init answer said, false without one`() { + var enabled = false + val search = SearchApiImpl(fixtures.calls) { enabled } + + assertFalse(search.agentEnabled) + enabled = true + assertTrue(search.agentEnabled) + assertFalse(SearchApiImpl(fixtures.calls).agentEnabled) + } + + private fun fullRequest(json: JSONObject) = SearchFullRequest( + categoryIds = json.argStrings("categoryIds"), + brands = json.argStrings("brands"), + excludedBrands = json.argStrings("excludedBrands"), + merchants = json.argStrings("merchants"), + excludedMerchants = json.argStrings("excludedMerchants"), + locations = json.argStrings("locations"), + priceMin = json.argDouble("priceMin"), + priceMax = json.argDouble("priceMax"), + colors = json.argStrings("colors"), + fashionSizes = json.argStrings("fashionSizes"), + excludedItemIds = json.argStrings("excludedItemIds"), + filters = json.argStringLists("filters"), + sortBy = json.argString("sortBy")?.let(::SortBy), + sortDir = json.argString("sortDir")?.let { dir -> SortDirection.entries.first { it.value == dir } }, + disableClarification = json.argBoolean("disableClarification") ?: false, + categoryLimit = json.argInt("categoryLimit"), + brandLimit = json.argInt("brandLimit"), + limit = json.argInt("limit"), + page = json.argInt("page"), + ) +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/segments/SegmentsApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/segments/SegmentsApiFixturesTest.kt new file mode 100644 index 00000000..83cfbfa7 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/segments/SegmentsApiFixturesTest.kt @@ -0,0 +1,84 @@ +package com.personalization.features.segments + +import com.personalization.core.BridgeApi +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.argString +import okhttp3.mockwebserver.MockResponse +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.CopyOnWriteArrayList + +/** `sdk.segments` against the contract's fixtures (`contract/0/segments.json`), and its A/B group. */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class SegmentsApiFixturesTest { + + private val fixtures = NamespaceFixtures("segments-shop") + private val changes = CopyOnWriteArrayList>() + private var abGroup: String? = "B" + private lateinit var segments: SegmentsApiImpl + + @Before + fun setUp() { + fixtures.start() + segments = SegmentsApiImpl(fixtures.calls, abGroup = { abGroup }) { type, signature -> changes += type to signature } + } + + @After + fun tearDown() = fixtures.stop() + + private val invoke = NamespaceFixtures.Invoke { method, args -> + when (method) { + "add" -> segments.add(args.getInt("segmentId"), args.argString("email"), args.argString("phone")) + "remove" -> segments.remove(args.getInt("segmentId"), args.argString("email"), args.argString("phone")) + "get" -> segments.get() + else -> error("no segments.$method") + } + } + + @Test + fun `every method makes the contract's request, or fails with invalidArgument and sends nothing`() { + fixtures.checkRequests("segments", invoke) { MockResponse().setBody("[]") } + fixtures.checkErrors("segments", invoke) + } + + @Test + fun `every method reads each answer of the contract into its result or its error`() { + fixtures.checkAnswers("segments", invoke) + } + + @Test + fun `the A-B group is the one the SDK keeps, and empty on an instance never initialized`() { + assertEquals("B", segments.getAbGroup()) + + abGroup = null + + assertEquals("", segments.getAbGroup()) + assertEquals(0, fixtures.server.requestCount) + } + + @Test + fun `add and remove tell popups v3 of the change once the server took it`() { + fixtures.server.enqueue(MockResponse().setBody("{}")) + fixtures.server.enqueue(MockResponse().setBody("{}")) + fixtures.server.enqueue(MockResponse().setResponseCode(500)) + + fixtures.outcome { segments.add(12) } + fixtures.outcome { segments.remove(12, email = "jane@example.com") } + fixtures.outcome { segments.add(13) } + + assertEquals( + listOf( + SegmentsApiImpl.SEGMENTS to """add {"segment_id":12}""", + SegmentsApiImpl.SEGMENTS to """remove {"segment_id":12,"email":"jane@example.com"}""", + ), + changes, + ) + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/sliders/SlidersApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/sliders/SlidersApiFixturesTest.kt new file mode 100644 index 00000000..7a50ae26 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/sliders/SlidersApiFixturesTest.kt @@ -0,0 +1,106 @@ +package com.personalization.features.sliders + +import androidx.test.core.app.ApplicationProvider +import com.personalization.api.models.sliders.Slider +import com.personalization.api.models.sliders.SliderBanner +import com.personalization.core.BridgeApi +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.argStrings +import com.personalization.core.internal.argString +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.MockResponse +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.TimeUnit + +/** + * `sliders.get` against the contract's fixtures (`contract/0/sliders.json`). The banner events of the same + * file are `tracking`'s: [com.personalization.features.tracking.impl.BannerEventsTest]. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class SlidersApiFixturesTest { + + private val fixtures = NamespaceFixtures(SHOP) + private lateinit var sliders: SlidersApiImpl + + private val invoke = NamespaceFixtures.Invoke { method, args -> + check(method == "get") { "unknown method $method" } + sliders.get(args.getString("code"), args.argStrings("tags"), args.argString("locationId")) + } + + @Before + fun setUp() { + fixtures.start(ApplicationProvider.getApplicationContext()) + sliders = SlidersApiImpl(fixtures.calls) + } + + @After + fun tearDown() = fixtures.stop() + + @Test + fun `get makes the contract's request, tags joined by commas`() { + assertEquals(2, fixtures.checkRequests(FILE, invoke, NAMESPACE)) + } + + @Test + fun `an empty code, an empty tag or one with a comma is invalidArgument without a request`() { + assertEquals(3, fixtures.checkErrors(FILE, invoke, NAMESPACE)) + } + + @Test + fun `get reads every answer of the contract into its slider or its error`() { + val json = NamespaceFixtures.Json { value -> + (value as Slider).let { slider -> + mapOf( + "code" to slider.code, "width" to slider.width, "height" to slider.height, + "banners" to slider.banners.map { banner -> + mapOf( + "id" to banner.id, "code" to banner.code, "imageUrl" to banner.imageUrl, "url" to banner.url, + "deeplinkIos" to banner.deeplinkIos, "deeplinkAndroid" to banner.deeplinkAndroid, "html" to banner.html, + ) + }, + ) + } + } + + assertTrue(fixtures.checkAnswers(FILE, invoke, NAMESPACE, json) >= 8) + } + + @Test + fun `an empty list of tags is not sent`() { + fixtures.server.enqueue(MockResponse().setBody("{}")) + + runCatching { runBlocking { withTimeout(10_000) { sliders.get("homepage_mobile", tags = emptyList()) } } } + + val url = fixtures.server.takeRequest(5, TimeUnit.SECONDS)!!.requestUrl!! + assertEquals(setOf("code"), url.queryParameterNames - NamespaceFixtures.COMMON_FIELDS) + } + + @Test + fun `a slider without its own code and size takes the code it was asked for and 0, a banner without an id is left out`() { + val body = JSONObject("""{"status":"success","payload":{"slides":[{"image_url":"a.jpg"},{"banner_id":5,"url":""}]}}""") + + val slider = SlidersApiImpl.readSlider(body, asked = "asked_code") + + assertEquals( + Slider("asked_code", 0, 0, listOf(SliderBanner("5", "asked_code", null, null, null, null, null))), + slider, + ) + } + + private companion object { + const val SHOP = "sliders-shop" + const val FILE = "sliders" + const val NAMESPACE = "sliders" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/stories/StoriesApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/stories/StoriesApiFixturesTest.kt new file mode 100644 index 00000000..56e33726 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/stories/StoriesApiFixturesTest.kt @@ -0,0 +1,164 @@ +package com.personalization.features.stories + +import androidx.test.core.app.ApplicationProvider +import com.personalization.api.models.stories.StoriesBlock +import com.personalization.api.models.stories.StoryButtonElement +import com.personalization.api.models.stories.StoryElement +import com.personalization.api.models.stories.StoryProduct +import com.personalization.api.models.stories.StoryProductElement +import com.personalization.api.models.stories.StoryProductsElement +import com.personalization.api.models.stories.StorySlideType +import com.personalization.api.models.stories.StoryTextBlockElement +import com.personalization.core.BridgeApi +import com.personalization.core.SdkError +import com.personalization.core.SdkException +import com.personalization.core.internal.NamespaceFixtures +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.MockResponse +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.TimeUnit + +/** `stories.get` against the contract's fixtures (`contract/0/stories.json`): the request, the refused arguments, how each answer reads. */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class StoriesApiFixturesTest { + + private val fixtures = NamespaceFixtures(SHOP) + private lateinit var stories: StoriesApiImpl + + private val invoke = NamespaceFixtures.Invoke { method, args -> + check(method == "get") { "unknown method $method" } + stories.get(args.getString("code")) + } + + @Before + fun setUp() { + fixtures.start(ApplicationProvider.getApplicationContext()) + stories = StoriesApiImpl(fixtures.calls) + } + + @After + fun tearDown() = fixtures.stop() + + @Test + fun `get makes the contract's request`() { + assertEquals(1, fixtures.checkRequests(FILE, invoke, NAMESPACE)) + } + + @Test + fun `an empty code is invalidArgument without a request`() { + assertEquals(1, fixtures.checkErrors(FILE, invoke, NAMESPACE)) + } + + @Test + fun `the code is encoded as one segment of the path`() { + fixtures.server.enqueue(MockResponse().setBody("{}")) + + runBlocking { withTimeout(10_000) { stories.get("main stories/1?") } } + + assertEquals("/stories/main%20stories%2F1%3F", fixtures.server.takeRequest(5, TimeUnit.SECONDS)?.requestUrl?.encodedPath) + } + + @Test + fun `a code of spaces is invalidArgument without a request`() { + val error = try { + runBlocking { stories.get(" ") } + null + } catch (e: SdkException) { + e.error + } + + assertTrue("$error", error is SdkError.InvalidArgument) + assertNull(fixtures.server.takeRequest(100, TimeUnit.MILLISECONDS)) + } + + @Test + fun `get reads every answer of the contract into its block or its error`() { + assertTrue(fixtures.checkAnswers(FILE, invoke, NAMESPACE, NamespaceFixtures.Json { block(it as StoriesBlock) }) >= 9) + } + + @Test + fun `an opacity is percent as a string or above 1, a fraction otherwise, and never outside 0 to 1`() { + val cases = listOf>( + "40%" to 0.4, "40" to 0.4, " 75 % " to 0.75, 0.5 to 0.5, 50 to 0.5, 1 to 1.0, "150%" to 1.0, + "-5" to 0.0, 0 to 0.0, "half" to 0.0, null to 0.0, true to 0.0, + ) + + cases.forEach { (value, expected) -> assertEquals("$value", expected, StoriesApiImpl.opacity(value), 1e-9) } + } + + @Test + fun `an answer without a body is decoding`() { + assertEquals(null, StoriesApiImpl.readBlock(null)) + } + + /** The block in the contract's names; an element carries its kind as `type`, as in TypeScript. */ + private fun block(block: StoriesBlock): Map = mapOf( + "id" to block.id, + "stories" to block.stories.map { story -> + mapOf( + "id" to story.id, "name" to story.name, "avatar" to story.avatar, "viewed" to story.viewed, + "pinned" to story.pinned, "startPosition" to story.startPosition, + "slides" to story.slides.map { slide -> + mapOf( + "id" to slide.id, "type" to slide.type.wire(), "background" to slide.background, + "backgroundColor" to slide.backgroundColor, "preview" to slide.preview, "duration" to slide.duration, + "elements" to slide.elements.map(::element), + ) + }, + ) + }, + ) + + private fun StorySlideType.wire(): String = when (this) { + StorySlideType.IMAGE -> "image" + StorySlideType.VIDEO -> "video" + StorySlideType.PRODUCT -> "product" + } + + private fun element(element: StoryElement): Map = when (element) { + is StoryButtonElement -> mapOf( + "type" to "button", "title" to element.title, "link" to element.link, "linkAndroid" to element.linkAndroid, + "linkIos" to element.linkIos, "background" to element.background, "color" to element.color, + "textBold" to element.textBold, + ) + is StoryProductElement -> mapOf("type" to "product", "title" to element.title, "item" to element.item?.let(::product)) + is StoryProductsElement -> mapOf( + "type" to "products", "showLabel" to element.showLabel, "hideLabel" to element.hideLabel, + "products" to element.products.map(::product), + ) + is StoryTextBlockElement -> mapOf( + "type" to "textBlock", "text" to element.text, "fontSize" to element.fontSize, "fontType" to element.fontType, + "bold" to element.bold, "italic" to element.italic, "textAlign" to element.textAlign, + "textColor" to element.textColor, "backgroundColor" to element.backgroundColor, + "backgroundOpacity" to element.backgroundOpacity, "lineSpacing" to element.lineSpacing, + "yOffset" to element.yOffset, "promocode" to element.promocode, + ) + } + + private fun product(product: StoryProduct): Map = mapOf( + "id" to product.id, "name" to product.name, "brand" to product.brand, "picture" to product.picture, + "imageUrl" to product.imageUrl, "price" to product.price, "priceFormatted" to product.priceFormatted, + "oldPrice" to product.oldPrice, "oldPriceFormatted" to product.oldPriceFormatted, + "discountPercent" to product.discountPercent, "promocode" to product.promocode, + "priceWithPromocode" to product.priceWithPromocode, "priceWithPromocodeFormatted" to product.priceWithPromocodeFormatted, + "currency" to product.currency, "url" to product.url, "deeplinkAndroid" to product.deeplinkAndroid, + "deeplinkIos" to product.deeplinkIos, + ) + + private companion object { + const val SHOP = "stories-shop" + const val FILE = "stories" + const val NAMESPACE = "stories" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/subscriptions/SubscriptionsApiFixturesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/subscriptions/SubscriptionsApiFixturesTest.kt new file mode 100644 index 00000000..33352480 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/subscriptions/SubscriptionsApiFixturesTest.kt @@ -0,0 +1,107 @@ +package com.personalization.features.subscriptions + +import com.personalization.api.models.subscriptions.BackInStockProperties +import com.personalization.api.models.subscriptions.SubscriptionsUpdateRequest +import com.personalization.core.BridgeApi +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.argBoolean +import com.personalization.core.internal.argString +import com.personalization.core.internal.argStrings +import okhttp3.mockwebserver.MockResponse +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.CopyOnWriteArrayList + +/** `sdk.subscriptions` against the contract's fixtures (`contract/0/subscriptions.json`). */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class SubscriptionsApiFixturesTest { + + private val fixtures = NamespaceFixtures("subscriptions-shop") + private val changes = CopyOnWriteArrayList() + private lateinit var subscriptions: SubscriptionsApiImpl + + @Before + fun setUp() { + fixtures.start() + subscriptions = SubscriptionsApiImpl(fixtures.calls) { type, _ -> changes += type } + } + + @After + fun tearDown() = fixtures.stop() + + private val invoke = NamespaceFixtures.Invoke { method, args -> + val email = args.argString("email") + val phone = args.argString("phone") + when (method) { + "manage" -> subscriptions.manage(manageRequest(args.getJSONObject("request"))) + "check" -> subscriptions.check() + "subscribeForPriceDrop" -> subscriptions.subscribeForPriceDrop(args.getString("itemId"), args.getDouble("currentPrice"), email, phone) + "unsubscribeFromPriceDrop" -> subscriptions.unsubscribeFromPriceDrop(args.argStrings("itemIds")!!, email, phone) + "subscribeForBackInStock" -> subscriptions.subscribeForBackInStock( + args.getString("itemId"), + args.optJSONObject("properties")?.let { + BackInStockProperties(it.argString("fashionSize"), it.argString("fashionColor"), it.argString("barcode")) + }, + email, + phone, + ) + "unsubscribeFromBackInStock" -> subscriptions.unsubscribeFromBackInStock(args.argStrings("itemIds")!!, email, phone) + else -> error("no subscriptions.$method") + } + } + + @Test + fun `every method makes the contract's request, or fails with invalidArgument and sends nothing`() { + fixtures.checkRequests("subscriptions", invoke) + fixtures.checkErrors("subscriptions", invoke) + } + + @Test + fun `every method reads each answer of the contract into its result or its error`() { + fixtures.checkAnswers("subscriptions", invoke) + } + + @Test + fun `only manage tells popups v3 of the change, once the server took it`() { + repeat(3) { fixtures.server.enqueue(MockResponse().setBody("{}")) } + fixtures.server.enqueue(MockResponse().setResponseCode(500)) + + fixtures.outcome { subscriptions.manage(SubscriptionsUpdateRequest(emailBulk = true)) } + fixtures.outcome { subscriptions.subscribeForPriceDrop("37", 10.0) } + fixtures.outcome { subscriptions.unsubscribeFromBackInStock(listOf("37")) } + fixtures.outcome { subscriptions.manage(SubscriptionsUpdateRequest(emailBulk = false)) } + + assertEquals(listOf(SubscriptionsApiImpl.MANAGE_PATH), changes) + } + + /** The request from the fixture's names, each of them a field of [SubscriptionsUpdateRequest] by the same name. */ + private fun manageRequest(json: JSONObject): SubscriptionsUpdateRequest { + val flags = FLAGS.associateWith { json.argBoolean(it) } + return SubscriptionsUpdateRequest( + email = json.argString("email"), phone = json.argString("phone"), externalId = json.argString("externalId"), + loyaltyId = json.argString("loyaltyId"), telegramId = json.argString("telegramId"), + emailBulk = flags["emailBulk"], emailChain = flags["emailChain"], emailTransactional = flags["emailTransactional"], + smsBulk = flags["smsBulk"], smsChain = flags["smsChain"], smsTransactional = flags["smsTransactional"], + webPushBulk = flags["webPushBulk"], webPushChain = flags["webPushChain"], webPushTransactional = flags["webPushTransactional"], + mobilePushBulk = flags["mobilePushBulk"], mobilePushChain = flags["mobilePushChain"], + mobilePushTransactional = flags["mobilePushTransactional"], + telegramBulk = flags["telegramBulk"], telegramChain = flags["telegramChain"], telegramTransactional = flags["telegramTransactional"], + whatsappBulk = flags["whatsappBulk"], whatsappChain = flags["whatsappChain"], whatsappTransactional = flags["whatsappTransactional"], + maxBulk = flags["maxBulk"], maxChain = flags["maxChain"], maxTransactional = flags["maxTransactional"], + walletBulk = flags["walletBulk"], walletChain = flags["walletChain"], walletTransactional = flags["walletTransactional"], + ) + } + + private companion object { + val FLAGS = listOf("email", "sms", "webPush", "mobilePush", "telegram", "whatsapp", "max", "wallet") + .flatMap { channel -> listOf("Bulk", "Chain", "Transactional").map { channel + it } } + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/features/tracking/impl/BannerEventsTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/features/tracking/impl/BannerEventsTest.kt new file mode 100644 index 00000000..baeee4ee --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/features/tracking/impl/BannerEventsTest.kt @@ -0,0 +1,299 @@ +package com.personalization.features.tracking.impl + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import com.personalization.LogLevel +import com.personalization.PreferencesPartition +import com.personalization.Rees46 +import com.personalization.Rees46Config +import com.personalization.SDK +import com.personalization.SdkLogHandler +import com.personalization.SdkLogMessage +import com.personalization.SdkRegistry +import com.personalization.api.managers.TrackingApi +import com.personalization.core.BridgeApi +import com.personalization.core.CompletionListener +import com.personalization.core.SdkError +import com.personalization.core.SdkResult +import com.personalization.core.SdkState +import com.personalization.core.internal.ContractFixtures +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.NamespaceFixtures +import com.personalization.core.internal.QueueStore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.logs.LogCodes +import com.personalization.logs.SdkLogs +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +/** + * `tracking.bannerView` and `bannerClick` as a bridge calls them: the cases of the contract's fixtures + * (`contract/0/sliders.json`) go to `track/slider` through the new core's queue, and the listener hears, + * on the main thread, that the queue took the event. On the legacy core, where apps run, they fail with + * `notInitialized` and send nothing. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class BannerEventsTest { + + private lateinit var context: Context + private val server = MockWebServer() + private val requests = LinkedBlockingQueue>() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val threads = TrackingThreads() + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { + context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() + } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + LegacyCore.threads = threads + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val url = request.requestUrl ?: return MockResponse().setResponseCode(400) + val path = url.encodedPath.removePrefix("/") + val body = if (request.method == "POST") JSONObject(request.body.readUtf8()) else JSONObject() + requests += path to body + return when (path) { + "init" -> MockResponse().setBody("""{"did":"D1","seance":"S1"}""") + SLIDER -> MockResponse().setResponseCode(204) + else -> MockResponse().setBody("{}") + } + } + } + server.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + server.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + QueueStore.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + private fun sdk(coreV2: Boolean): SDK { + val config = Rees46Config( + shopId = SHOP, + apiDomain = server.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + val sdk = Rees46.initialize(context, config, coreV2) + runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } + return sdk + } + + /** What a listener heard: the result, and whether on the main thread. */ + private class Heard : CompletionListener { + val ends = CopyOnWriteArrayList, Boolean>>() + override fun onComplete(result: SdkResult) { + ends += result to (Looper.myLooper() == Looper.getMainLooper()) + } + } + + /** Runs the main looper until [heard] heard once, and a little after to catch a second time. */ + private fun await(heard: Heard): List, Boolean>> { + val until = System.currentTimeMillis() + 5_000 + while (heard.ends.isEmpty() && System.currentTimeMillis() < until) { + shadowOf(Looper.getMainLooper()).idle() + Thread.sleep(10) + } + repeat(5) { + Thread.sleep(10) + shadowOf(Looper.getMainLooper()).idle() + } + return heard.ends.toList() + } + + private fun call(tracking: TrackingApi, method: String, args: JSONObject, listener: CompletionListener?) = when (method) { + "bannerView" -> tracking.bannerView(args.getString("bannerId"), args.getString("code"), listener) + "bannerClick" -> tracking.bannerClick(args.getString("bannerId"), args.getString("code"), listener) + else -> error("unknown method $method") + } + + /** The banner cases of the fixtures that pair with [kind]. */ + private fun cases(kind: String) = ContractFixtures.cases("sliders").filter { + it.has(kind) && it.getJSONObject("call").getString("namespace") == "tracking" + } + + /** The bodies of `track/slider` the server got once the queue was sent. */ + private fun sentEvents(sdk: SDK): List { + runBlocking { withTimeout(5_000) { sdk.flush() } } + threads.awaitIdle() + Thread.sleep(100) + return generateSequence { requests.poll() }.filter { it.first == SLIDER }.map { it.second }.toList() + } + + @Test + fun `the banner events of the fixtures go to track slider through the queue, accepted on the main thread`() { + val sdk = sdk(coreV2 = true) + val cases = cases("request") + assertEquals(2, cases.size) + + cases.forEach { case -> + val name = case.getString("name") + val call = case.getJSONObject("call") + val heard = Heard() + + call(sdk.tracking, call.getString("method"), call.getJSONObject("args"), heard) + + assertEquals(name, listOf(SdkResult.Success(Unit) to true), await(heard)) + val expected = case.getJSONObject("request") + assertEquals(name, "POST", expected.getString("method")) + assertEquals(name, SLIDER, expected.getString("path")) + val body = sentEvents(sdk).single() + val own = body.keys().asSequence().filter { it !in NamespaceFixtures.COMMON_FIELDS }.associateWith { NamespaceFixtures.normalize(body.get(it)) } + assertEquals(name, NamespaceFixtures.normalize(expected.getJSONObject("body")), own) + assertTrue(name, body.get("banner_id") is Number) + assertFalse(name, body.has("recommended_by")) + assertEquals(name, "D1", body.getString("did")) + assertEquals(name, "S1", body.getString("sid")) + assertEquals(name, SHOP, body.getString("shop_id")) + } + } + + @Test + fun `a wrong banner id or an empty code is invalidArgument and sends nothing`() { + val sdk = sdk(coreV2 = true) + val cases = cases("error") + assertEquals(3, cases.size) + + cases.forEach { case -> + val name = case.getString("name") + val call = case.getJSONObject("call") + val heard = Heard() + + call(sdk.tracking, call.getString("method"), call.getJSONObject("args"), heard) + + val ends = await(heard) + assertEquals(name, 1, ends.size) + assertTrue("$name: ${ends.single()}", (ends.single().first as? SdkResult.Failure)?.error is SdkError.InvalidArgument) + assertTrue(name, ends.single().second) + } + assertEquals(emptyList(), sentEvents(sdk)) + assertEquals(3, logged.count { it.code == LogCodes.INVALID_ARGUMENT && it.context["call"].toString().startsWith("tracking.banner") }) + } + + @Test + fun `banner ids outside an unsigned 32-bit number are refused`() { + val sdk = sdk(coreV2 = true) + listOf("0", "-1", "4294967296", "1.5", " 101", "١٠١").forEach { id -> + val heard = Heard() + + sdk.tracking.bannerView(id, "homepage_mobile", heard) + + assertTrue(id, (await(heard).single().first as? SdkResult.Failure)?.error is SdkError.InvalidArgument) + } + val heard = Heard() + sdk.tracking.bannerView("4294967295", "homepage_mobile", heard) + assertEquals(listOf(SdkResult.Success(Unit) to true), await(heard)) + assertEquals(4294967295L, sentEvents(sdk).single().getLong("banner_id")) + } + + @Test + fun `events without a listener go in the order of the calls`() { + val sdk = sdk(coreV2 = true) + + sdk.tracking.bannerView("101", "homepage_mobile") + sdk.tracking.bannerClick("101", "homepage_mobile") + sdk.tracking.bannerView("102", "homepage_mobile") + + val sent = sentEvents(sdk).map { it.getString("event") + ":" + it.getLong("banner_id") } + assertEquals(listOf("view:101", "click:101", "view:102"), sent) + } + + @Test + fun `on the legacy core a banner event is notInitialized, sends nothing and says why in the log`() { + val sdk = sdk(coreV2 = false) + threads.awaitIdle() + requests.clear() + val view = Heard() + val click = Heard() + + sdk.tracking.bannerView("101", "homepage_mobile", view) + sdk.tracking.bannerClick("101", "", click) + + assertEquals(listOf(SdkResult.Failure(SdkError.NotInitialized) to true), await(view)) + assertEquals(listOf(SdkResult.Failure(SdkError.NotInitialized) to true), await(click)) + threads.awaitIdle() + Thread.sleep(100) + assertTrue(requests.none { it.first == SLIDER }) + val mismatches = logged.filter { it.code == LogCodes.CORE_FLAG_MISMATCH && it.context.containsKey("call") }.map { it.context["call"] } + assertEquals(listOf("tracking.bannerView", "tracking.bannerClick"), mismatches) + } + + @Test + fun `after release a banner event is notInitialized`() { + val sdk = sdk(coreV2 = true) + sdk.release() + val heard = Heard() + + sdk.tracking.bannerClick("101", "homepage_mobile", heard) + + assertEquals(listOf(SdkResult.Failure(SdkError.NotInitialized) to true), await(heard)) + } + + @Test + fun `Java does not see the banner events`() { + val methods = TrackingApi::class.java.methods.filter { it.name == "bannerView" || it.name == "bannerClick" } + + assertEquals(2, methods.size) + assertTrue(methods.all { it.isSynthetic }) + } + + private companion object { + const val SHOP = "banner-events-shop" + const val SLIDER = "track/slider" + } +} diff --git a/personalization-sdk/src/test/resources/contract/0/cart.json b/personalization-sdk/src/test/resources/contract/0/cart.json new file mode 100644 index 00000000..cff116f9 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/cart.json @@ -0,0 +1,74 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "request": { "method": "GET", "path": "products/cart", "query": {} } + }, + { + "name": "корзина в форме data.items", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "data": { "items": [ { "uniqid": "37", "quantity": 2 }, { "uniqid": "38", "quantity": 1 } ] } } }, + "expect": { "result": [ { "id": "37", "quantity": 2 }, { "id": "38", "quantity": 1 } ] } + }, + { + "name": "корзина в форме payload.cart_items из документации", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", "payload": { "cart_items": [ { "uniqid": "37", "quantity": 2 } ] } } }, + "expect": { "result": [ { "id": "37", "quantity": 2 } ] } + }, + { + "name": "пустая корзина", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "data": { "items": [] } } }, + "expect": { "result": [] } + }, + { + "name": "числа строкой, позиция без uniqid пропускается, без quantity — 1, незнакомые поля не мешают", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "data": { "items": [ { "uniqid": 37, "quantity": "3", "price": 999.5 }, + { "quantity": 1 }, + { "uniqid": "", "quantity": 1 }, + { "uniqid": "38" }, + { "uniqid": "39", "quantity": null } ], + "total": 4 } } }, + "expect": { "result": [ { "id": "37", "quantity": 3 }, { "id": "38", "quantity": 1 }, { "id": "39", "quantity": 1 } ] } + }, + { + "name": "404 — неизвестный did", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 404, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "403 — отказ услуги или магазина, состояние SDK не меняется", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 403, "body": null }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "ответ ни в одной из двух форм", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "items": [ { "uniqid": "37", "quantity": 1 } ] } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/collections.json b/personalization-sdk/src/test/resources/contract/0/collections.json new file mode 100644 index 00000000..aad1209b --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/collections.json @@ -0,0 +1,62 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "request": { "method": "GET", "path": "collection/12", "query": {} } + }, + { + "name": "get: идентификатор в пути URL-кодирован", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "a b/c" } }, + "request": { "method": "GET", "path": "collection/a%20b%2Fc", "query": {} } + }, + { + "name": "get с пустым collectionId", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "товары коллекции", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": 200, + "body": { "products": [ { "id": "37", "group_id": "_37_", "name": "Кроссовки", "url": "https://shop.example/p/37", + "price": 4990, "currency": "₽", "oldprice": 5990, + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5" } ] }, + { "id": "38", "name": "Без цены", "url": "https://shop.example/p/38", "currency": "₽" } ] } }, + "expect": { "result": { "products": [ { "id": "37", "groupId": "_37_", "name": "Кроссовки", "url": "https://shop.example/p/37", + "price": 4990, "currency": "₽", "oldPrice": 5990, "isNew": false, + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5" } ] } ] } } + }, + { + "name": "пустая коллекция", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": 200, "body": { "products": [] } }, + "expect": { "result": { "products": [] } } + }, + { + "name": "400 — неизвестная или неактивная коллекция", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "999" } }, + "response": { "status": 400, "body": { "status": "error", "message": "Collection with id 999 was not found" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "ответ без products", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": 200, "body": {} }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/loyalty.json b/personalization-sdk/src/test/resources/contract/0/loyalty.json new file mode 100644 index 00000000..e535434d --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/loyalty.json @@ -0,0 +1,183 @@ +{ + "contract": "0", + "cases": [ + { + "name": "join со всеми полями", + "call": { "namespace": "loyalty", "method": "join", + "args": { "phone": "+79991234567", "firstName": "Anna", "lastName": "Ivanova", "gender": "female", "birthday": "1990-05-17" } }, + "request": { "method": "POST", "path": "loyalty/members/join", + "body": { "phone": "+79991234567", "first_name": "Anna", "last_name": "Ivanova", "gender": "f", "birthday": "1990-05-17" } } + }, + { + "name": "join с телефоном и полом: телефон уходит как есть", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "89991234567", "gender": "male" } }, + "request": { "method": "POST", "path": "loyalty/members/join", "body": { "phone": "89991234567", "gender": "m" } } + }, + { + "name": "join с пустым phone", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "join с birthday не YYYY-MM-DD", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567", "birthday": "17.05.1990" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "join: birthday — несуществующая дата; непонятную дату сервер стёр бы", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567", "birthday": "1990-02-30" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "join: пустой birthday", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567", "birthday": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "join — новый участник", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", "payload": { "message": "Member is registered successfully", "identifier": "79991234567" } } }, + "expect": { "result": { "identifier": "79991234567" } } + }, + { + "name": "join — телефон уже зарегистрирован, тот же идентификатор (В45)", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", "payload": { "message": "Member is already registered", "identifier": 79991234567 } } }, + "expect": { "result": { "identifier": "79991234567" } } + }, + { + "name": "join — 403, у магазина выключены методы лояльности с фронта (В17, В18)", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567" } }, + "response": { "status": 403, "body": { "status": "error", "message": "Shop not found by secret key" } }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "join — ответ без identifier", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "message": "Member is registered successfully" } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getStatus", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "request": { "method": "GET", "path": "loyalty/members/status", "query": { "identifier": "+79991234567" } } + }, + { + "name": "getStatus с пустым phone", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getStatus — участник на уровне", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "member": true, "level": { "name": "Gold", "code": "level_gold", "expiration_date": "2028-01-01" } } } }, + "expect": { "result": { "isMember": true, "level": { "code": "level_gold", "name": "Gold", "expirationDate": "2028-01-01" } } } + }, + { + "name": "getStatus — базовый уровень: level пусто", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "member": true, "level": { "name": null, "code": null, "expiration_date": null } } } }, + "expect": { "result": { "isMember": true, "level": null } } + }, + { + "name": "getStatus — не участник", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "member": false, "level": { "name": null, "code": null, "expiration_date": null } } } }, + "expect": { "result": { "isMember": false, "level": null } } + }, + { + "name": "getStatus — 400, неверный идентификатор", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "12" } }, + "response": { "status": 400, "body": { "status": "error", "message": "Incorrect member identifier" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "getStatus — 404, лояльность не настроена", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": 404, "body": { "status": "error", "message": "Loyalty program not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "getPromotions без параметров", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "request": { "method": "GET", "path": "loyalty/promos/for-client", "query": {} } + }, + { + "name": "getPromotions со всеми параметрами: промокоды — массивом Rails", + "call": { "namespace": "loyalty", "method": "getPromotions", + "args": { "locationId": "msk-1", "promoCodes": [ "SPRING", "VIP" ], "chargeBonuses": true, "currentTime": "18:30" } }, + "request": { "method": "GET", "path": "loyalty/promos/for-client", + "query": { "location_id": "msk-1", "promo_codes[]": [ "SPRING", "VIP" ], "charge_bonuses": "true", "current_time": "18:30" } } + }, + { + "name": "getPromotions с currentTime не HH:MM", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": { "currentTime": "25:00" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getPromotions с пустым промокодом", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": { "promoCodes": [ "SPRING", "" ] } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getPromotions — акции из документации; id больше 2^31", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "promotions": [ + { "id": 33, "name": "Half price", "start_date": "2026-01-01", "finish_date": "2026-01-14", "stream": "ios", + "badge_label": "-50%", "badge_color": "#AABB00", "description": "On one product", + "reward_type": "discount", + "reward_rules": { "amount_type": "percentage", "reward_type": "discount", "amount_value": 100, + "include_products": [ { "sku": { "values": "300275", "operator": "in" } } ] } }, + { "id": 3000000012, "name": "1+1=3", "start_date": "2026-01-01", "finish_date": "2026-01-14", "stream": null, + "badge_label": "1+1=3", "badge_color": "#AA0000", "description": null, + "reward_type": "bonuses_earn", "reward_rules": {} }, + { "id": "7", "name": "Spend bonuses", "reward_type": "bonuses_usage" } ] } } }, + "expect": { "result": [ + { "id": 33, "name": "Half price", "description": "On one product", "startDate": "2026-01-01", "finishDate": "2026-01-14", + "stream": "ios", "badgeLabel": "-50%", "badgeColor": "#AABB00", "rewardType": "discount" }, + { "id": 3000000012, "name": "1+1=3", "description": null, "stream": null, "badgeLabel": "1+1=3", "rewardType": "bonusesEarn" }, + { "id": 7, "name": "Spend bonuses", "startDate": null, "finishDate": null, "badgeColor": null, "rewardType": "bonusesUsage" } ] } + }, + { + "name": "getPromotions — незнакомый reward_type даёт пустое поле", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", "payload": { "promotions": [ { "id": 5, "name": "Gift", "reward_type": "gift" } ] } } }, + "expect": { "result": [ { "id": 5, "name": "Gift", "rewardType": null } ] } + }, + { + "name": "getPromotions — нет подходящих акций", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "promotions": [] } } }, + "expect": { "result": [] } + }, + { + "name": "getPromotions — 402, услуга лояльности выключена", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 402, "body": { "status": "error", "message": "Loyalty service is disabled" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/notifications.json b/personalization-sdk/src/test/resources/contract/0/notifications.json new file mode 100644 index 00000000..ac446c30 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/notifications.json @@ -0,0 +1,120 @@ +{ + "contract": "0", + "cases": [ + { + "name": "trackDelivered", + "call": { "namespace": "notifications", "method": "trackDelivered", "args": { "code": "m-delivered", "type": "bulk" } }, + "request": { "method": "POST", "path": "track/delivered", "body": { "code": "m-delivered", "type": "bulk" } } + }, + { + "name": "trackOpened", + "call": { "namespace": "notifications", "method": "trackOpened", "args": { "code": "m-opened", "type": "chain" } }, + "request": { "method": "POST", "path": "track/opened", "body": { "code": "m-opened", "type": "chain" } } + }, + { + "name": "trackClicked", + "call": { "namespace": "notifications", "method": "trackClicked", "args": { "code": "m-clicked", "type": "transactional" } }, + "request": { "method": "POST", "path": "track/clicked", "body": { "code": "m-clicked", "type": "transactional" } } + }, + { + "name": "trackClosed с типом digest", + "call": { "namespace": "notifications", "method": "trackClosed", "args": { "code": "m-closed", "type": "digest" } }, + "request": { "method": "POST", "path": "track/closed", "body": { "code": "m-closed", "type": "digest" } } + }, + { + "name": "trackDelivered с пустым code", + "call": { "namespace": "notifications", "method": "trackDelivered", "args": { "code": "", "type": "bulk" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "trackClicked с пустым type", + "call": { "namespace": "notifications", "method": "trackClicked", "args": { "code": "m-1", "type": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "setPushToken FCM на Android", + "platform": "android", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "fcm-token-1", "provider": "fcm" } }, + "request": { "method": "POST", "path": "mobile_push_tokens", + "body": { "token": "fcm-token-1", "platform": "android", "push_provider": "firebase" } } + }, + { + "name": "setPushToken HMS на Android", + "platform": "android", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "hms-token-1", "provider": "hms" } }, + "request": { "method": "POST", "path": "mobile_push_tokens", + "body": { "token": "hms-token-1", "platform": "android", "push_provider": "huawei" } } + }, + { + "name": "setPushToken APNs на iOS", + "platform": "ios", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "apns-token-1", "provider": "apns" } }, + "request": { "method": "POST", "path": "mobile_push_tokens", "body": { "token": "apns-token-1", "platform": "ios" } } + }, + { + "name": "setPushToken FCM на iOS", + "platform": "ios", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "fcm-token-2", "provider": "fcm" } }, + "request": { "method": "POST", "path": "mobile_push_tokens", "body": { "token": "fcm-token-2", "platform": "ios_firebase" } } + }, + { + "name": "setPushToken APNs на Android", + "platform": "android", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "apns-token-2", "provider": "apns" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "setPushToken HMS на iOS", + "platform": "ios", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "hms-token-2", "provider": "hms" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "setPushToken с пустым токеном", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "", "provider": "fcm" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "setPushToken: 200 success", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-200", "provider": "fcm" } }, + "response": { "status": 200, "body": { "status": "success" } }, + "expect": { "result": null } + }, + { + "name": "setPushToken: 2xx без тела — успех", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-empty", "provider": "fcm" } }, + "response": { "status": 200, "body": null }, + "expect": { "result": null } + }, + { + "name": "setPushToken: 400 — клиент не найден", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-400", "provider": "fcm" } }, + "response": { "status": 400, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "setPushToken: 403 — неизвестный или отключённый магазин, пустое тело", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-403", "provider": "fcm" } }, + "response": { "status": 403, "body": null }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "setPushToken: 404 — нет shop_id, пустое тело", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-404", "provider": "fcm" } }, + "response": { "status": 404, "body": null }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "setPushToken: 2xx со status error", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-2xx-error", "provider": "fcm" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "setPushToken: нет ответа", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-no-answer", "provider": "fcm" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/predict.json b/personalization-sdk/src/test/resources/contract/0/predict.json new file mode 100644 index 00000000..e659116e --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/predict.json @@ -0,0 +1,82 @@ +{ + "contract": "0", + "cases": [ + { + "name": "getProbabilityToPurchase — API v3 на appDomain (В42)", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "request": { "method": "GET", "path": "api/v3/cdp/users/probability-to-purchase", "query": {} } + }, + { + "name": "покупатель найден", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "probability": 0.42, "client_id": 12345 } } }, + "expect": { "result": { "probability": 0.42, "clientId": "12345" } } + }, + { + "name": "покупатель найден, событий нет; client_id больше 2^31", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "probability": 0.0, "client_id": 3000000001 } } }, + "expect": { "result": { "probability": 0, "clientId": "3000000001" } } + }, + { + "name": "покупатель не найден — успех с пустым clientId", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "probability": 0.0, "client_id": null } } }, + "expect": { "result": { "probability": 0, "clientId": null } } + }, + { + "name": "ответ без payload — форма старого пути", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "probability": 0.42, "client_id": 12345 } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет probability", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "client_id": 12345 } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "probability не число", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "probability": "high", "client_id": 12345 } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "400 — нет did", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 400, "body": { "status": "fail", "message": "Invalid request parameters" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "402 — у магазина не подключена услуга cdp или он не оплачен", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 402, "body": { "status": "fail", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "403 — магазин неактивен или ограничен", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 403, "body": { "status": "fail", "message": "Access denied" } }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "404 — неизвестный магазин", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 404, "body": { "status": "fail", "message": "Resource not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/products.json b/personalization-sdk/src/test/resources/contract/0/products.json new file mode 100644 index 00000000..01c492b4 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/products.json @@ -0,0 +1,276 @@ +{ + "contract": "0", + "cases": [ + { + "name": "getInfo", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "request": { "method": "GET", "path": "products/get", "query": { "item_id": "37" } } + }, + { + "name": "getInfo с пустым itemId", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList без запроса — первая страница всего каталога", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "request": { "method": "GET", "path": "products", "query": {} } + }, + { + "name": "getList со всеми полями: списки через запятую без пробелов, числа без лишних нулей, filters JSON-строкой", + "call": { "namespace": "products", "method": "getList", + "args": { "request": { "categoryIds": [ "1", "2" ], "brands": [ "Nike", "Adidas" ], "merchants": [ "m1" ], + "locations": [ "msk", "spb" ], "priceMin": 100, "priceMax": 999.5, + "filters": { "color": [ "red", "blue" ] }, + "sortBy": "price", "sortDir": "asc", "limit": 20, "page": 2 } } }, + "request": { "method": "GET", "path": "products", + "query": { "categories": "1,2", "brands": "Nike,Adidas", "merchants": "m1", "locations": "msk,spb", + "price_min": "100", "price_max": "999.5", "filters": "{\"color\":[\"red\",\"blue\"]}", + "sort_by": "price", "sort_dir": "asc", "limit": "20", "page": "2" } } + }, + { + "name": "getList: пустые списки и словарь не уходят", + "call": { "namespace": "products", "method": "getList", + "args": { "request": { "categoryIds": [], "brands": [], "filters": {} } } }, + "request": { "method": "GET", "path": "products", "query": {} } + }, + { + "name": "getList: ключ сортировки не из списка констант уходит как есть", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "sortBy": "popular" } } }, + "request": { "method": "GET", "path": "products", "query": { "sort_by": "popular" } } + }, + { + "name": "getList с limit 0", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "limit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList с page 0", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "page": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList с отрицательной ценой", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "priceMin": -1 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList с priceMin больше priceMax", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "priceMin": 500, "priceMax": 100 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList с сортировкой relevance — только для search.full", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "sortBy": "relevance" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getCounters", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "37" } }, + "request": { "method": "GET", "path": "products/counters", "query": { "item": "37" } } + }, + { + "name": "getCounters с пустым itemId", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getCategory — делегат getList с categories", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "12" } }, + "request": { "method": "GET", "path": "products", "query": { "categories": "12" } } + }, + { + "name": "getCategory с запросом", + "call": { "namespace": "products", "method": "getCategory", + "args": { "categoryId": "12", + "request": { "brands": [ "Nike" ], "locations": [ "msk" ], "filters": { "size": [ "42" ] }, + "priceMin": 0, "priceMax": 5000, "sortBy": "sales_rate", "sortDir": "desc", + "limit": 30, "page": 1 } } }, + "request": { "method": "GET", "path": "products", + "query": { "categories": "12", "brands": "Nike", "locations": "msk", "filters": "{\"size\":[\"42\"]}", + "price_min": "0", "price_max": "5000", "sort_by": "sales_rate", "sort_dir": "desc", + "limit": "30", "page": "1" } } + }, + { + "name": "getCategory с пустым categoryId", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getCategory с сортировкой relevance", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "12", "request": { "sortBy": "relevance" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getInfo: карточка товара — id из uniqid, цены строками, discount логическое, level строкой и числом, пустое описание — null, params словарём в порядке ответа", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "9922" } }, + "response": { "status": 200, + "body": { "name": "Скамья Жасмин", "is_available": true, "description": "", + "price": "10760", "price_full": 10760, "price_formatted": "10 760 ₽", "price_full_formatted": "10 760.00 ₽", + "currency": "₽", "url": "https://shop.example/p/9922", "url_handle": "/p/9922", + "picture": "https://shop.example/i/9922-180.webp", "image_url": "https://shop.example/i/9922.webp", + "image_url_handle": "/i/9922.webp", "image_url_resized": {}, "category_ids": [], "brand": "БРВ Мебель", + "sales_rate": null, "relative_sales_rate": null, + "categories": [ { "id": "23", "name": "Прихожие", "url": "https://shop.example/c/23", "branch": 1, "level": 1 }, + { "parent_id": "23", "id": "12023", "name": "Скамьи", "url": "https://shop.example/c/12023", "level": "2" } ], + "params": { "Цвет": { "value": [ "графит" ], "searchable": true }, "Ширина": { "value": [ 100, 120.5 ], "searchable": false } }, + "group_id": "9921", "id": "9922", "uniqid": "9922", "widgetable": true, "ignored": false, "locations": {}, + "model": "LAK", "barcode": "УТ-70041501", "oldprice": "13450", "discount": true, "discount_percent": 20 } }, + "expect": { "result": { "id": "9922", "groupId": "9921", "name": "Скамья Жасмин", "brand": "БРВ Мебель", "model": "LAK", + "barcode": "УТ-70041501", "url": "https://shop.example/p/9922", + "imageUrl": "https://shop.example/i/9922.webp", "picture": "https://shop.example/i/9922-180.webp", + "resizedImages": {}, "price": 10760, "priceFormatted": "10 760 ₽", "priceFull": 10760, + "priceFullFormatted": "10 760.00 ₽", "oldPrice": 13450, "currency": "₽", "discountPercent": 20, + "isNew": false, "categoryIds": [], + "categories": [ { "id": "23", "name": "Прихожие", "url": "https://shop.example/c/23", "level": 1 }, + { "id": "12023", "name": "Скамьи", "url": "https://shop.example/c/12023", "parentId": "23", "level": 2 } ], + "params": [ { "key": "Цвет", "values": [ "графит" ] }, { "key": "Ширина", "values": [ "100", "120.5" ] } ] } } + }, + { + "name": "getInfo: id только в uniqid", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "uniqid": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽" } }, + "expect": { "result": { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽", "isNew": false } } + }, + { + "name": "getInfo: неизвестный товар — 200 {}, результат пустой", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "404" } }, + "response": { "status": 200, "body": {} }, + "expect": { "result": null } + }, + { + "name": "getInfo: непустой ответ без uniqid и id", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": { "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getInfo: 2xx со status error", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getInfo: 500", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": 500, "body": null }, + "expect": { "error": { "type": "http", "code": 500 } } + }, + { + "name": "getInfo: нет ответа", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + }, + { + "name": "getList: страница с фасетами; params списком; товар без обязательного поля пропускается, бренд без количества пропускается", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "response": { "status": 200, + "body": { "products_total": "2", + "products": [ { "id": "37", "group_id": "_37_", "name": "Кроссовки", "url": "https://shop.example/p/37", + "price": 4990, "price_formatted": "4 990 ₽", "oldprice": 0, "oldprice_full": 0, + "currency": "₽", "discount": 15, "is_new": true, "rating": 4, "stock_quantity": "7", + "deeplink_android": "shop://p/37", "deeplink_ios": "shop://p/37", + "image_url_resized": { "120": "https://shop.example/i/37-120.webp", "original": "https://shop.example/i/37.webp" }, + "sales_rate": 120, "relative_sales_rate": 0.5, + "category_ids": [ "5", 6 ], "params": [ { "key": "Размер", "values": [ 42, "43" ] } ] }, + { "id": "38", "name": "Без валюты", "url": "https://shop.example/p/38", "price": 100 } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "parent": "1", "count": 2, "alias": "obuv" } ], + "brands": [ { "name": "Nike", "count": 3, "picture": "https://shop.example/b/nike.png" }, { "name": "Без количества" } ], + "locations": [ { "id": "msk", "name": "Москва", "type": "city" } ], + "filters": { "Цвет": { "count": 3, "priority": 1, "values": { "красный": 2, "синий": "1" } }, + "Вес": { "count": 2, "ranges": { "min": 0.5, "max": "10" } } }, + "price_range": { "min": 100, "max": "9990" }, + "price_ranges": [ { "to": 1000, "count": 2 }, { "from": 1000, "count": 1 } ], + "price_median": "1500" } }, + "expect": { "result": { "productsTotal": 2, + "products": [ { "id": "37", "groupId": "_37_", "name": "Кроссовки", "url": "https://shop.example/p/37", + "price": 4990, "priceFormatted": "4 990 ₽", "currency": "₽", "discountPercent": 15, + "isNew": true, "rating": 4, "stockQuantity": 7, + "deeplinkAndroid": "shop://p/37", "deeplinkIos": "shop://p/37", + "resizedImages": { "120": "https://shop.example/i/37-120.webp", "original": "https://shop.example/i/37.webp" }, + "salesRate": 120, "relativeSalesRate": 0.5, "categoryIds": [ "5", "6" ], + "params": [ { "key": "Размер", "values": [ "42", "43" ] } ] } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "parentId": "1", "count": 2, "alias": "obuv" } ], + "brands": [ { "name": "Nike", "count": 3 } ], + "locations": [ { "id": "msk", "name": "Москва", "type": "city" } ], + "filters": { "Цвет": { "count": 3, "priority": 1, "values": { "красный": 2, "синий": 1 } }, + "Вес": { "count": 2, "min": 0.5, "max": 10 } }, + "priceRange": { "min": 100, "max": 9990 }, + "priceRanges": [ { "from": 0, "to": 1000, "count": 2 }, { "from": 1000, "count": 1 } ], + "priceMedian": 1500 } } + }, + { + "name": "getList: пустая страница", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "response": { "status": 200, "body": { "products_total": 0, "products": [] } }, + "expect": { "result": { "productsTotal": 0, "products": [] } } + }, + { + "name": "getList: ответ без products", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "response": { "status": 200, "body": { "products_total": 0 } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getList: 403", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "response": { "status": 403, "body": null }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "getCounters: числа строкой", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "daily": { "view": 10, "cart": "2", "purchase": 1 }, "now": { "view": 1, "cart": 0, "purchase": 0 }, + "triggers": { "back_in_stock": 3, "price_drop": 4 } } }, + "expect": { "result": { "daily": { "view": 10, "cart": 2, "purchase": 1 }, "now": { "view": 1, "cart": 0, "purchase": 0 }, + "triggers": { "backInStock": 3, "priceDrop": 4 } } } + }, + { + "name": "getCounters: пустой ответ", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": {} }, + "expect": { "result": {} } + }, + { + "name": "getCounters: ответ не объект", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": [] }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getCategory: товары и фасеты категории; поля вне CategoryResponse не попадают в результат", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "5" } }, + "response": { "status": 200, + "body": { "products_total": 1, + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": "4990.50", "currency": "₽", + "oldprice": 5990, "oldprice_formatted": "5 990 ₽", "oldprice_full": 5990.5, "oldprice_full_formatted": "5 990.50 ₽" } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "count": 1 } ], + "brands": [ { "name": "Nike", "count": 1 } ], + "locations": [ { "id": "msk", "name": "Москва" } ], + "industrial_filters": { "colors": [ { "color": "red", "count": 1 } ] }, + "filters": [], + "price_range": { "min": 4990, "max": 4990 }, + "price_ranges": [], + "price_median": 4990 } }, + "expect": { "result": { "productsTotal": 1, + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990.5, "currency": "₽", + "oldPrice": 5990, "oldPriceFormatted": "5 990 ₽", "oldPriceFull": 5990.5, + "oldPriceFullFormatted": "5 990.50 ₽", "isNew": false } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "count": 1 } ], + "brands": [ { "name": "Nike", "count": 1 } ], + "filters": {}, + "priceRange": { "min": 4990, "max": 4990 }, + "priceRanges": [], + "priceMedian": 4990 } } + }, + { + "name": "getCategory: ответ без products", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "5" } }, + "response": { "status": 200, "body": { "status": "success" } }, + "expect": { "error": { "type": "decoding" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/profile.json b/personalization-sdk/src/test/resources/contract/0/profile.json new file mode 100644 index 00000000..c0cf4ce6 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/profile.json @@ -0,0 +1,212 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "request": { "method": "GET", "path": "profile", "query": {} } + }, + { + "name": "set со всеми полями: externalId уходит полями id и external_id, cars — полем auto, свои свойства — на верхнем уровне", + "call": { "namespace": "profile", "method": "set", + "args": { "request": { "email": "jane@example.com", "phone": "+79990000000", "externalId": "u-1", "loyaltyId": "l-1", + "telegramId": "t-1", "fbId": "fb-1", "vkId": "vk-1", "firstName": "Jane", "lastName": "Doe", + "gender": "female", "birthday": "1990-02-28", "age": 36, "location": "msk", + "kids": [ { "gender": "male", "birthday": "2016-02-29" }, { "gender": "female" } ], + "cars": [ { "brand": "Lada", "model": "Vesta", "vds": "XTA000000000" } ], + "customProperties": { "favorite_color": "green", "points": 120, "vip": true, "visited_at": null, + "tags": [ "a", "b" ], "address": { "city": "Moscow" } } } } }, + "request": { "method": "POST", "path": "profile/set", + "body": { "email": "jane@example.com", "phone": "+79990000000", "id": "u-1", "external_id": "u-1", "loyalty_id": "l-1", + "telegram_id": "t-1", "fb_id": "fb-1", "vk_id": "vk-1", "first_name": "Jane", "last_name": "Doe", + "gender": "f", "birthday": "1990-02-28", "age": 36, "location": "msk", + "kids": [ { "gender": "m", "birthday": "2016-02-29" }, { "gender": "f" } ], + "auto": [ { "brand": "Lada", "model": "Vesta", "vds": "XTA000000000" } ], + "favorite_color": "green", "points": 120, "vip": true, "visited_at": null, + "tags": [ "a", "b" ], "address": { "city": "Moscow" } } } + }, + { + "name": "set: пустая строка стирает location", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "location": "" } } }, + "request": { "method": "POST", "path": "profile/set", "body": { "location": "" } } + }, + { + "name": "set: пустые списки не уходят — менять нечего", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "kids": [], "cars": [] } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set без полей", + "call": { "namespace": "profile", "method": "set", "args": { "request": {} } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set с пустым email", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set с пустым phone", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "phone": "" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set с пустым loyaltyId — сервер его не стирает", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "loyaltyId": "" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: пустая строка стирает externalId, telegramId и birthday — они уходят пустыми строками", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "externalId": "", "telegramId": "", "birthday": "" } } }, + "request": { "method": "POST", "path": "profile/set", "body": { "id": "", "external_id": "", "telegram_id": "", "birthday": "" } } + }, + { + "name": "set: age 0 стирает возраст", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "age": 0 } } }, + "request": { "method": "POST", "path": "profile/set", "body": { "age": 0 } } + }, + { + "name": "set: birthday не в формате YYYY-MM-DD", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "birthday": "28.02.1990" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday — несуществующая дата", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "birthday": "2026-02-29" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday с годом до 1000", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "birthday": "0999-12-31" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday с годом после 2999", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "birthday": "3000-01-01" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday ребёнка — несуществующая дата", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "kids": [ { "birthday": "2015-02-29" } ] } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday ребёнка не в формате", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "kids": [ { "birthday": "2016-2-1" } ] } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: отрицательный age", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "age": -1 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: ключ customProperties не из [a-z0-9_]", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "customProperties": { "Favorite-Color": "green" } } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: ключ customProperties совпадает с полем запроса", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "customProperties": { "first_name": "Jane" } } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: ключ customProperties совпадает со служебным полем", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "customProperties": { "did": "x" } } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getLastOrder", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "request": { "method": "GET", "path": "orders/last_for_user", "query": {} } + }, + { + "name": "get: профиль; незнакомый пол — пустое поле, поля вне Profile не попадают в результат", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "response": { "status": 200, + "body": { "id": 123, "has_email": true, "email_registered_at": "2026-11-01 10:00:00", "gender": "f", + "computed_gender": "x", "bought_something": false, "email": "hidden@example.com", + "custom_properties": { "favorite_color": "green", "points": 120, "tags": [ "a", "b" ], "address": { "city": "Moscow" } } } }, + "expect": { "result": { "id": "123", "hasEmail": true, "emailRegisteredAt": "2026-11-01 10:00:00", "gender": "female", + "boughtSomething": false, + "customProperties": { "favorite_color": "green", "points": 120, "tags": [ "a", "b" ], "address": { "city": "Moscow" } } } } + }, + { + "name": "get: пустой профиль", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "response": { "status": 200, "body": {} }, + "expect": { "result": {} } + }, + { + "name": "get: 404 — неизвестный did", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "response": { "status": 404, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "get: ответ не объект", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "response": { "status": 200, "body": [] }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "set: успех", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "jane@example.com" } } }, + "response": { "status": 200, "body": { "status": "success" } }, + "expect": { "result": null } + }, + { + "name": "set: успех без тела", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "jane@example.com" } } }, + "response": { "status": 204, "body": null }, + "expect": { "result": null } + }, + { + "name": "set: 400 — сервер не принял email", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "not-an-email" } } }, + "response": { "status": 400, "body": { "status": "error", "message": "Invalid email" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "set: 2xx со status error", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "jane@example.com" } } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "set: нет ответа", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "jane@example.com" } } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + }, + { + "name": "getLastOrder: товары последнего заказа", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "response": { "status": 200, + "body": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽", + "oldprice": 5990, "is_new": true, "stock_quantity": 1000, "rating": 4, "leftovers": "lots", + "categories": [ { "id": "5", "parent": null, "name": "Обувь", "url": "https://shop.example/c/5" } ] } ] }, + "expect": { "result": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽", + "oldPrice": 5990, "isNew": true, "stockQuantity": 1000, "rating": 4, + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5" } ] } ] } + }, + { + "name": "getLastOrder: заказов нет", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "response": { "status": 200, "body": [] }, + "expect": { "result": [] } + }, + { + "name": "getLastOrder: 400 — неизвестный did", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "response": { "status": 400, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "getLastOrder: ответ не массив", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "response": { "status": 200, "body": { "products": [] } }, + "expect": { "error": { "type": "decoding" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/recommendations.json b/personalization-sdk/src/test/resources/contract/0/recommendations.json new file mode 100644 index 00000000..d0b087bc --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/recommendations.json @@ -0,0 +1,105 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get без запроса — товары целиком", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "request": { "method": "GET", "path": "recommend/block-1", "query": { "extended": "true" } } + }, + { + "name": "get со всеми полями", + "call": { "namespace": "recommendations", "method": "get", + "args": { "code": "block-1", + "request": { "itemId": "37", "categoryId": "5", "searchQuery": "кроссовки", "excludedItemIds": [ "1", "2" ], + "brands": [ "Nike", "Adidas" ], "locations": [ "msk" ], "limit": 10, + "extended": true, "withLocations": true } } }, + "request": { "method": "GET", "path": "recommend/block-1", + "query": { "item_id": "37", "category": "5", "search_query": "кроссовки", "exclude": "1,2", + "brands": "Nike,Adidas", "locations": "msk", "limit": "10", "extended": "true", "with_locations": "true" } } + }, + { + "name": "get только артикулы: extended не уходит", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1", "request": { "extended": false } } }, + "request": { "method": "GET", "path": "recommend/block-1", "query": {} } + }, + { + "name": "get: код блока в пути URL-кодирован", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "a/b" } }, + "request": { "method": "GET", "path": "recommend/a%2Fb", "query": { "extended": "true" } } + }, + { + "name": "get с пустым кодом", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "get с limit 0", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1", "request": { "limit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "get: withLocations без extended", + "call": { "namespace": "recommendations", "method": "get", + "args": { "code": "block-1", "request": { "extended": false, "withLocations": true } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "расширенный ответ: товары целиком, itemIds — их id", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 200, + "body": { "id": 12, "title": "Похожие товары", "link": "https://shop.example/similar", + "recommends": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37?recommended_by=dynamic", + "price": 4990, "currency": "₽", "location_ids": [ "global" ] }, + { "id": "38", "name": "Кеды", "url": "https://shop.example/p/38", "price": "2990", "currency": "₽", + "location_ids": [ "msk", "spb" ] } ] } }, + "expect": { "result": { "id": 12, "title": "Похожие товары", "link": "https://shop.example/similar", + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37?recommended_by=dynamic", + "price": 4990, "currency": "₽", "isNew": false, "locationIds": [ "global" ] }, + { "id": "38", "name": "Кеды", "url": "https://shop.example/p/38", "price": 2990, "currency": "₽", + "isNew": false, "locationIds": [ "msk", "spb" ] } ], + "itemIds": [ "37", "38" ] } } + }, + { + "name": "простой ответ: только артикулы", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1", "request": { "extended": false } } }, + "response": { "status": 200, "body": { "id": 12, "title": "Похожие товары", "recommends": [ "37", "38" ] } }, + "expect": { "result": { "id": 12, "title": "Похожие товары", "products": [], "itemIds": [ "37", "38" ] } } + }, + { + "name": "блок на паузе — пусто, а не decoding", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 200, "body": { "state": "paused" } }, + "expect": { "result": { "products": [], "itemIds": [] } } + }, + { + "name": "ответ без recommends и не на паузе", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 200, "body": { "id": 12, "title": "Похожие товары" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "404 — неизвестный код блока", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "unknown" } }, + "response": { "status": 404, "body": { "status": "error", "message": "Recommender block not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "402 — услуга не оплачена", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 402, "body": { "status": "error", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/reviews.json b/personalization-sdk/src/test/resources/contract/0/reviews.json new file mode 100644 index 00000000..29ba0f32 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/reviews.json @@ -0,0 +1,430 @@ +{ + "contract": "0", + "cases": [ + { + "name": "createNps", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "request": { "method": "POST", "path": "api/v3/polls/nps/reviews", + "body": { "rate": 9, "channel": "ios_app", "category": "delivery" } } + }, + { + "name": "createNps с оценкой 0, заказом, комментарием и меткой", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 0, "channel": "ios_app", "category": "delivery", + "orderId": "A-1001", "comment": "Долго везли", "label": "checkout" } }, + "request": { "method": "POST", "path": "api/v3/polls/nps/reviews", + "body": { "rate": 0, "channel": "ios_app", "category": "delivery", + "order_id": "A-1001", "comment": "Долго везли", "label": "checkout" } } + }, + { + "name": "createNps с пустыми необязательными полями — они не уходят", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 10, "channel": "ios_app", "category": "delivery", + "orderId": "", "comment": "", "label": "" } }, + "request": { "method": "POST", "path": "api/v3/polls/nps/reviews", + "body": { "rate": 10, "channel": "ios_app", "category": "delivery" } } + }, + { + "name": "createNps с оценкой 11", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 11, "channel": "ios_app", "category": "delivery" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createNps с оценкой -1", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": -1, "channel": "ios_app", "category": "delivery" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createNps с пустым каналом", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "", "category": "delivery" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createNps с пустой категорией", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": " " } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCsat", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 5, "channel": "ios_app", "campaign": "support" } }, + "request": { "method": "POST", "path": "api/v3/polls/csat/reviews", + "body": { "rate": 5, "channel": "ios_app", "campaign": "support" } } + }, + { + "name": "createCsat с оценкой 0", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 0, "channel": "ios_app", "campaign": "support" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCsat с оценкой 6", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 6, "channel": "ios_app", "campaign": "support" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCsat с пустой кампанией", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 4, "channel": "ios_app", "campaign": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCes с заказом", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 7, "channel": "ios_app", "campaign": "checkout", "orderId": "A-1001" } }, + "request": { "method": "POST", "path": "api/v3/polls/ces/reviews", + "body": { "rate": 7, "channel": "ios_app", "campaign": "checkout", "order_id": "A-1001" } } + }, + { + "name": "createCes с оценкой 0", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 0, "channel": "ios_app", "campaign": "checkout" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCes с оценкой 8", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 8, "channel": "ios_app", "campaign": "checkout" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCes с пустым каналом", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 3, "channel": "", "campaign": "checkout" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getNpsCategories", + "call": { "namespace": "reviews", "method": "getNpsCategories", "args": {} }, + "request": { "method": "GET", "path": "api/v3/polls/nps/categories", "query": {} } + }, + { + "name": "getNpsChannels", + "call": { "namespace": "reviews", "method": "getNpsChannels", "args": {} }, + "request": { "method": "GET", "path": "api/v3/polls/nps/channels", "query": {} } + }, + { + "name": "getCsatCampaigns", + "call": { "namespace": "reviews", "method": "getCsatCampaigns", "args": {} }, + "request": { "method": "GET", "path": "api/v3/polls/csat/campaigns", "query": {} } + }, + { + "name": "getCesCampaigns", + "call": { "namespace": "reviews", "method": "getCesCampaigns", "args": {} }, + "request": { "method": "GET", "path": "api/v3/polls/ces/campaigns", "query": {} } + }, + { + "name": "getProductReviews", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "request": { "method": "GET", "path": "reviews/product", "query": { "product": "37" } } + }, + { + "name": "getProductReviews со страницей", + "call": { "namespace": "reviews", "method": "getProductReviews", + "args": { "itemId": "37", "limit": 10, "offset": 20 } }, + "request": { "method": "GET", "path": "reviews/product", + "query": { "product": "37", "limit": "10", "offset": "20" } } + }, + { + "name": "getProductReviews с пустым itemId", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getProductReviews с limit 0", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37", "limit": 0 } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getProductReviews с limit 101", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37", "limit": 101 } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getProductReviews с отрицательным offset", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37", "offset": -1 } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getClientReviews", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "request": { "method": "GET", "path": "reviews/client", "query": { "order": "A-1001" } } + }, + { + "name": "getClientReviews с пустым orderId", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createNps — сохранённый отзыв", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "review": { "id": 512 } } } }, + "expect": { "result": { "id": 512 } } + }, + { + "name": "createNps — id больше 2^31", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 10, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "review": { "id": 3000000512, "rate": 10, "comment": null } } } }, + "expect": { "result": { "id": 3000000512 } } + }, + { + "name": "createCsat — id строкой", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 5, "channel": "ios_app", "campaign": "support" } }, + "response": { "status": 201, "body": { "status": "success", "payload": { "review": { "id": "77" } } } }, + "expect": { "result": { "id": 77 } } + }, + { + "name": "createCes — ответ без payload.review.id", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 7, "channel": "ios_app", "campaign": "checkout" } }, + "response": { "status": 200, "body": { "status": "success", "payload": {} } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "createNps — пустой ответ", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 200, "body": null }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "createNps — 400, оценка не прошла проверку", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 400, "body": { "status": "fail", "message": "Comment is too long" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "createNps — 404, нет канала", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 404, "body": { "status": "fail", "message": "Channel not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "createCsat — 402, проект не оплачен", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 5, "channel": "ios_app", "campaign": "support" } }, + "response": { "status": 402, "body": { "status": "fail", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "createCes — 429, больше 30 оценок в минуту", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 7, "channel": "ios_app", "campaign": "checkout" } }, + "response": { "status": 429, "body": { "status": "fail", "message": "Too many requests" } }, + "expect": { "error": { "type": "http", "code": 429 } } + }, + { + "name": "createNps — 2xx со status error", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getNpsCategories — элемент без code пропускается, пустые тексты — пусто", + "call": { "namespace": "reviews", "method": "getNpsCategories", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "categories": [ + { "code": "delivery", "name": "Доставка", + "detractor_question": "Что пошло не так?", "passive_question": "Что улучшить?", + "promoter_question": "Что понравилось?", + "detractor_success": "Разберёмся", "passive_success": "Спасибо", + "promoter_success": "Спасибо!", "button_label": "Готово", "position": 1 }, + { "code": "support", "name": "Поддержка", + "detractor_question": null, "passive_question": "", + "promoter_question": "Что понравилось?" }, + { "name": "Без кода" } + ] } } }, + "expect": { "result": [ + { "code": "delivery", "name": "Доставка", + "detractorQuestion": "Что пошло не так?", "passiveQuestion": "Что улучшить?", + "promoterQuestion": "Что понравилось?", + "detractorSuccess": "Разберёмся", "passiveSuccess": "Спасибо", + "promoterSuccess": "Спасибо!", "buttonLabel": "Готово" }, + { "code": "support", "name": "Поддержка", "promoterQuestion": "Что понравилось?" } + ] } + }, + { + "name": "getNpsChannels — справочник", + "call": { "namespace": "reviews", "method": "getNpsChannels", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "channels": [ { "code": "ios_app", "name": "Приложение iOS" }, + { "code": "web", "name": "Сайт" } ] } } }, + "expect": { "result": [ { "code": "ios_app", "name": "Приложение iOS" }, { "code": "web", "name": "Сайт" } ] } + }, + { + "name": "getCsatCampaigns — справочник", + "call": { "namespace": "reviews", "method": "getCsatCampaigns", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "campaigns": [ + { "code": "support", "name": "Поддержка", + "dissatisfied_question": "Что не так?", "neutral_question": "Что улучшить?", + "satisfied_question": "Что понравилось?", + "dissatisfied_success": "Разберёмся", "neutral_success": "Спасибо", + "satisfied_success": "Спасибо!", "button_label": "Готово" } + ] } } }, + "expect": { "result": [ + { "code": "support", "name": "Поддержка", + "dissatisfiedQuestion": "Что не так?", "neutralQuestion": "Что улучшить?", + "satisfiedQuestion": "Что понравилось?", + "dissatisfiedSuccess": "Разберёмся", "neutralSuccess": "Спасибо", + "satisfiedSuccess": "Спасибо!", "buttonLabel": "Готово" } + ] } + }, + { + "name": "getCesCampaigns — справочник", + "call": { "namespace": "reviews", "method": "getCesCampaigns", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "campaigns": [ + { "code": "checkout", "name": "Оформление заказа", + "difficult_question": "Что мешало?", "neutral_question": "Что улучшить?", + "easy_question": "Что помогло?", + "difficult_success": "Разберёмся", "neutral_success": "Спасибо", + "easy_success": "Спасибо!", "button_label": null } + ] } } }, + "expect": { "result": [ + { "code": "checkout", "name": "Оформление заказа", + "difficultQuestion": "Что мешало?", "neutralQuestion": "Что улучшить?", + "easyQuestion": "Что помогло?", + "difficultSuccess": "Разберёмся", "neutralSuccess": "Спасибо", "easySuccess": "Спасибо!" } + ] } + }, + { + "name": "getCsatCampaigns — нет кампаний", + "call": { "namespace": "reviews", "method": "getCsatCampaigns", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "campaigns": [] } } }, + "expect": { "result": [] } + }, + { + "name": "getNpsChannels — ответ без payload.channels", + "call": { "namespace": "reviews", "method": "getNpsChannels", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "channels": [ { "code": "web", "name": "Сайт" } ] } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getCesCampaigns — 403, проект неактивен", + "call": { "namespace": "reviews", "method": "getCesCampaigns", "args": {} }, + "response": { "status": 403, "body": { "status": "fail", "message": "Access denied" } }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "getProductReviews — сводка и отзывы, числа строкой, отзыв без created_at пропускается", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "summary": { "count": 3, "average_rating": 4.3, + "ratings": { "1": 0, "2": 0, "3": 1, "4": 0, "5": "2" } }, + "reviews": [ + { "id": 11, "rating": 5, "comment": "Отлично", "author": "Анна", + "created_at": "2026-11-10T12:00:00+03:00" }, + { "id": "10", "rating": "3", "comment": null, "author": null, + "created_at": "2026-11-09T08:30:00+03:00" }, + { "id": 9, "rating": 5 } + ] } } }, + "expect": { "result": { + "summary": { "count": 3, "averageRating": 4.3, "ratings": { "1": 0, "2": 0, "3": 1, "4": 0, "5": 2 } }, + "reviews": [ + { "id": 11, "rating": 5, "comment": "Отлично", "author": "Анна", "createdAt": "2026-11-10T12:00:00+03:00" }, + { "id": 10, "rating": 3, "createdAt": "2026-11-09T08:30:00+03:00" } + ] } } + }, + { + "name": "getProductReviews — id отзыва больше 2^31", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "summary": { "count": 1, "average_rating": 5.0, "ratings": { "5": 1 } }, + "reviews": [ { "id": 3000000011, "rating": 5, "created_at": "2026-11-10T12:00:00+03:00" } ] } } }, + "expect": { "result": { + "summary": { "count": 1, "averageRating": 5, "ratings": { "5": 1 } }, + "reviews": [ { "id": 3000000011, "rating": 5, "createdAt": "2026-11-10T12:00:00+03:00" } ] } } + }, + { + "name": "getProductReviews — нет отзывов", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "summary": { "count": 0, "average_rating": null, "ratings": {} }, + "reviews": [] } } }, + "expect": { "result": { "summary": { "count": 0, "ratings": {} }, "reviews": [] } } + }, + { + "name": "getProductReviews — 403, услуга не подключена", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 403, "body": { "status": "error", "payload": { "message": "Service is not enabled" } } }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "getProductReviews — ответ без summary", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "reviews": [] } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getClientReviews — незнакомый state пустой", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "reviews": [ + { "id": 21, "product": "37", "order": "A-1001", "rating": 4, "comment": "Хорошо", + "state": "published", "created_at": "2026-11-10T12:00:00+03:00" }, + { "id": 22, "product": 38, "order": "A-1001", "rating": 2, + "state": "moderation", "created_at": "2026-11-10T12:05:00+03:00" }, + { "id": 23, "product": "39", "order": "A-1001", "rating": 1, + "state": "archived", "created_at": "2026-11-10T12:10:00+03:00" } + ] } } }, + "expect": { "result": [ + { "id": 21, "itemId": "37", "orderId": "A-1001", "rating": 4, "comment": "Хорошо", + "state": "published", "createdAt": "2026-11-10T12:00:00+03:00" }, + { "id": 22, "itemId": "38", "orderId": "A-1001", "rating": 2, + "state": "moderation", "createdAt": "2026-11-10T12:05:00+03:00" }, + { "id": 23, "itemId": "39", "orderId": "A-1001", "rating": 1, "createdAt": "2026-11-10T12:10:00+03:00" } + ] } + }, + { + "name": "getClientReviews — id отзыва больше 2^31", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "reviews": [ + { "id": 3000000021, "product": "37", "order": "A-1001", "rating": 4, + "state": "published", "created_at": "2026-11-10T12:00:00+03:00" } ] } } }, + "expect": { "result": [ + { "id": 3000000021, "itemId": "37", "orderId": "A-1001", "rating": 4, "state": "published", "createdAt": "2026-11-10T12:00:00+03:00" } + ] } + }, + { + "name": "getClientReviews — нет отзывов", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "reviews": [] } } }, + "expect": { "result": [] } + }, + { + "name": "getClientReviews — 404, чужой заказ", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "response": { "status": 404, "body": { "status": "error", "payload": { "message": "Order not found" } } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "getNpsCategories — нет ответа", + "call": { "namespace": "reviews", "method": "getNpsCategories", "args": {} }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/search.json b/personalization-sdk/src/test/resources/contract/0/search.json new file mode 100644 index 00000000..91ec39a9 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/search.json @@ -0,0 +1,376 @@ +{ + "contract": "0", + "cases": [ + { + "name": "blank", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "request": { "method": "GET", "path": "search/blank", "query": {} } + }, + { + "name": "instant", + "call": { "namespace": "search", "method": "instant", "args": { "query": "iphone" } }, + "request": { "method": "GET", "path": "search", "query": { "type": "instant_search", "search_query": "iphone" } } + }, + { + "name": "instant со списками через запятую без пробелов", + "call": { "namespace": "search", "method": "instant", + "args": { "query": "iphone", "locations": [ "msk", "spb" ], "excludedMerchants": [ "m1", "m2" ], "excludedBrands": [ "b1", "b2" ] } }, + "request": { "method": "GET", "path": "search", + "query": { "type": "instant_search", "search_query": "iphone", "locations": "msk,spb", + "excluded_merchants": "m1,m2", "excluded_brands": "b1,b2" } } + }, + { + "name": "instant: excludedMerchants без locations не уходит", + "call": { "namespace": "search", "method": "instant", "args": { "query": "iphone", "excludedMerchants": [ "m1" ] } }, + "request": { "method": "GET", "path": "search", "query": { "type": "instant_search", "search_query": "iphone" } } + }, + { + "name": "instant с пустым запросом", + "call": { "namespace": "search", "method": "instant", "args": { "query": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full без запроса", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone" } }, + "request": { "method": "GET", "path": "search", "query": { "type": "full_search", "search_query": "iphone" } } + }, + { + "name": "full со всеми полями: направление сортировки — order, уточнение — no_clarification", + "call": { "namespace": "search", "method": "full", + "args": { "query": "iphone", + "request": { "categoryIds": [ "1", "2" ], "brands": [ "Apple" ], "excludedBrands": [ "Noname" ], + "merchants": [ "m1" ], "excludedMerchants": [ "m2" ], "locations": [ "msk" ], + "priceMin": 1000, "priceMax": 99999.99, "colors": [ "black", "white" ], "fashionSizes": [ "42" ], + "excludedItemIds": [ "37" ], "filters": { "memory": [ "128", "256" ] }, + "sortBy": "relevance", "sortDir": "desc", "disableClarification": true, + "categoryLimit": 5, "brandLimit": 50, "limit": 24, "page": 3 } } }, + "request": { "method": "GET", "path": "search", + "query": { "type": "full_search", "search_query": "iphone", "categories": "1,2", "brands": "Apple", + "excluded_brands": "Noname", "merchants": "m1", "excluded_merchants": "m2", "locations": "msk", + "price_min": "1000", "price_max": "99999.99", "colors": "black,white", "fashion_sizes": "42", + "exclude": "37", "filters": "{\"memory\":[\"128\",\"256\"]}", "sort_by": "relevance", "order": "desc", + "no_clarification": "true", "category_limit": "5", "brand_limit": "50", "limit": "24", "page": "3" } } + }, + { + "name": "full: excludedMerchants без locations не уходит, disableClarification false не уходит", + "call": { "namespace": "search", "method": "full", + "args": { "query": "iphone", "request": { "excludedMerchants": [ "m2" ], "disableClarification": false } } }, + "request": { "method": "GET", "path": "search", "query": { "type": "full_search", "search_query": "iphone" } } + }, + { + "name": "full с пустым запросом", + "call": { "namespace": "search", "method": "full", "args": { "query": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с limit 0", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "limit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с page 0", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "page": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с categoryLimit 0", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "categoryLimit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с brandLimit 0", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "brandLimit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с отрицательной ценой", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "priceMax": -5 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с priceMin больше priceMax", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "priceMin": 500, "priceMax": 100 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "blank: недавние запросы и товары покупателя, подсказки, популярное; html не попадает в результат", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "response": { "status": 200, + "body": { "last_queries": [ { "name": "iphone", "url": "https://shop.example/search?q=iphone" } ], + "suggests": [ { "name": "iphone 15", "url": "https://shop.example/search?q=iphone+15" } ], + "last_products": true, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽" } ], + "popular_categories": [ { "name": "Смартфоны", "url": "https://shop.example/c/1" } ], + "popular_brands": [ { "name": "Apple", "url": "https://shop.example/b/apple" } ], + "popular_links": [ { "name": "Распродажа", "url": "https://shop.example/sale" }, { "name": "Без ссылки" } ], + "html": "
" } }, + "expect": { "result": { "lastQueries": [ { "name": "iphone", "url": "https://shop.example/search?q=iphone" } ], + "suggests": [ { "name": "iphone 15", "url": "https://shop.example/search?q=iphone+15" } ], + "lastProducts": true, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽", "isNew": false } ], + "popularCategories": [ { "name": "Смартфоны", "url": "https://shop.example/c/1" } ], + "popularBrands": [ { "name": "Apple", "url": "https://shop.example/b/apple" } ], + "popularLinks": [ { "name": "Распродажа", "url": "https://shop.example/sale" } ] } } + }, + { + "name": "blank: без last_products — популярные товары", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "response": { "status": 200, + "body": { "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽" } ] } }, + "expect": { "result": { "lastProducts": false, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽", "isNew": false } ] } } + }, + { + "name": "blank: совсем пустой ответ — []", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "response": { "status": 200, "body": [] }, + "expect": { "result": { "products": [], "lastProducts": false } } + }, + { + "name": "instant: результаты, категории-фасеты, подсказки с оценкой, локации, переход вместо результатов", + "call": { "namespace": "search", "method": "instant", "args": { "query": "ifone" } }, + "response": { "status": 200, + "body": { "search_query": "iphone", "search_query_original": "ifone", "clarification": false, "products_total": 1, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽", + "discount_percent": 10, "discount_formatted": "10%" } ], + "categories": [ { "id": "1", "name": "Смартфоны", "url": "https://shop.example/c/1", "parent": null, "count": 1, "alias": "phones" } ], + "queries": [ { "name": "iphone 15", "url": "https://shop.example/search?q=iphone+15", "score": "0.9" } ], + "locations": [ { "id": "msk", "name": "Москва", "type": null } ], + "search_query_redirects": { "query": "iphone", "redirect_link": "https://shop.example/apple", "deep_link": null }, + "html": "
", "requests_count": 3, "book_author": [], "collections": [] } }, + "expect": { "result": { "searchQuery": "iphone", "searchQueryOriginal": "ifone", "clarification": false, "productsTotal": 1, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽", + "discountPercent": 10, "discountFormatted": "10%", "isNew": false } ], + "categories": [ { "id": "1", "name": "Смартфоны", "url": "https://shop.example/c/1", "count": 1, "alias": "phones" } ], + "queries": [ { "name": "iphone 15", "url": "https://shop.example/search?q=iphone+15", "score": 0.9 } ], + "locations": [ { "id": "msk", "name": "Москва" } ], + "redirect": { "query": "iphone", "url": "https://shop.example/apple" } } } + }, + { + "name": "instant: ничего не найдено", + "call": { "namespace": "search", "method": "instant", "args": { "query": "zzz" } }, + "response": { "status": 200, "body": { "search_query": "zzz", "products_total": 0, "products": [] } }, + "expect": { "result": { "searchQuery": "zzz", "productsTotal": 0, "products": [] } } + }, + { + "name": "full: результаты с фасетами", + "call": { "namespace": "search", "method": "full", "args": { "query": "кроссовки" } }, + "response": { "status": 200, + "body": { "search_query": "кроссовки", "clarification": true, "products_total": 120, + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽" } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "parent": "1", "count": 120 } ], + "brands": [ { "name": "Nike", "count": 80 }, { "name": "Adidas", "count": "40" } ], + "locations": [ { "id": "msk", "name": "Москва", "type": "city" } ], + "filters": { "Размер": { "count": 120, "priority": 2, "values": { "42": 30, "43": 25 } } }, + "industrial_filters": { "colors": [ { "color": "black", "count": 70 } ], "fashion_sizes": [ { "size": "42", "count": 30 }, { "count": 1 } ] }, + "price_range": { "min": 1990, "max": 19990 }, + "price_ranges": [ { "from": 0, "to": 5000, "count": 90 }, { "from": 5000, "count": 30 } ], + "price_median": 4990, "html": "", "requests_count": 1, "collections": [] } }, + "expect": { "result": { "searchQuery": "кроссовки", "clarification": true, "productsTotal": 120, + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽", "isNew": false } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "parentId": "1", "count": 120 } ], + "brands": [ { "name": "Nike", "count": 80 }, { "name": "Adidas", "count": 40 } ], + "locations": [ { "id": "msk", "name": "Москва", "type": "city" } ], + "filters": { "Размер": { "count": 120, "priority": 2, "values": { "42": 30, "43": 25 } } }, + "industrialFilters": { "colors": [ { "color": "black", "count": 70 } ], "fashionSizes": [ { "size": "42", "count": 30 } ] }, + "priceRange": { "min": 1990, "max": 19990 }, + "priceRanges": [ { "from": 0, "to": 5000, "count": 90 }, { "from": 5000, "count": 30 } ], + "priceMedian": 4990 } } + }, + { + "name": "instant: ответ без products", + "call": { "namespace": "search", "method": "instant", "args": { "query": "iphone" } }, + "response": { "status": 200, "body": { "queries": [] } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "full: ответ без products", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone" } }, + "response": { "status": 200, "body": { "products_total": 0 } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "full: ответ не объект", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone" } }, + "response": { "status": 200, "body": [] }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "instant: 2xx со status error", + "call": { "namespace": "search", "method": "instant", "args": { "query": "iphone" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "full: 500", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone" } }, + "response": { "status": 500, "body": null }, + "expect": { "error": { "type": "http", "code": 500 } } + }, + { + "name": "blank: нет ответа", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + }, + { + "name": "agentDialog без параметров — последняя сессия, локация из профиля", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "request": {"method": "GET", "path": "api/v3/storefront/search/agent", "query": {}} + }, + { + "name": "agentDialog с сессией и локациями: location через запятую", + "call": {"namespace": "search", "method": "agentDialog", "args": {"sessionId": 12, "locations": ["msk", "spb"]}}, + "request": {"method": "GET", "path": "api/v3/storefront/search/agent", "query": {"session_id": "12", "location": "msk,spb"}} + }, + { + "name": "agent: новая сессия, тело — JSON", + "call": {"namespace": "search", "method": "agent", "args": {"message": "нужна флешка на 1тб"}}, + "request": {"method": "POST", "path": "api/v3/storefront/search/agent", "body": {"message": "нужна флешка на 1тб"}} + }, + { + "name": "agent в сессии с локацией", + "call": {"namespace": "search", "method": "agent", "args": {"message": "а есть подешевле?", "sessionId": 12, "locations": ["msk"]}}, + "request": {"method": "POST", "path": "api/v3/storefront/search/agent", "body": {"message": "а есть подешевле?", "session_id": 12, "location": "msk"}} + }, + { + "name": "agent: id сессии больше 2^31", + "call": {"namespace": "search", "method": "agent", "args": {"message": "ещё", "sessionId": 3000000012}}, + "request": {"method": "POST", "path": "api/v3/storefront/search/agent", "body": {"message": "ещё", "session_id": 3000000012}} + }, + { + "name": "agentDialog: id сессии больше 2^31 уходит строкой", + "call": {"namespace": "search", "method": "agentDialog", "args": {"sessionId": 3000000012}}, + "request": {"method": "GET", "path": "api/v3/storefront/search/agent", "query": {"session_id": "3000000012"}} + }, + { + "name": "agent: сообщение в 500 символов", + "call": {"namespace": "search", "method": "agent", "args": {"message": "яяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяя"}}, + "request": {"method": "POST", "path": "api/v3/storefront/search/agent", "body": {"message": "яяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяя"}} + }, + { + "name": "agent с пустым сообщением", + "call": {"namespace": "search", "method": "agent", "args": {"message": ""}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "agent: сообщение длиннее 500 символов", + "call": {"namespace": "search", "method": "agent", "args": {"message": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "agentDialog: сессии и сообщения выбранной; товар без id пропускается", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 200, "body": {"sessions": [{"id": 12, "title": "Флешка на 1 ТБ", "updated_at": "2026-11-01T12:00:00Z"}, {"id": 9, "title": "Наушники", "updated_at": "2026-10-30T08:15:00Z"}], "session": {"id": 12, "title": "Флешка на 1 ТБ", "updated_at": "2026-11-01T12:00:00Z", "messages": [{"id": 1, "role": "user", "content": "нужна флешка на 1тб", "products": [], "created_at": "2026-11-01T11:59:40Z"}, {"id": 2, "role": "assistant", "content": "Нашёл три флешки на 1 ТБ с USB 3.2...", "created_at": "2026-11-01T12:00:00Z", "products": [{"id": "123", "name": "Флешка Example 1 ТБ", "price": 1990.0, "oldprice": 2490.0, "price_formatted": "1 990 ₽", "oldprice_formatted": "2 490 ₽", "picture": "https://example.com/images/123.jpg", "url": "https://example.com/p/123?recommended_by=agent_search&recommended_code=12", "reason": "Объём 1 ТБ, USB 3.2"}, {"name": "Без id", "price": 100.0}]}]}}}, + "expect": {"result": {"sessions": [{"id": 12, "title": "Флешка на 1 ТБ", "updatedAt": "2026-11-01T12:00:00Z", "messages": []}, {"id": 9, "title": "Наушники", "updatedAt": "2026-10-30T08:15:00Z", "messages": []}], "session": {"id": 12, "title": "Флешка на 1 ТБ", "updatedAt": "2026-11-01T12:00:00Z", "messages": [{"id": 1, "role": "user", "content": "нужна флешка на 1тб", "createdAt": "2026-11-01T11:59:40Z", "products": []}, {"id": 2, "role": "assistant", "content": "Нашёл три флешки на 1 ТБ с USB 3.2...", "createdAt": "2026-11-01T12:00:00Z", "products": [{"id": "123", "name": "Флешка Example 1 ТБ", "price": 1990, "oldPrice": 2490, "priceFormatted": "1 990 ₽", "oldPriceFormatted": "2 490 ₽", "picture": "https://example.com/images/123.jpg", "url": "https://example.com/p/123?recommended_by=agent_search&recommended_code=12", "reason": "Объём 1 ТБ, USB 3.2"}]}]}}} + }, + { + "name": "agentDialog: сессий ещё нет", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 200, "body": {"sessions": [], "session": null}}, + "expect": {"result": {"sessions": []}} + }, + { + "name": "agent: ответ агента; старая цена 0.0 — пусто", + "call": {"namespace": "search", "method": "agent", "args": {"message": "а есть подешевле?", "sessionId": 12}}, + "response": {"status": 200, "body": {"session": {"id": 12, "title": "Флешка на 1 ТБ", "updated_at": "2026-11-01T12:01:10Z"}, "message": {"id": 4, "role": "assistant", "content": "Вот варианты дешевле 1 500 ₽...", "created_at": "2026-11-01T12:01:10Z", "products": [{"id": "456", "name": "Флешка Example Lite 1 ТБ", "price": 1390.0, "oldprice": 0.0, "price_formatted": "1 390 ₽", "oldprice_formatted": null, "picture": null, "url": null, "reason": ""}]}}}, + "expect": {"result": {"session": {"id": 12, "title": "Флешка на 1 ТБ", "updatedAt": "2026-11-01T12:01:10Z", "messages": []}, "message": {"id": 4, "role": "assistant", "content": "Вот варианты дешевле 1 500 ₽...", "createdAt": "2026-11-01T12:01:10Z", "products": [{"id": "456", "name": "Флешка Example Lite 1 ТБ", "price": 1390, "priceFormatted": "1 390 ₽", "reason": ""}]}}} + }, + { + "name": "agent: незнакомая роль читается как есть — открытый набор", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 200, "body": {"session": {"id": 13}, "message": {"id": 1, "role": "system", "content": "Агент обновлён"}}}, + "expect": {"result": {"session": {"id": 13, "messages": []}, "message": {"id": 1, "role": "system", "content": "Агент обновлён", "products": []}}} + }, + { + "name": "agent: id сессии и сообщения больше 2^31", + "call": {"namespace": "search", "method": "agent", "args": {"message": "ещё", "sessionId": 3000000012}}, + "response": {"status": 200, "body": {"session": {"id": 3000000012, "title": "Флешка"}, "message": {"id": 3000000099, "role": "assistant", "content": "Вот ещё", "products": []}}}, + "expect": {"result": {"session": {"id": 3000000012, "title": "Флешка", "messages": []}, "message": {"id": 3000000099, "role": "assistant", "content": "Вот ещё", "products": []}}} + }, + { + "name": "agent: ответ без message", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 200, "body": {"session": {"id": 13}}}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "agentDialog: ответ не объект", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 200, "body": []}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "agent: 400 — нет did", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 400, "body": {"error": "did is required"}}, + "expect": {"error": {"type": "http", "code": 400}} + }, + { + "name": "agent: 402 — услуга поиска не подключена", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 402, "body": {"status": "fail", "message": "Search is not paid"}}, + "expect": {"error": {"type": "http", "code": 402}} + }, + { + "name": "agent: 403 — магазин неактивен или неверный секрет", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 403, "body": {"status": "fail", "message": "Access denied"}}, + "expect": {"error": {"type": "http", "code": 403}} + }, + { + "name": "agentDialog: 403 — магазин неактивен", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 403, "body": {"status": "fail", "message": "Access denied"}}, + "expect": {"error": {"type": "http", "code": 403}} + }, + { + "name": "agentDialog: 404 — сессия не найдена или чужая", + "call": {"namespace": "search", "method": "agentDialog", "args": {"sessionId": 99}}, + "response": {"status": 404, "body": {"error": "Session not found"}}, + "expect": {"error": {"type": "http", "code": 404}} + }, + { + "name": "agent: 422 — сообщение длиннее 500 символов по счёту сервера", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 422, "body": {"error": "Message is too long"}}, + "expect": {"error": {"type": "http", "code": 422}} + }, + { + "name": "agent: 429 — превышен лимит", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 429, "body": {"error": "Too many requests"}}, + "expect": {"error": {"type": "http", "code": 429}} + }, + { + "name": "agentDialog: 503 — агент недоступен, показать blank", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 503, "body": {"error": "Agent is unavailable"}}, + "expect": {"error": {"type": "http", "code": 503}} + }, + { + "name": "agent: 503 — агент не ответил", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 503, "body": {"error": "Agent is unavailable"}}, + "expect": {"error": {"type": "http", "code": 503}} + }, + { + "name": "agent: 503 — посетитель в контрольной группе поиска, показать blank", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 503, "body": {"error": "agent is unavailable"}}, + "expect": {"error": {"type": "http", "code": 503}} + }, + { + "name": "agentDialog: 503 — посетитель в контрольной группе поиска, показать blank", + "call": {"namespace": "search", "method": "agentDialog", "args": {"sessionId": 3000000012}}, + "response": {"status": 503, "body": {"error": "agent is unavailable"}}, + "expect": {"error": {"type": "http", "code": 503}} + }, + { + "name": "agent: нет ответа", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": null}, + "expect": {"error": {"type": "network"}} + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/segments.json b/personalization-sdk/src/test/resources/contract/0/segments.json new file mode 100644 index 00000000..256d09a0 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/segments.json @@ -0,0 +1,82 @@ +{ + "contract": "0", + "cases": [ + { + "name": "add", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12}}, + "request": {"method": "POST", "path": "segments/add", "body": {"segment_id": 12}} + }, + { + "name": "add с контактами", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12, "email": "jane@example.com", "phone": "+79990000000"}}, + "request": {"method": "POST", "path": "segments/add", "body": {"segment_id": 12, "email": "jane@example.com", "phone": "+79990000000"}} + }, + { + "name": "remove", + "call": {"namespace": "segments", "method": "remove", "args": {"segmentId": 12}}, + "request": {"method": "POST", "path": "segments/remove", "body": {"segment_id": 12}} + }, + { + "name": "add с segmentId 0", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 0}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "remove с отрицательным segmentId", + "call": {"namespace": "segments", "method": "remove", "args": {"segmentId": -3}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "add с пустым email", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12, "email": ""}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "get — GET, не POST из документации", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "request": {"method": "GET", "path": "segments/get", "query": {}} + }, + { + "name": "get: сегменты клиента; незнакомый тип читается как есть, сегмент без id пропускается", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "response": {"status": 200, "body": [{"id": 1, "type": "dynamic"}, {"id": "2", "type": "static"}, {"id": 3, "type": "brand_new_kind"}, {"type": "rfm"}]}, + "expect": {"result": [{"id": 1, "type": "dynamic"}, {"id": 2, "type": "static"}, {"id": 3, "type": "brand_new_kind"}]} + }, + { + "name": "get: сегментов нет", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "response": {"status": 200, "body": []}, + "expect": {"result": []} + }, + { + "name": "get: 404 — неизвестный did", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "response": {"status": 404, "body": {"status": "error", "message": "User not found"}}, + "expect": {"error": {"type": "http", "code": 404}} + }, + { + "name": "get: ответ не массив", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "response": {"status": 200, "body": {"segments": []}}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "add: успех", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12}}, + "response": {"status": 200, "body": {"status": "success"}}, + "expect": {"result": null} + }, + { + "name": "remove: 2xx со status error", + "call": {"namespace": "segments", "method": "remove", "args": {"segmentId": 12}}, + "response": {"status": 200, "body": {"status": "error", "message": "Something went wrong"}}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "add: нет ответа", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12}}, + "response": {"status": null}, + "expect": {"error": {"type": "network"}} + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/sliders.json b/personalization-sdk/src/test/resources/contract/0/sliders.json new file mode 100644 index 00000000..1bb370d5 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/sliders.json @@ -0,0 +1,123 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "request": { "method": "GET", "path": "slider", "query": { "code": "homepage_mobile" } } + }, + { + "name": "get с тегами и локацией: теги через запятую", + "call": { "namespace": "sliders", "method": "get", + "args": { "code": "homepage_mobile", "tags": [ "sale", "new" ], "locationId": "msk-1" } }, + "request": { "method": "GET", "path": "slider", "query": { "code": "homepage_mobile", "tags": "sale,new", "location": "msk-1" } } + }, + { + "name": "get с пустым code", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "get с запятой в теге", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile", "tags": [ "sale,new" ] } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "get с пустым тегом", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile", "tags": [ "sale", "" ] } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "слайдер с баннерами: список — payload.slides, id из banner_id строкой (В54, В55)", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "properties": { "code": "homepage_mobile", "width": 1000, "height": 160 }, + "slides": [ + { "banner_id": 12, "recommended_code": "homepage_mobile", + "image_url": "https://cdn.example/b12.jpg", "url": "https://shop.example/sale", + "deeplink_ios": "app://sale", "deeplink_android": "app://sale", + "content_type": "image", "content": "x", "html": null }, + { "banner_id": "13", "recommended_code": "homepage_mobile", + "image_url": null, "url": null, "html": "
Sale
" } ] } } }, + "expect": { "result": { + "code": "homepage_mobile", "width": 1000, "height": 160, + "banners": [ + { "id": "12", "code": "homepage_mobile", "imageUrl": "https://cdn.example/b12.jpg", "url": "https://shop.example/sale", + "deeplinkIos": "app://sale", "deeplinkAndroid": "app://sale", "html": null }, + { "id": "13", "code": "homepage_mobile", "imageUrl": null, "url": null, "deeplinkIos": null, "deeplinkAndroid": null, + "html": "
Sale
" } ] } } + }, + { + "name": "пустой слайдер", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "properties": { "code": "homepage_mobile", "width": "1000", "height": "160" }, "slides": [] } } }, + "expect": { "result": { "code": "homepage_mobile", "width": 1000, "height": 160, "banners": [] } } + }, + { + "name": "404 — неизвестный или неактивный слайдер (В53)", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "nope" } }, + "response": { "status": 404, "body": { "status": "error", "message": "Slider not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "403 с пустым телом — неизвестный или отключённый магазин", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 403, "body": null }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "402 — услуга слайдеров не оплачена", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 402, "body": { "status": "error", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "2xx со status error из документации", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 200, "body": { "status": "error", "payload": { "message": "Invalid slider code" } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "ответ без payload", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 200, "body": { "status": "success" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + }, + { + "name": "bannerView", + "call": { "namespace": "tracking", "method": "bannerView", "args": { "bannerId": "12", "code": "homepage_mobile" } }, + "request": { "method": "POST", "path": "track/slider", + "body": { "event": "view", "banner_id": 12, "recommended_code": "homepage_mobile" } } + }, + { + "name": "bannerClick", + "call": { "namespace": "tracking", "method": "bannerClick", "args": { "bannerId": "12", "code": "homepage_mobile" } }, + "request": { "method": "POST", "path": "track/slider", + "body": { "event": "click", "banner_id": 12, "recommended_code": "homepage_mobile" } } + }, + { + "name": "bannerView с пустым bannerId", + "call": { "namespace": "tracking", "method": "bannerView", "args": { "bannerId": "", "code": "homepage_mobile" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "bannerClick с bannerId не целым числом", + "call": { "namespace": "tracking", "method": "bannerClick", "args": { "bannerId": "b-12", "code": "homepage_mobile" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "bannerView с пустым code", + "call": { "namespace": "tracking", "method": "bannerView", "args": { "bannerId": "12", "code": "" } }, + "error": { "type": "invalidArgument" } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/stories.json b/personalization-sdk/src/test/resources/contract/0/stories.json new file mode 100644 index 00000000..057fc316 --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/stories.json @@ -0,0 +1,154 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "request": { "method": "GET", "path": "stories/115bd0b67cf5989a1b60c841790b2af6", "query": {} } + }, + { + "name": "get с пустым code", + "call": { "namespace": "stories", "method": "get", "args": { "code": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "блок: товарный слайд, видео, картинка с кнопкой, товарами и текстом; header пропускается", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, + "body": { "id": 35, + "settings": { "color": "#212529" }, + "stories": [ + { "id": 39, "name": "Test story", "avatar": "https://cdn.example/avatar.jpg", + "viewed": false, "start_position": 0, "pinned": false, + "slides": [ + { "id": "39_0", "duration": 10, "background": "https://cdn.example/bg.jpg", "preview": "", "type": "", + "elements": [ + { "type": "button", "title": "Buy", "link": "https://shop.example/p/1?recommended_by=dynamic", + "link_ios": "https://shop.example/p/1", "link_android": "https://shop.example/p/1", + "background": "#3b82f6", "color": "#ffffff" }, + { "type": "product", "title": "Pool", + "item": { "id": "216908", "name": "Pool INTEX", "brand": "INTEX", + "picture": "https://pictures.example/180/135478.jpg", + "image_url": "https://api.example/216908_1.jpg", + "price": 19990, "price_formatted": "19 990 ₽", + "oldprice": 27990, "oldprice_formatted": "27 990 ₽", + "discount_percent": 28, "currency": "₽", + "url": "https://shop.example/p/1?recommended_by=stories", + "deeplink_android": "app://p/1", "deeplink_ios": "app://p/1" } } ] } ] }, + { "id": "40", "name": "Gaming", "avatar": "https://cdn.example/avatar2.jpg", + "viewed": true, "start_position": "1", "pinned": true, + "slides": [ + { "id": 36, "duration": "15", "background": "https://cdn.example/clip.mp4", + "preview": "https://cdn.example/poster.jpg", "type": "video" }, + { "id": 37, "duration": 0, "background": "https://cdn.example/slide.jpg", + "background_color": "#000000", "preview": "", "type": "image", + "elements": [ + { "type": "button", "title": "Go gaming!", "link": "https://demo.example/", "link_ios": "", + "link_android": "https://demo.example/", "text_bold": true, + "background": "#3b82f6", "color": "#ffffff" }, + { "type": "products", + "labels": { "show_carousel": "Show products", "hide_carousel": "Hide products" }, + "products": [ { "id": 1, "name": "Mouse", "price": "1990.0", "price_formatted": "1 990 ₽", + "oldprice": 1990, "promocode": "GAME5", "price_with_promocode": 1890, + "price_with_promocode_formatted": "1 890 ₽" } ] }, + { "type": "text_block", "text_input": "Up to 10% off", "font_size": "24", "font_type": "serif", + "bold": true, "italic": false, "text_align": "center", "text_color": "#FFFFFF", + "text_background_color": "#16AE13", "text_background_color_opacity": "40%", + "text_line_spacing": "1.2", "y_offset": 12, "promocode": "SALE10" }, + { "type": "header", "title": "left out" }, + { "type": "poll", "question": "left out" } ] }, + { "id": 38, "background": "https://cdn.example/plain.jpg", "type": "image" } ] } ] } }, + "expect": { "result": { + "id": "35", + "stories": [ + { "id": "39", "name": "Test story", "avatar": "https://cdn.example/avatar.jpg", + "viewed": false, "pinned": false, "startPosition": 0, + "slides": [ + { "id": "39_0", "type": "product", "background": "https://cdn.example/bg.jpg", "backgroundColor": "", "preview": "", + "duration": 10, + "elements": [ + { "type": "button", "title": "Buy", "link": "https://shop.example/p/1?recommended_by=dynamic", + "linkAndroid": "https://shop.example/p/1", "linkIos": "https://shop.example/p/1", + "background": "#3b82f6", "color": "#ffffff", "textBold": false }, + { "type": "product", "title": "Pool", + "item": { "id": "216908", "name": "Pool INTEX", "brand": "INTEX", + "picture": "https://pictures.example/180/135478.jpg", "imageUrl": "https://api.example/216908_1.jpg", + "price": 19990, "priceFormatted": "19 990 ₽", "oldPrice": 27990, "oldPriceFormatted": "27 990 ₽", + "discountPercent": 28, "promocode": "", "priceWithPromocode": 0, "priceWithPromocodeFormatted": "", + "currency": "₽", "url": "https://shop.example/p/1?recommended_by=stories", + "deeplinkAndroid": "app://p/1", "deeplinkIos": "app://p/1" } } ] } ] }, + { "id": "40", "name": "Gaming", "avatar": "https://cdn.example/avatar2.jpg", + "viewed": true, "pinned": true, "startPosition": 1, + "slides": [ + { "id": "36", "type": "video", "background": "https://cdn.example/clip.mp4", + "preview": "https://cdn.example/poster.jpg", "duration": 15, "elements": [] }, + { "id": "37", "type": "image", "background": "https://cdn.example/slide.jpg", "backgroundColor": "#000000", + "duration": 10, + "elements": [ + { "type": "button", "title": "Go gaming!", "linkIos": "", "textBold": true }, + { "type": "products", "showLabel": "Show products", "hideLabel": "Hide products", + "products": [ { "id": "1", "name": "Mouse", "brand": "", "price": 1990, "oldPrice": null, + "discountPercent": 0, "promocode": "GAME5", "priceWithPromocode": 1890, + "priceWithPromocodeFormatted": "1 890 ₽" } ] }, + { "type": "textBlock", "text": "Up to 10% off", "fontSize": 24, "fontType": "serif", "bold": true, + "italic": false, "textAlign": "center", "textColor": "#FFFFFF", "backgroundColor": "#16AE13", + "backgroundOpacity": 0.4, "lineSpacing": 1.2, "yOffset": 12, "promocode": "SALE10" } ] }, + { "id": "38", "type": "image", "duration": 10, "backgroundColor": "", "preview": "", "elements": [] } ] } ] } } + }, + { + "name": "текстовый блок без полей — значения по умолчанию, товар без item", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, + "body": { "id": "35", "stories": [ { "id": 1, "slides": [ { "id": 2, "type": "image", + "elements": [ { "type": "text_block" }, { "type": "product", "item": {} }, { "type": "something_new" } ] } ] } ] } }, + "expect": { "result": { "id": "35", "stories": [ { "id": "1", "name": "", "avatar": "", "viewed": false, "pinned": false, + "startPosition": 0, + "slides": [ { "id": "2", "type": "image", "elements": [ + { "type": "textBlock", "text": "", "fontSize": 14, "fontType": "", "bold": false, "backgroundOpacity": 0, + "lineSpacing": 0, "yOffset": 0, "promocode": null }, + { "type": "product", "title": "", "item": null } ] } ] } ] } } + }, + { + "name": "блок на паузе — успех с пустым stories", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, "body": { "id": 35, "stories": [], "state": "paused" } }, + "expect": { "result": { "id": "35", "stories": [] } } + }, + { + "name": "404 — неизвестный блок", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 404, "body": { "status": "error", "message": "Stories not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "402 — услуга сторис не оплачена", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 402, "body": { "status": "error", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "400 — неизвестный покупатель", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 400, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "ответ не JSON-объект", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, "body": [ { "id": 35 } ] }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/personalization-sdk/src/test/resources/contract/0/subscriptions.json b/personalization-sdk/src/test/resources/contract/0/subscriptions.json new file mode 100644 index 00000000..6b7c4e4b --- /dev/null +++ b/personalization-sdk/src/test/resources/contract/0/subscriptions.json @@ -0,0 +1,144 @@ +{ + "contract": "0", + "cases": [ + { + "name": "manage: контакты и флаги; null не уходит", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"email": "jane@example.com", "phone": "+79990000000", "externalId": "u-1", "loyaltyId": "l-1", "telegramId": "t-1", "emailBulk": true, "smsChain": false, "walletTransactional": true}}}, + "request": {"method": "POST", "path": "subscriptions/manage", "body": {"email": "jane@example.com", "phone": "+79990000000", "external_id": "u-1", "loyalty_id": "l-1", "telegram_id": "t-1", "email_bulk": true, "sms_chain": false, "wallet_transactional": true}} + }, + { + "name": "manage: все 24 флага", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"emailBulk": true, "emailChain": true, "emailTransactional": true, "smsBulk": true, "smsChain": true, "smsTransactional": true, "webPushBulk": true, "webPushChain": true, "webPushTransactional": true, "mobilePushBulk": true, "mobilePushChain": true, "mobilePushTransactional": true, "telegramBulk": true, "telegramChain": true, "telegramTransactional": true, "whatsappBulk": true, "whatsappChain": true, "whatsappTransactional": true, "maxBulk": true, "maxChain": true, "maxTransactional": true, "walletBulk": true, "walletChain": true, "walletTransactional": true}}}, + "request": {"method": "POST", "path": "subscriptions/manage", "body": {"email_bulk": true, "email_chain": true, "email_transactional": true, "sms_bulk": true, "sms_chain": true, "sms_transactional": true, "web_push_bulk": true, "web_push_chain": true, "web_push_transactional": true, "mobile_push_bulk": true, "mobile_push_chain": true, "mobile_push_transactional": true, "telegram_bulk": true, "telegram_chain": true, "telegram_transactional": true, "whatsapp_bulk": true, "whatsapp_chain": true, "whatsapp_transactional": true, "max_bulk": true, "max_chain": true, "max_transactional": true, "wallet_bulk": true, "wallet_chain": true, "wallet_transactional": true}} + }, + { + "name": "manage без флагов", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"email": "jane@example.com"}}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "manage с пустым email", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"email": "", "emailBulk": true}}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "check", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "request": {"method": "GET", "path": "subscriptions/check", "query": {}} + }, + { + "name": "subscribeForPriceDrop: товар полем item_id, цена полем price", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "37", "currentPrice": 4990.5, "email": "jane@example.com"}}, + "request": {"method": "POST", "path": "subscriptions/subscribe_for_product_price", "body": {"item_id": "37", "price": 4990.5, "email": "jane@example.com"}} + }, + { + "name": "subscribeForPriceDrop с пустым itemId", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "", "currentPrice": 4990}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "subscribeForPriceDrop с ценой 0", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "37", "currentPrice": 0}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "subscribeForPriceDrop с пустым phone", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "37", "currentPrice": 4990, "phone": ""}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "unsubscribeFromPriceDrop: item_ids строкой через запятую без пробелов", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromPriceDrop", "args": {"itemIds": ["37", "38"], "phone": "+79990000000"}}, + "request": {"method": "POST", "path": "subscriptions/unsubscribe_from_product_price", "body": {"item_ids": "37,38", "phone": "+79990000000"}} + }, + { + "name": "unsubscribeFromPriceDrop: пустой список — от всех товаров", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromPriceDrop", "args": {"itemIds": []}}, + "request": {"method": "POST", "path": "subscriptions/unsubscribe_from_product_price", "body": {"item_ids": ""}} + }, + { + "name": "unsubscribeFromPriceDrop: пустая строка в списке", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromPriceDrop", "args": {"itemIds": ["37", ""]}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "subscribeForBackInStock со свойствами варианта", + "call": {"namespace": "subscriptions", "method": "subscribeForBackInStock", "args": {"itemId": "37", "properties": {"fashionSize": "42", "fashionColor": "red", "barcode": "4600000000000"}, "phone": "+79990000000"}}, + "request": {"method": "POST", "path": "subscriptions/subscribe_for_product_available", "body": {"item_id": "37", "properties": {"fashion_size": "42", "fashion_color": "red", "barcode": "4600000000000"}, "phone": "+79990000000"}} + }, + { + "name": "subscribeForBackInStock: свойства без полей не уходят", + "call": {"namespace": "subscriptions", "method": "subscribeForBackInStock", "args": {"itemId": "37", "properties": {}}}, + "request": {"method": "POST", "path": "subscriptions/subscribe_for_product_available", "body": {"item_id": "37"}} + }, + { + "name": "subscribeForBackInStock с пустым itemId", + "call": {"namespace": "subscriptions", "method": "subscribeForBackInStock", "args": {"itemId": ""}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "unsubscribeFromBackInStock", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromBackInStock", "args": {"itemIds": ["37"], "email": "jane@example.com"}}, + "request": {"method": "POST", "path": "subscriptions/unsubscribe_from_product_available", "body": {"item_ids": "37", "email": "jane@example.com"}} + }, + { + "name": "unsubscribeFromBackInStock: пустая строка в списке", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromBackInStock", "args": {"itemIds": [""]}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "check: все 24 флага, пуш-токены и состояние email; незнакомые поля не мешают", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 200, "body": {"exists": true, "email_bulk": true, "email_chain": false, "email_transactional": false, "sms_bulk": true, "sms_chain": false, "sms_transactional": false, "web_push_bulk": true, "web_push_chain": false, "web_push_transactional": false, "mobile_push_bulk": true, "mobile_push_chain": false, "mobile_push_transactional": false, "telegram_bulk": true, "telegram_chain": false, "telegram_transactional": false, "whatsapp_bulk": true, "whatsapp_chain": false, "whatsapp_transactional": false, "max_bulk": true, "max_chain": false, "max_transactional": false, "wallet_bulk": true, "wallet_chain": false, "wallet_transactional": false, "web_push": false, "mobile_push": true, "email_invalid": false, "email_blacklisted": false, "email_bounced": false, "email_suppressed": false, "email_confirmed": true, "unknown_flag": true}}, + "expect": {"result": {"exists": true, "emailBulk": true, "emailChain": false, "emailTransactional": false, "smsBulk": true, "smsChain": false, "smsTransactional": false, "webPushBulk": true, "webPushChain": false, "webPushTransactional": false, "mobilePushBulk": true, "mobilePushChain": false, "mobilePushTransactional": false, "telegramBulk": true, "telegramChain": false, "telegramTransactional": false, "whatsappBulk": true, "whatsappChain": false, "whatsappTransactional": false, "maxBulk": true, "maxChain": false, "maxTransactional": false, "walletBulk": true, "walletChain": false, "walletTransactional": false, "hasWebPush": false, "hasMobilePush": true, "emailInvalid": false, "emailBlacklisted": false, "emailBounced": false, "emailSuppressed": false, "emailConfirmed": true}} + }, + { + "name": "check: нет поля — false; логическое строкой и числом", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 200, "body": {"exists": "1", "email_bulk": "true", "sms_bulk": 1}}, + "expect": {"result": {"exists": true, "emailBulk": true, "emailChain": false, "emailTransactional": false, "smsBulk": true, "smsChain": false, "smsTransactional": false, "webPushBulk": false, "webPushChain": false, "webPushTransactional": false, "mobilePushBulk": false, "mobilePushChain": false, "mobilePushTransactional": false, "telegramBulk": false, "telegramChain": false, "telegramTransactional": false, "whatsappBulk": false, "whatsappChain": false, "whatsappTransactional": false, "maxBulk": false, "maxChain": false, "maxTransactional": false, "walletBulk": false, "walletChain": false, "walletTransactional": false, "hasWebPush": false, "hasMobilePush": false, "emailInvalid": false, "emailBlacklisted": false, "emailBounced": false, "emailSuppressed": false, "emailConfirmed": false}} + }, + { + "name": "check: пустой ответ — всё false", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 200, "body": {}}, + "expect": {"result": {"exists": false, "emailBulk": false, "emailChain": false, "emailTransactional": false, "smsBulk": false, "smsChain": false, "smsTransactional": false, "webPushBulk": false, "webPushChain": false, "webPushTransactional": false, "mobilePushBulk": false, "mobilePushChain": false, "mobilePushTransactional": false, "telegramBulk": false, "telegramChain": false, "telegramTransactional": false, "whatsappBulk": false, "whatsappChain": false, "whatsappTransactional": false, "maxBulk": false, "maxChain": false, "maxTransactional": false, "walletBulk": false, "walletChain": false, "walletTransactional": false, "hasWebPush": false, "hasMobilePush": false, "emailInvalid": false, "emailBlacklisted": false, "emailBounced": false, "emailSuppressed": false, "emailConfirmed": false}} + }, + { + "name": "check: 400 — неизвестный did", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 400, "body": {"status": "error", "message": "Client not found"}}, + "expect": {"error": {"type": "http", "code": 400}} + }, + { + "name": "check: ответ не объект", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 200, "body": []}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "manage: успех", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"emailBulk": true}}}, + "response": {"status": 200, "body": {"status": "success"}}, + "expect": {"result": null} + }, + { + "name": "subscribeForBackInStock: 400 — свойство не из списка сервера", + "call": {"namespace": "subscriptions", "method": "subscribeForBackInStock", "args": {"itemId": "37", "properties": {"fashionSize": "42"}}}, + "response": {"status": 400, "body": {"status": "error", "message": "Incorrect product property"}}, + "expect": {"error": {"type": "http", "code": 400}} + }, + { + "name": "unsubscribeFromPriceDrop: 2xx со status error", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromPriceDrop", "args": {"itemIds": ["37"]}}, + "response": {"status": 200, "body": {"status": "error", "message": "Something went wrong"}}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "subscribeForPriceDrop: нет ответа", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "37", "currentPrice": 4990}}, + "response": {"status": null}, + "expect": {"error": {"type": "network"}} + } + ] +}