From a5995744627dde6b58a4591475d5873154cc2587 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Thu, 27 Aug 2026 23:51:22 +0400 Subject: [PATCH 1/9] chore(deps): point the plugin at the local native DEV-4409 branches The tracking namespace lands in the native SDKs first and is not released yet, so while it is being bridged the plugin resolves both natives from the sibling checkouts: - Android via mavenLocal, published from android-sdk with `./gradlew :personalization-sdk:publishRees46ReleaseLibraryPublicationToMavenLocal` as `com.personalization:personalization-sdk:2.36.0`; - iOS via a `:path` pod pointing at the ios-sdk checkout. Both are marked LOCAL WIRING in place and revert to the JitPack coordinate and the podspec dependency once the native release ships. --- android/build.gradle.kts | 21 ++++++++++++++++----- example/android/build.gradle.kts | 2 ++ example/ios/Podfile | 5 +++++ example/ios/Podfile.lock | 12 ++++++++++-- 4 files changed, 33 insertions(+), 7 deletions(-) diff --git a/android/build.gradle.kts b/android/build.gradle.kts index 6a9cde6..848a335 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -4,6 +4,10 @@ version = "1.0-SNAPSHOT" buildscript { val kotlinVersion = "2.2.20" repositories { + // LOCAL WIRING (DEV-4409): the native SDK is built from the sibling + // DEV-4409-standart-tracking-metod-unification branch and published to mavenLocal. + // Revert to JitPack coordinates once the native release ships. + mavenLocal() google() mavenCentral() maven(url = "https://jitpack.io") @@ -17,6 +21,10 @@ buildscript { allprojects { repositories { + // LOCAL WIRING (DEV-4409): the native SDK is built from the sibling + // DEV-4409-standart-tracking-metod-unification branch and published to mavenLocal. + // Revert to JitPack coordinates once the native release ships. + mavenLocal() google() mavenCentral() maven(url = "https://jitpack.io") @@ -86,13 +94,16 @@ android { } dependencies { - // REES46 Android SDK (JitPack). - // Published from github.com/rees46/android-sdk as `com.github.rees46:android-sdk:`. - // v2.36.0 is the first tag that ships the multi-instance `Rees46` facade. - val rees46AndroidSdkVersion = "v2.36.0" + // REES46 Android SDK. + // LOCAL WIRING (DEV-4409): built from the sibling android-sdk checkout on branch + // DEV-4409-standart-tracking-metod-unification and published with + // `./gradlew :personalization-sdk:publishRees46ReleaseLibraryPublicationToMavenLocal`. + // Revert to the JitPack coordinate below once the native release ships: + // val rees46AndroidSdkVersion = "v2.36.0" + // add("rees46Implementation", "com.github.rees46:android-sdk:$rees46AndroidSdkVersion") add( "rees46Implementation", - "com.github.rees46:android-sdk:$rees46AndroidSdkVersion", + "com.personalization:personalization-sdk:2.36.0", ) // Used directly by the push presenter (NotificationCompat / ContextCompat). The native SDK diff --git a/example/android/build.gradle.kts b/example/android/build.gradle.kts index eeea458..c305684 100644 --- a/example/android/build.gradle.kts +++ b/example/android/build.gradle.kts @@ -1,5 +1,7 @@ allprojects { repositories { + // LOCAL WIRING (DEV-4409) — see android/build.gradle.kts. Remove with it. + mavenLocal() google() mavenCentral() maven(url = "https://jitpack.io") diff --git a/example/ios/Podfile b/example/ios/Podfile index 5612959..63edfd1 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -30,6 +30,11 @@ flutter_ios_podfile_setup target 'Runner' do use_frameworks! + # LOCAL WIRING (DEV-4409): the native pod is taken from the sibling ios-sdk checkout on branch + # DEV-4409-standart-tracking-metod-unification. Remove this line once the release ships — the + # pod normally comes from the plugin podspec's dependency. + pod 'REES46', :path => '/Users/andreykropotov/Documents/FlutterProjects/ios-sdk' + target 'RunnerUITests' do inherit! :complete end diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index c6eca3c..cf6adee 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -1,6 +1,8 @@ PODS: - CocoaAsyncSocket (7.6.5) - Flutter (1.0.0) + - integration_test (0.0.1): + - Flutter - patrol (0.0.1): - CocoaAsyncSocket (~> 7.6) - Flutter @@ -12,29 +14,35 @@ PODS: DEPENDENCIES: - Flutter (from `Flutter`) + - integration_test (from `.symlinks/plugins/integration_test/ios`) - patrol (from `.symlinks/plugins/patrol/darwin`) + - REES46 (from `/Users/andreykropotov/Documents/FlutterProjects/ios-sdk`) - rees46_sdk (from `.symlinks/plugins/rees46_sdk/ios`) SPEC REPOS: trunk: - CocoaAsyncSocket - - REES46 EXTERNAL SOURCES: Flutter: :path: Flutter + integration_test: + :path: ".symlinks/plugins/integration_test/ios" patrol: :path: ".symlinks/plugins/patrol/darwin" + REES46: + :path: "/Users/andreykropotov/Documents/FlutterProjects/ios-sdk" rees46_sdk: :path: ".symlinks/plugins/rees46_sdk/ios" SPEC CHECKSUMS: CocoaAsyncSocket: 065fd1e645c7abab64f7a6a2007a48038fdc6a99 Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 + integration_test: 4a889634ef21a45d28d50d622cf412dc6d9f586e patrol: cea8074f183a2a4232d0ebd10569ae05149ada42 REES46: e99e94c2ae031e62b6dd62c81a0d0db37659a48c rees46_sdk: 5677cdb063f6ed6f1fd7cfafe3cd209a47313c7c -PODFILE CHECKSUM: b6e248ac4c1eff5807c8b044b39b8bc326af3f5f +PODFILE CHECKSUM: 060e5d67fb40e2ac65b0b9bf93fba35390ac423b COCOAPODS: 1.16.2 From cae82df104f584be850487950eec27a39bb6e79e Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 28 Aug 2026 10:08:52 +0400 Subject: [PATCH 2/9] feat(tracking): bridge the standard events to the tracking namespace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Flutter had no standard tracking events at all — only a custom event and a purchase. They arrive now as `sdk.tracking.*`, the same namespace and the same method names the native SDKs expose: product and category view, search, cart and favorites (single and full sync), story view and click, purchase, custom event and attribution. Typed models rather than maps: `TrackingItem`, `TrackingSource` and `TrackingSourceType`, whose `dynamicBlock` carries the wire value `dynamic`, which cannot name a Dart enum member. Arguments are validated in Dart, before the channel call. Each method has its own Pigeon method and both bridges hand straight to the native `tracking` namespace, so an event fired from Dart is the request the native SDKs send — no JSON assembled in the plugin. `PersonalizationSdk.trackEvent` and `trackPurchase` are deprecated in favour of `tracking.custom` and `tracking.purchase` and keep working. One divergence to settle before release: the iOS `RecommendedByCase` has no `stories` case, so a story-attributed source is dropped by the iOS bridge. --- .../Rees46FlutterSdkPlugin.kt | 146 +++++++ .../pigeon/PersonalizationApi.g.kt | 360 ++++++++++++++++ ios/Classes/Rees46FlutterSdkPlugin.swift | 187 +++++++++ ios/Classes/pigeon/PersonalizationApi.g.swift | 322 ++++++++++++++ lib/rees46_sdk.dart | 2 + lib/src/personalization_sdk.dart | 8 + lib/src/pigeon/personalization_api.g.dart | 397 ++++++++++++++++++ lib/src/tracking/tracking_api.dart | 212 ++++++++++ lib/src/tracking/tracking_models.dart | 46 ++ pigeons/personalization_api.dart | 69 +++ 10 files changed, 1749 insertions(+) create mode 100644 lib/src/tracking/tracking_api.dart create mode 100644 lib/src/tracking/tracking_models.dart diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/Rees46FlutterSdkPlugin.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/Rees46FlutterSdkPlugin.kt index 6935ca9..99a169c 100644 --- a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/Rees46FlutterSdkPlugin.kt +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/Rees46FlutterSdkPlugin.kt @@ -10,6 +10,8 @@ import com.rees46.rees46_flutter_sdk.pigeon.PersonalizationFlutterApi import com.rees46.rees46_flutter_sdk.pigeon.PersonalizationHostApi import com.rees46.rees46_flutter_sdk.pigeon.ProfileParamsWire import com.rees46.rees46_flutter_sdk.pigeon.PurchaseLineItemWire +import com.rees46.rees46_flutter_sdk.pigeon.TrackingItemWire +import com.rees46.rees46_flutter_sdk.pigeon.TrackingSourceWire import com.google.gson.Gson import com.personalization.Params import com.personalization.PushEventType @@ -18,6 +20,10 @@ import com.personalization.Rees46 import com.personalization.Rees46Config import com.personalization.SDK import com.personalization.api.OnApiCallbackListener +import com.personalization.api.managers.TrackingApi +import com.personalization.api.models.tracking.TrackingItem +import com.personalization.api.models.tracking.TrackingSource +import com.personalization.api.models.tracking.TrackingSourceType import com.personalization.api.params.ProfileParams import com.personalization.api.params.SearchParams as NativeSearchParams import com.personalization.sdk.data.models.dto.notification.NotificationData @@ -509,6 +515,146 @@ class Rees46FlutterSdkPlugin : } } + // region tracking namespace + // + // Each method hands straight to the native `tracking` namespace of the resolved instance; + // the wire models are translated one to one. + + override fun trackProductView( + itemId: String, + source: TrackingSourceWire?, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { + it.productView(itemId, source.toNative(), trackingListener(callback)) + } + + override fun trackCategoryView( + categoryId: String, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { it.categoryView(categoryId, trackingListener(callback)) } + + override fun trackSearch( + query: String, + results: List?, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { it.search(query, results, trackingListener(callback)) } + + override fun trackAddToCart( + item: TrackingItemWire, + source: TrackingSourceWire?, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { + it.addToCart(item.toNative(), source.toNative(), trackingListener(callback)) + } + + override fun trackSyncCart( + items: List, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { + it.syncCart(items.map { item -> item.toNative() }, trackingListener(callback)) + } + + override fun trackRemoveFromCart( + itemId: String, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { it.removeFromCart(itemId, trackingListener(callback)) } + + override fun trackAddToFavorites( + itemId: String, + source: TrackingSourceWire?, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { + it.addToFavorites(itemId, source.toNative(), trackingListener(callback)) + } + + override fun trackSyncFavorites( + itemIds: List, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { it.syncFavorites(itemIds, trackingListener(callback)) } + + override fun trackRemoveFromFavorites( + itemId: String, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { + it.removeFromFavorites(itemId, trackingListener(callback)) + } + + override fun trackStoryView( + storyId: String, + slideId: String, + code: String?, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { + it.storyView(storyId, slideId, code, trackingListener(callback)) + } + + override fun trackStoryClick( + storyId: String, + slideId: String, + code: String?, + shopId: String?, + callback: (Result) -> Unit, + ) = trackingCall(callback, shopId) { + it.storyClick(storyId, slideId, code, trackingListener(callback)) + } + + override fun trackSetSource(source: TrackingSourceWire, shopId: String?) { + val native = source.toNative() + ?: throw FlutterError("bad_args", "unknown source type: ${source.type}", null) + sdk(shopId).tracking.setSource(native) + } + + /** Resolves the instance, reports a resolution failure through [callback], then tracks. */ + private fun trackingCall( + callback: (Result) -> Unit, + shopId: String?, + body: (TrackingApi) -> Unit, + ) { + try { + body(sdk(shopId).tracking) + } catch (t: Throwable) { + callback(Result.failure(FlutterError("track_failed", t.message, null))) + } + } + + private fun trackingListener(callback: (Result) -> Unit) = + object : OnApiCallbackListener() { + override fun onSuccess(response: JSONObject?) { + callback(Result.success(Unit)) + } + + override fun onError(code: Int, msg: String?) { + val message = listOfNotNull(code.toString(), msg).joinToString(": ") + callback(Result.failure(FlutterError("track_failed", message, null))) + } + } + + private fun TrackingItemWire.toNative(): TrackingItem = TrackingItem( + id = id, + quantity = quantity.toInt(), + price = price, + fashionSize = fashionSize, + ) + + /** An unknown source type is dropped rather than guessed — Dart only sends known values. */ + private fun TrackingSourceWire?.toNative(): TrackingSource? { + val wire = this ?: return null + val type = TrackingSourceType.entries.firstOrNull { it.value == wire.type } ?: return null + return TrackingSource(type = type, code = wire.code) + } + + // endregion + override fun trackEvent( event: String, time: Long?, diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/pigeon/PersonalizationApi.g.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/pigeon/PersonalizationApi.g.kt index c1eb6d9..ada9154 100644 --- a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/pigeon/PersonalizationApi.g.kt +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/pigeon/PersonalizationApi.g.kt @@ -269,6 +269,88 @@ data class ProfileParamsWire ( override fun hashCode(): Int = toList().hashCode() } + +/** + * Wire format for one product line in a tracking event (maps to native `TrackingItem`). + * + * [quantity] is the domain name for the line quantity; native sends it as `amount`. + * + * Generated class from Pigeon that represents data sent in messages. + */ +data class TrackingItemWire ( + val id: String, + val quantity: Long, + val price: Double? = null, + val fashionSize: String? = null +) + { + companion object { + fun fromList(pigeonVar_list: List): TrackingItemWire { + val id = pigeonVar_list[0] as String + val quantity = pigeonVar_list[1] as Long + val price = pigeonVar_list[2] as Double? + val fashionSize = pigeonVar_list[3] as String? + return TrackingItemWire(id, quantity, price, fashionSize) + } + } + fun toList(): List { + return listOf( + id, + quantity, + price, + fashionSize, + ) + } + override fun equals(other: Any?): Boolean { + if (other !is TrackingItemWire) { + return false + } + if (this === other) { + return true + } + return PersonalizationApiPigeonUtils.deepEquals(toList(), other.toList()) } + + override fun hashCode(): Int = toList().hashCode() +} + +/** + * Wire format for event attribution (maps to native `TrackingSource`). + * + * [type] is the wire value of the source type — `dynamic`, `chain`, `bulk`, + * `transactional`, `instant_search`, `full_search`, `stories`. Dart only ever sends what its + * `TrackingSourceType` enum produces; the bridges reject anything else. + * + * Generated class from Pigeon that represents data sent in messages. + */ +data class TrackingSourceWire ( + val type: String, + val code: String +) + { + companion object { + fun fromList(pigeonVar_list: List): TrackingSourceWire { + val type = pigeonVar_list[0] as String + val code = pigeonVar_list[1] as String + return TrackingSourceWire(type, code) + } + } + fun toList(): List { + return listOf( + type, + code, + ) + } + override fun equals(other: Any?): Boolean { + if (other !is TrackingSourceWire) { + return false + } + if (this === other) { + return true + } + return PersonalizationApiPigeonUtils.deepEquals(toList(), other.toList()) } + + override fun hashCode(): Int = toList().hashCode() +} private open class PersonalizationApiPigeonCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { @@ -287,6 +369,16 @@ private open class PersonalizationApiPigeonCodec : StandardMessageCodec() { ProfileParamsWire.fromList(it) } } + 132.toByte() -> { + return (readValue(buffer) as? List)?.let { + TrackingItemWire.fromList(it) + } + } + 133.toByte() -> { + return (readValue(buffer) as? List)?.let { + TrackingSourceWire.fromList(it) + } + } else -> super.readValueOfType(type, buffer) } } @@ -304,6 +396,14 @@ private open class PersonalizationApiPigeonCodec : StandardMessageCodec() { stream.write(131) writeValue(stream, value.toList()) } + is TrackingItemWire -> { + stream.write(132) + writeValue(stream, value.toList()) + } + is TrackingSourceWire -> { + stream.write(133) + writeValue(stream, value.toList()) + } else -> super.writeValue(stream, value) } } @@ -400,6 +500,19 @@ interface PersonalizationHostApi { * maps it to its own vocabulary (Android `PushEventType`, iOS `PushEvent`). */ fun handlePush(payload: Map, event: Long, callback: (Result) -> Unit) + fun trackProductView(itemId: String, source: TrackingSourceWire?, shopId: String?, callback: (Result) -> Unit) + fun trackCategoryView(categoryId: String, shopId: String?, callback: (Result) -> Unit) + fun trackSearch(query: String, results: List?, shopId: String?, callback: (Result) -> Unit) + fun trackAddToCart(item: TrackingItemWire, source: TrackingSourceWire?, shopId: String?, callback: (Result) -> Unit) + fun trackSyncCart(items: List, shopId: String?, callback: (Result) -> Unit) + fun trackRemoveFromCart(itemId: String, shopId: String?, callback: (Result) -> Unit) + fun trackAddToFavorites(itemId: String, source: TrackingSourceWire?, shopId: String?, callback: (Result) -> Unit) + fun trackSyncFavorites(itemIds: List, shopId: String?, callback: (Result) -> Unit) + fun trackRemoveFromFavorites(itemId: String, shopId: String?, callback: (Result) -> Unit) + fun trackStoryView(storyId: String, slideId: String, code: String?, shopId: String?, callback: (Result) -> Unit) + fun trackStoryClick(storyId: String, slideId: String, code: String?, shopId: String?, callback: (Result) -> Unit) + /** Stores the attribution source natively for the next event. */ + fun trackSetSource(source: TrackingSourceWire, shopId: String?) /** [customJson] and [recommendedSourceJson] are JSON object strings or null. */ fun trackPurchase(orderId: String, orderPrice: Double, items: List, deliveryType: String?, deliveryAddress: String?, paymentType: String?, isTaxFree: Boolean, promocode: String?, orderCash: Double?, orderBonuses: Double?, orderDelivery: Double?, orderDiscount: Double?, channel: String?, customJson: String?, recommendedSourceJson: String?, stream: String?, segment: String?, shopId: String?, callback: (Result) -> Unit) @@ -820,6 +933,253 @@ interface PersonalizationHostApi { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackProductView$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val itemIdArg = args[0] as String + val sourceArg = args[1] as TrackingSourceWire? + val shopIdArg = args[2] as String? + api.trackProductView(itemIdArg, sourceArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackCategoryView$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val categoryIdArg = args[0] as String + val shopIdArg = args[1] as String? + api.trackCategoryView(categoryIdArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSearch$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val queryArg = args[0] as String + val resultsArg = args[1] as List? + val shopIdArg = args[2] as String? + api.trackSearch(queryArg, resultsArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToCart$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val itemArg = args[0] as TrackingItemWire + val sourceArg = args[1] as TrackingSourceWire? + val shopIdArg = args[2] as String? + api.trackAddToCart(itemArg, sourceArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncCart$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val itemsArg = args[0] as List + val shopIdArg = args[1] as String? + api.trackSyncCart(itemsArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromCart$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val itemIdArg = args[0] as String + val shopIdArg = args[1] as String? + api.trackRemoveFromCart(itemIdArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToFavorites$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val itemIdArg = args[0] as String + val sourceArg = args[1] as TrackingSourceWire? + val shopIdArg = args[2] as String? + api.trackAddToFavorites(itemIdArg, sourceArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncFavorites$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val itemIdsArg = args[0] as List + val shopIdArg = args[1] as String? + api.trackSyncFavorites(itemIdsArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromFavorites$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val itemIdArg = args[0] as String + val shopIdArg = args[1] as String? + api.trackRemoveFromFavorites(itemIdArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryView$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val storyIdArg = args[0] as String + val slideIdArg = args[1] as String + val codeArg = args[2] as String? + val shopIdArg = args[3] as String? + api.trackStoryView(storyIdArg, slideIdArg, codeArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryClick$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val storyIdArg = args[0] as String + val slideIdArg = args[1] as String + val codeArg = args[2] as String? + val shopIdArg = args[3] as String? + api.trackStoryClick(storyIdArg, slideIdArg, codeArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSetSource$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val sourceArg = args[0] as TrackingSourceWire + val shopIdArg = args[1] as String? + val wrapped: List = try { + api.trackSetSource(sourceArg, shopIdArg) + listOf(null) + } catch (exception: Throwable) { + PersonalizationApiPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPurchase$separatedMessageChannelSuffix", codec) if (api != null) { diff --git a/ios/Classes/Rees46FlutterSdkPlugin.swift b/ios/Classes/Rees46FlutterSdkPlugin.swift index 9682ff5..cd4b3c8 100644 --- a/ios/Classes/Rees46FlutterSdkPlugin.swift +++ b/ios/Classes/Rees46FlutterSdkPlugin.swift @@ -844,6 +844,173 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { } } + // MARK: - Tracking namespace + // + // Each method hands straight to the native `tracking` namespace of the resolved instance; + // the wire models are translated one to one. + + func trackProductView( + itemId: String, + source: TrackingSourceWire?, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.productView(id: itemId, source: source?.native) { self.report($0, completion) } + } + } + + func trackCategoryView( + categoryId: String, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.categoryView(id: categoryId) { self.report($0, completion) } + } + } + + func trackSearch( + query: String, + results: [String]?, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.search(query: query, results: results) { self.report($0, completion) } + } + } + + func trackAddToCart( + item: TrackingItemWire, + source: TrackingSourceWire?, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.addToCart(item: item.native, source: source?.native) { self.report($0, completion) } + } + } + + func trackSyncCart( + items: [TrackingItemWire], + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.syncCart(items: items.map { $0.native }) { self.report($0, completion) } + } + } + + func trackRemoveFromCart( + itemId: String, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.removeFromCart(id: itemId) { self.report($0, completion) } + } + } + + func trackAddToFavorites( + itemId: String, + source: TrackingSourceWire?, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.addToFavorites(id: itemId, source: source?.native) { self.report($0, completion) } + } + } + + func trackSyncFavorites( + itemIds: [String], + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.syncFavorites(ids: itemIds) { self.report($0, completion) } + } + } + + func trackRemoveFromFavorites( + itemId: String, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.removeFromFavorites(id: itemId) { self.report($0, completion) } + } + } + + func trackStoryView( + storyId: String, + slideId: String, + code: String?, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.storyView(storyId: storyId, slideId: slideId, code: code) { + self.report($0, completion) + } + } + } + + func trackStoryClick( + storyId: String, + slideId: String, + code: String?, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + withTracking(shopId, completion) { tracking in + tracking.storyClick(storyId: storyId, slideId: slideId, code: code) { + self.report($0, completion) + } + } + } + + func trackSetSource(source: TrackingSourceWire, shopId: String?) throws { + guard let sdk = sdk(shopId) else { + throw PigeonError(code: "not_initialized", message: "SDK is not initialized", details: nil) + } + guard let native = source.native else { + throw PigeonError( + code: "bad_args", message: "unknown source type: \(source.type)", details: nil) + } + sdk.tracking.setSource(native) + } + + /// Resolves the instance, reports a resolution failure through `completion`, then tracks. + private func withTracking( + _ shopId: String?, + _ completion: @escaping (Result) -> Void, + _ body: (TrackingAPI) -> Void + ) { + guard let sdk = sdk(shopId) else { + completion( + .failure( + PigeonError(code: "not_initialized", message: "SDK is not initialized", details: nil))) + return + } + body(sdk.tracking) + } + + private func report( + _ result: Result, + _ completion: @escaping (Result) -> Void + ) { + switch result { + case .success: + completion(.success(())) + case .failure(let error): + completion( + .failure( + PigeonError(code: "track_failed", message: "\(error)", details: nil))) + } + } + func trackEvent( event: String, time: Int64?, @@ -995,3 +1162,23 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { return obj as? [String: Any] } } + +extension TrackingItemWire { + var native: TrackingItem { + TrackingItem( + id: id, + quantity: Int(quantity), + price: price, + fashionSize: fashionSize + ) + } +} + +extension TrackingSourceWire { + /// An unknown source type is dropped rather than guessed — Dart only sends known values. + /// `stories` has no case in the iOS `RecommendedByCase`, so a story source is dropped here. + var native: TrackingSource? { + guard let type = RecommendedByCase(rawValue: type) else { return nil } + return TrackingSource(type: type, code: code) + } +} diff --git a/ios/Classes/pigeon/PersonalizationApi.g.swift b/ios/Classes/pigeon/PersonalizationApi.g.swift index 34c43b3..ed45519 100644 --- a/ios/Classes/pigeon/PersonalizationApi.g.swift +++ b/ios/Classes/pigeon/PersonalizationApi.g.swift @@ -338,6 +338,82 @@ struct ProfileParamsWire: Hashable { } } +/// Wire format for one product line in a tracking event (maps to native `TrackingItem`). +/// +/// [quantity] is the domain name for the line quantity; native sends it as `amount`. +/// +/// Generated class from Pigeon that represents data sent in messages. +struct TrackingItemWire: Hashable { + var id: String + var quantity: Int64 + var price: Double? = nil + var fashionSize: String? = nil + + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> TrackingItemWire? { + let id = pigeonVar_list[0] as! String + let quantity = pigeonVar_list[1] as! Int64 + let price: Double? = nilOrValue(pigeonVar_list[2]) + let fashionSize: String? = nilOrValue(pigeonVar_list[3]) + + return TrackingItemWire( + id: id, + quantity: quantity, + price: price, + fashionSize: fashionSize + ) + } + func toList() -> [Any?] { + return [ + id, + quantity, + price, + fashionSize, + ] + } + static func == (lhs: TrackingItemWire, rhs: TrackingItemWire) -> Bool { + return deepEqualsPersonalizationApi(lhs.toList(), rhs.toList()) } + func hash(into hasher: inout Hasher) { + deepHashPersonalizationApi(value: toList(), hasher: &hasher) + } +} + +/// Wire format for event attribution (maps to native `TrackingSource`). +/// +/// [type] is the wire value of the source type — `dynamic`, `chain`, `bulk`, +/// `transactional`, `instant_search`, `full_search`, `stories`. Dart only ever sends what its +/// `TrackingSourceType` enum produces; the bridges reject anything else. +/// +/// Generated class from Pigeon that represents data sent in messages. +struct TrackingSourceWire: Hashable { + var type: String + var code: String + + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> TrackingSourceWire? { + let type = pigeonVar_list[0] as! String + let code = pigeonVar_list[1] as! String + + return TrackingSourceWire( + type: type, + code: code + ) + } + func toList() -> [Any?] { + return [ + type, + code, + ] + } + static func == (lhs: TrackingSourceWire, rhs: TrackingSourceWire) -> Bool { + return deepEqualsPersonalizationApi(lhs.toList(), rhs.toList()) } + func hash(into hasher: inout Hasher) { + deepHashPersonalizationApi(value: toList(), hasher: &hasher) + } +} + private class PersonalizationApiPigeonCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { @@ -347,6 +423,10 @@ private class PersonalizationApiPigeonCodecReader: FlutterStandardReader { return PurchaseLineItemWire.fromList(self.readValue() as! [Any?]) case 131: return ProfileParamsWire.fromList(self.readValue() as! [Any?]) + case 132: + return TrackingItemWire.fromList(self.readValue() as! [Any?]) + case 133: + return TrackingSourceWire.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } @@ -364,6 +444,12 @@ private class PersonalizationApiPigeonCodecWriter: FlutterStandardWriter { } else if let value = value as? ProfileParamsWire { super.writeByte(131) super.writeValue(value.toList()) + } else if let value = value as? TrackingItemWire { + super.writeByte(132) + super.writeValue(value.toList()) + } else if let value = value as? TrackingSourceWire { + super.writeByte(133) + super.writeValue(value.toList()) } else { super.writeValue(value) } @@ -449,6 +535,19 @@ protocol PersonalizationHostApi { /// `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side /// maps it to its own vocabulary (Android `PushEventType`, iOS `PushEvent`). func handlePush(payload: [String: String], event: Int64, completion: @escaping (Result) -> Void) + func trackProductView(itemId: String, source: TrackingSourceWire?, shopId: String?, completion: @escaping (Result) -> Void) + func trackCategoryView(categoryId: String, shopId: String?, completion: @escaping (Result) -> Void) + func trackSearch(query: String, results: [String]?, shopId: String?, completion: @escaping (Result) -> Void) + func trackAddToCart(item: TrackingItemWire, source: TrackingSourceWire?, shopId: String?, completion: @escaping (Result) -> Void) + func trackSyncCart(items: [TrackingItemWire], shopId: String?, completion: @escaping (Result) -> Void) + func trackRemoveFromCart(itemId: String, shopId: String?, completion: @escaping (Result) -> Void) + func trackAddToFavorites(itemId: String, source: TrackingSourceWire?, shopId: String?, completion: @escaping (Result) -> Void) + func trackSyncFavorites(itemIds: [String], shopId: String?, completion: @escaping (Result) -> Void) + func trackRemoveFromFavorites(itemId: String, shopId: String?, completion: @escaping (Result) -> Void) + func trackStoryView(storyId: String, slideId: String, code: String?, shopId: String?, completion: @escaping (Result) -> Void) + func trackStoryClick(storyId: String, slideId: String, code: String?, shopId: String?, completion: @escaping (Result) -> Void) + /// Stores the attribution source natively for the next event. + func trackSetSource(source: TrackingSourceWire, shopId: String?) throws /// [customJson] and [recommendedSourceJson] are JSON object strings or null. func trackPurchase(orderId: String, orderPrice: Double, items: [PurchaseLineItemWire], deliveryType: String?, deliveryAddress: String?, paymentType: String?, isTaxFree: Bool, promocode: String?, orderCash: Double?, orderBonuses: Double?, orderDelivery: Double?, orderDiscount: Double?, channel: String?, customJson: String?, recommendedSourceJson: String?, stream: String?, segment: String?, shopId: String?, completion: @escaping (Result) -> Void) } @@ -857,6 +956,229 @@ class PersonalizationHostApiSetup { } else { handlePushChannel.setMessageHandler(nil) } + let trackProductViewChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackProductView\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackProductViewChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let itemIdArg = args[0] as! String + let sourceArg: TrackingSourceWire? = nilOrValue(args[1]) + let shopIdArg: String? = nilOrValue(args[2]) + api.trackProductView(itemId: itemIdArg, source: sourceArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackProductViewChannel.setMessageHandler(nil) + } + let trackCategoryViewChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackCategoryView\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackCategoryViewChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let categoryIdArg = args[0] as! String + let shopIdArg: String? = nilOrValue(args[1]) + api.trackCategoryView(categoryId: categoryIdArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackCategoryViewChannel.setMessageHandler(nil) + } + let trackSearchChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSearch\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackSearchChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let queryArg = args[0] as! String + let resultsArg: [String]? = nilOrValue(args[1]) + let shopIdArg: String? = nilOrValue(args[2]) + api.trackSearch(query: queryArg, results: resultsArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackSearchChannel.setMessageHandler(nil) + } + let trackAddToCartChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToCart\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackAddToCartChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let itemArg = args[0] as! TrackingItemWire + let sourceArg: TrackingSourceWire? = nilOrValue(args[1]) + let shopIdArg: String? = nilOrValue(args[2]) + api.trackAddToCart(item: itemArg, source: sourceArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackAddToCartChannel.setMessageHandler(nil) + } + let trackSyncCartChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncCart\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackSyncCartChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let itemsArg = args[0] as! [TrackingItemWire] + let shopIdArg: String? = nilOrValue(args[1]) + api.trackSyncCart(items: itemsArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackSyncCartChannel.setMessageHandler(nil) + } + let trackRemoveFromCartChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromCart\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackRemoveFromCartChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let itemIdArg = args[0] as! String + let shopIdArg: String? = nilOrValue(args[1]) + api.trackRemoveFromCart(itemId: itemIdArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackRemoveFromCartChannel.setMessageHandler(nil) + } + let trackAddToFavoritesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToFavorites\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackAddToFavoritesChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let itemIdArg = args[0] as! String + let sourceArg: TrackingSourceWire? = nilOrValue(args[1]) + let shopIdArg: String? = nilOrValue(args[2]) + api.trackAddToFavorites(itemId: itemIdArg, source: sourceArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackAddToFavoritesChannel.setMessageHandler(nil) + } + let trackSyncFavoritesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncFavorites\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackSyncFavoritesChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let itemIdsArg = args[0] as! [String] + let shopIdArg: String? = nilOrValue(args[1]) + api.trackSyncFavorites(itemIds: itemIdsArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackSyncFavoritesChannel.setMessageHandler(nil) + } + let trackRemoveFromFavoritesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromFavorites\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackRemoveFromFavoritesChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let itemIdArg = args[0] as! String + let shopIdArg: String? = nilOrValue(args[1]) + api.trackRemoveFromFavorites(itemId: itemIdArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackRemoveFromFavoritesChannel.setMessageHandler(nil) + } + let trackStoryViewChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryView\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackStoryViewChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let storyIdArg = args[0] as! String + let slideIdArg = args[1] as! String + let codeArg: String? = nilOrValue(args[2]) + let shopIdArg: String? = nilOrValue(args[3]) + api.trackStoryView(storyId: storyIdArg, slideId: slideIdArg, code: codeArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackStoryViewChannel.setMessageHandler(nil) + } + let trackStoryClickChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryClick\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackStoryClickChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let storyIdArg = args[0] as! String + let slideIdArg = args[1] as! String + let codeArg: String? = nilOrValue(args[2]) + let shopIdArg: String? = nilOrValue(args[3]) + api.trackStoryClick(storyId: storyIdArg, slideId: slideIdArg, code: codeArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackStoryClickChannel.setMessageHandler(nil) + } + /// Stores the attribution source natively for the next event. + let trackSetSourceChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSetSource\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackSetSourceChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let sourceArg = args[0] as! TrackingSourceWire + let shopIdArg: String? = nilOrValue(args[1]) + do { + try api.trackSetSource(source: sourceArg, shopId: shopIdArg) + reply(wrapResult(nil)) + } catch { + reply(wrapError(error)) + } + } + } else { + trackSetSourceChannel.setMessageHandler(nil) + } /// [customJson] and [recommendedSourceJson] are JSON object strings or null. let trackPurchaseChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPurchase\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) if let api = api { diff --git a/lib/rees46_sdk.dart b/lib/rees46_sdk.dart index 38ba4e0..6cd497a 100644 --- a/lib/rees46_sdk.dart +++ b/lib/rees46_sdk.dart @@ -17,3 +17,5 @@ export 'src/search/search_params.dart'; export 'src/search/search_response.dart'; export 'src/sdk_init_config.dart'; export 'src/tracking/purchase_line_item.dart'; +export 'src/tracking/tracking_api.dart'; +export 'src/tracking/tracking_models.dart'; diff --git a/lib/src/personalization_sdk.dart b/lib/src/personalization_sdk.dart index 4870d96..da759e4 100644 --- a/lib/src/personalization_sdk.dart +++ b/lib/src/personalization_sdk.dart @@ -19,6 +19,7 @@ import 'search/search_params.dart'; import 'search/search_response.dart'; import 'sdk_init_config.dart'; import 'tracking/purchase_line_item.dart'; +import 'tracking/tracking_api.dart'; class PersonalizationSdk { final pigeon.PersonalizationHostApi _api; @@ -31,9 +32,14 @@ class PersonalizationSdk { /// stored now so multi-instance handles carry their identity. final String? shopId; + /// Standard tracking events, grouped: `sdk.tracking.productView('sku-1')`, + /// `sdk.tracking.addToCart(item)`, and the rest. + late final TrackingApi tracking; + PersonalizationSdk({pigeon.PersonalizationHostApi? api, this.shopId}) : _api = api ?? pigeon.PersonalizationHostApi(), _initHandler = SdkInitHandler(api: api) { + tracking = TrackingApi(_api, shopId); // One process-global dispatcher owns the Pigeon push channel and routes each // inbound push (by shopId) to the right handle — register this handle's // callbacks with it instead of claiming the channel per instance. @@ -250,6 +256,7 @@ class PersonalizationSdk { } /// Custom event tracking (native `trackEvent` / `TrackEventManager.trackEvent`). + @Deprecated('Use sdk.tracking.custom(event) instead.') Future trackEvent( String event, { int? time, @@ -276,6 +283,7 @@ class PersonalizationSdk { } /// Purchase tracking (native `trackPurchase` with typed line items). + @Deprecated('Use sdk.tracking.purchase(...) instead.') Future trackPurchase({ required String orderId, required double orderPrice, diff --git a/lib/src/pigeon/personalization_api.g.dart b/lib/src/pigeon/personalization_api.g.dart index 8bfb780..1a3bdb0 100644 --- a/lib/src/pigeon/personalization_api.g.dart +++ b/lib/src/pigeon/personalization_api.g.dart @@ -321,6 +321,116 @@ class ProfileParamsWire { ; } +/// Wire format for one product line in a tracking event (maps to native `TrackingItem`). +/// +/// [quantity] is the domain name for the line quantity; native sends it as `amount`. +class TrackingItemWire { + TrackingItemWire({ + required this.id, + required this.quantity, + this.price, + this.fashionSize, + }); + + String id; + + int quantity; + + double? price; + + String? fashionSize; + + List _toList() { + return [ + id, + quantity, + price, + fashionSize, + ]; + } + + Object encode() { + return _toList(); } + + static TrackingItemWire decode(Object result) { + result as List; + return TrackingItemWire( + id: result[0]! as String, + quantity: result[1]! as int, + price: result[2] as double?, + fashionSize: result[3] as String?, + ); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! TrackingItemWire || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()) +; +} + +/// Wire format for event attribution (maps to native `TrackingSource`). +/// +/// [type] is the wire value of the source type — `dynamic`, `chain`, `bulk`, +/// `transactional`, `instant_search`, `full_search`, `stories`. Dart only ever sends what its +/// `TrackingSourceType` enum produces; the bridges reject anything else. +class TrackingSourceWire { + TrackingSourceWire({ + required this.type, + required this.code, + }); + + String type; + + String code; + + List _toList() { + return [ + type, + code, + ]; + } + + Object encode() { + return _toList(); } + + static TrackingSourceWire decode(Object result) { + result as List; + return TrackingSourceWire( + type: result[0]! as String, + code: result[1]! as String, + ); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! TrackingSourceWire || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()) +; +} + class _PigeonCodec extends StandardMessageCodec { const _PigeonCodec(); @@ -338,6 +448,12 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is ProfileParamsWire) { buffer.putUint8(131); writeValue(buffer, value.encode()); + } else if (value is TrackingItemWire) { + buffer.putUint8(132); + writeValue(buffer, value.encode()); + } else if (value is TrackingSourceWire) { + buffer.putUint8(133); + writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } @@ -352,6 +468,10 @@ class _PigeonCodec extends StandardMessageCodec { return PurchaseLineItemWire.decode(readValue(buffer)!); case 131: return ProfileParamsWire.decode(readValue(buffer)!); + case 132: + return TrackingItemWire.decode(readValue(buffer)!); + case 133: + return TrackingSourceWire.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -943,6 +1063,283 @@ class PersonalizationHostApi { } } + Future trackProductView(String itemId, TrackingSourceWire? source, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackProductView$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, source, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackCategoryView(String categoryId, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackCategoryView$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([categoryId, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackSearch(String query, List? results, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSearch$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([query, results, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackAddToCart(TrackingItemWire item, TrackingSourceWire? source, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToCart$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([item, source, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackSyncCart(List items, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncCart$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([items, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackRemoveFromCart(String itemId, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromCart$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackAddToFavorites(String itemId, TrackingSourceWire? source, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToFavorites$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, source, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackSyncFavorites(List itemIds, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncFavorites$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemIds, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackRemoveFromFavorites(String itemId, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromFavorites$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackStoryView(String storyId, String slideId, String? code, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryView$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([storyId, slideId, code, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + Future trackStoryClick(String storyId, String slideId, String? code, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryClick$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([storyId, slideId, code, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + /// Stores the attribution source natively for the next event. + Future trackSetSource(TrackingSourceWire source, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSetSource$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([source, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + /// [customJson] and [recommendedSourceJson] are JSON object strings or null. Future trackPurchase(String orderId, double orderPrice, List items, String? deliveryType, String? deliveryAddress, String? paymentType, bool isTaxFree, String? promocode, double? orderCash, double? orderBonuses, double? orderDelivery, double? orderDiscount, String? channel, String? customJson, String? recommendedSourceJson, String? stream, String? segment, String? shopId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPurchase$pigeonVar_messageChannelSuffix'; diff --git a/lib/src/tracking/tracking_api.dart b/lib/src/tracking/tracking_api.dart new file mode 100644 index 0000000..1221c2d --- /dev/null +++ b/lib/src/tracking/tracking_api.dart @@ -0,0 +1,212 @@ +import 'dart:convert'; + +import '../pigeon/personalization_api.g.dart' as pigeon; +import 'purchase_line_item.dart'; +import 'tracking_models.dart'; + +/// Standard tracking events — the `tracking` namespace of the SDK. +/// +/// Reached through an SDK handle: `Rees46.getInstance().tracking.productView('sku-1')`. +/// Every method routes to the native namespace of the same name, so an event fired from Dart +/// is the same request the native SDKs send. +class TrackingApi { + TrackingApi(this._api, this._shopId); + + final pigeon.PersonalizationHostApi _api; + + /// The shop this namespace tracks for; `null` is the legacy default instance. + final String? _shopId; + + /// Product page opened (`view`). + Future productView(String itemId, {TrackingSource? source}) { + _requireNonEmpty(itemId, 'itemId'); + return _api.trackProductView(itemId, source?._wire, _shopId); + } + + /// Category listing opened (`category`). + Future categoryView(String categoryId) { + _requireNonEmpty(categoryId, 'categoryId'); + return _api.trackCategoryView(categoryId, _shopId); + } + + /// Search query issued by the user (`search`). + /// + /// Pass [results] when the host runs its own search and knows the ids it showed. + Future search(String query, {List? results}) { + _requireNonEmpty(query, 'query'); + return _api.trackSearch(query, results, _shopId); + } + + /// One product added to the cart (`cart`). + Future addToCart(TrackingItem item, {TrackingSource? source}) { + _requireNonEmpty(item.id, 'item.id'); + return _api.trackAddToCart(item._wire, source?._wire, _shopId); + } + + /// Full cart contents after a change (`cart` with `full_cart`). + Future syncCart(List items) { + if (items.isEmpty) { + throw ArgumentError.value(items, 'items', 'must be non-empty'); + } + return _api.trackSyncCart(items.map((e) => e._wire).toList(), _shopId); + } + + /// One product removed from the cart (`remove_from_cart`). + Future removeFromCart(String itemId) { + _requireNonEmpty(itemId, 'itemId'); + return _api.trackRemoveFromCart(itemId, _shopId); + } + + /// One product added to favorites (`wish`). + Future addToFavorites(String itemId, {TrackingSource? source}) { + _requireNonEmpty(itemId, 'itemId'); + return _api.trackAddToFavorites(itemId, source?._wire, _shopId); + } + + /// Full favorites contents after a change (`wish` with `full_wish`). + Future syncFavorites(List itemIds) { + if (itemIds.isEmpty) { + throw ArgumentError.value(itemIds, 'itemIds', 'must be non-empty'); + } + return _api.trackSyncFavorites(itemIds, _shopId); + } + + /// One product removed from favorites (`remove_wish`). + Future removeFromFavorites(String itemId) { + _requireNonEmpty(itemId, 'itemId'); + return _api.trackRemoveFromFavorites(itemId, _shopId); + } + + /// A story slide was shown (`track/stories`, `view`). + /// + /// [code] is the stories block code; when omitted the native SDK uses the block it last + /// loaded. + Future storyView({ + required String storyId, + required String slideId, + String? code, + }) { + _requireNonEmpty(storyId, 'storyId'); + _requireNonEmpty(slideId, 'slideId'); + return _api.trackStoryView(storyId, slideId, code, _shopId); + } + + /// A story slide was tapped (`track/stories`, `click`). + Future storyClick({ + required String storyId, + required String slideId, + String? code, + }) { + _requireNonEmpty(storyId, 'storyId'); + _requireNonEmpty(slideId, 'slideId'); + return _api.trackStoryClick(storyId, slideId, code, _shopId); + } + + /// Stores the attribution source for subsequent events. + /// + /// Use it when the source outlives a single call — a user entering the catalog from a + /// recommender block. For a single event prefer the `source` parameter. + Future setSource(TrackingSource source) { + return _api.trackSetSource(source._wire, _shopId); + } + + /// Completed order (`purchase`). + Future purchase({ + required String orderId, + required double orderPrice, + required List items, + String? deliveryType, + String? deliveryAddress, + String? paymentType, + bool isTaxFree = false, + String? promocode, + double? orderCash, + double? orderBonuses, + double? orderDelivery, + double? orderDiscount, + String? channel, + Map? custom, + Map? recommendedSource, + String? stream, + String? segment, + }) { + _requireNonEmpty(orderId, 'orderId'); + if (items.isEmpty) { + throw ArgumentError.value(items, 'items', 'must be non-empty'); + } + return _api.trackPurchase( + orderId, + orderPrice, + items + .map( + (e) => pigeon.PurchaseLineItemWire( + id: e.id, + amount: e.amount, + price: e.price, + lineId: e.lineId, + fashionSize: e.fashionSize, + ), + ) + .toList(), + deliveryType, + deliveryAddress, + paymentType, + isTaxFree, + promocode, + orderCash, + orderBonuses, + orderDelivery, + orderDiscount, + channel, + custom == null ? null : jsonEncode(custom), + recommendedSource == null ? null : jsonEncode(recommendedSource), + stream, + segment, + _shopId, + ); + } + + /// Custom event defined by the shop (`push/custom`). + /// + /// [customFields] is the one deliberately free-form field: its entries are sent at the top + /// level and duplicated under `payload`. Reserved keys are rejected natively. + Future custom( + String event, { + int? time, + String? category, + String? label, + int? value, + Map? customFields, + }) { + _requireNonEmpty(event, 'event'); + return _api.trackEvent( + event, + time, + category, + label, + value, + customFields == null ? null : jsonEncode(customFields), + _shopId, + ); + } + + void _requireNonEmpty(String value, String name) { + if (value.isEmpty) { + throw ArgumentError.value(value, name, 'must be non-empty'); + } + } +} + +extension on TrackingItem { + pigeon.TrackingItemWire get _wire => pigeon.TrackingItemWire( + id: id, + quantity: quantity, + price: price, + fashionSize: fashionSize, + ); +} + +extension on TrackingSource { + pigeon.TrackingSourceWire get _wire => + pigeon.TrackingSourceWire(type: type.wireValue, code: code); +} diff --git a/lib/src/tracking/tracking_models.dart b/lib/src/tracking/tracking_models.dart new file mode 100644 index 0000000..6c22534 --- /dev/null +++ b/lib/src/tracking/tracking_models.dart @@ -0,0 +1,46 @@ +/// One product line in a tracking event. +/// +/// [quantity] is the domain name for the line quantity; on the wire it is sent as `amount` — +/// the field the REES46 API has always consumed. +class TrackingItem { + final String id; + final int quantity; + final double? price; + final String? fashionSize; + + const TrackingItem({ + required this.id, + this.quantity = 1, + this.price, + this.fashionSize, + }); +} + +/// The tool an event is attributed to (`recommended_by` on the wire). +/// +/// [dynamicBlock] carries the wire value `dynamic`, which cannot be an enum member name in Dart. +enum TrackingSourceType { + dynamicBlock('dynamic'), + chain('chain'), + bulk('bulk'), + transactional('transactional'), + instantSearch('instant_search'), + fullSearch('full_search'), + stories('stories'); + + const TrackingSourceType(this.wireValue); + + /// The value the API expects for `recommended_by`. + final String wireValue; +} + +/// Where a tracked action came from — a recommender block, a search result, a story. +/// +/// Passed per call to attribute a single event, or stored for subsequent events with +/// [TrackingApi.setSource]. +class TrackingSource { + final TrackingSourceType type; + final String code; + + const TrackingSource({required this.type, required this.code}); +} diff --git a/pigeons/personalization_api.dart b/pigeons/personalization_api.dart index f479fb3..78e7cec 100644 --- a/pigeons/personalization_api.dart +++ b/pigeons/personalization_api.dart @@ -109,6 +109,35 @@ class ProfileParamsWire { }); } +/// Wire format for one product line in a tracking event (maps to native `TrackingItem`). +/// +/// [quantity] is the domain name for the line quantity; native sends it as `amount`. +class TrackingItemWire { + final String id; + final int quantity; + final double? price; + final String? fashionSize; + + const TrackingItemWire({ + required this.id, + required this.quantity, + this.price, + this.fashionSize, + }); +} + +/// Wire format for event attribution (maps to native `TrackingSource`). +/// +/// [type] is the wire value of the source type — `dynamic`, `chain`, `bulk`, +/// `transactional`, `instant_search`, `full_search`, `stories`. Dart only ever sends what its +/// `TrackingSourceType` enum produces; the bridges reject anything else. +class TrackingSourceWire { + final String type; + final String code; + + const TrackingSourceWire({required this.type, required this.code}); +} + // Multi-instance: every per-instance method carries a trailing `String? shopId` // so the native bridge can resolve the target instance via the native `Rees46` // facade. `shopId == null` means the legacy single/default instance (the @@ -228,6 +257,46 @@ abstract class PersonalizationHostApi { @async void handlePush(Map payload, int event); + // Standard tracking events (`tracking` namespace). Each maps onto the native namespace + // method of the same name; `trackEvent` and `trackPurchase` above are its `custom` and + // `purchase` members. + + @async + void trackProductView(String itemId, TrackingSourceWire? source, String? shopId); + + @async + void trackCategoryView(String categoryId, String? shopId); + + @async + void trackSearch(String query, List? results, String? shopId); + + @async + void trackAddToCart(TrackingItemWire item, TrackingSourceWire? source, String? shopId); + + @async + void trackSyncCart(List items, String? shopId); + + @async + void trackRemoveFromCart(String itemId, String? shopId); + + @async + void trackAddToFavorites(String itemId, TrackingSourceWire? source, String? shopId); + + @async + void trackSyncFavorites(List itemIds, String? shopId); + + @async + void trackRemoveFromFavorites(String itemId, String? shopId); + + @async + void trackStoryView(String storyId, String slideId, String? code, String? shopId); + + @async + void trackStoryClick(String storyId, String slideId, String? code, String? shopId); + + /// Stores the attribution source natively for the next event. + void trackSetSource(TrackingSourceWire source, String? shopId); + /// [customJson] and [recommendedSourceJson] are JSON object strings or null. @async void trackPurchase( From 34a47d9fd606a7ddbc5ea1168345dc281d0faf5d Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 28 Aug 2026 10:08:53 +0400 Subject: [PATCH 3/9] test(tracking): cover the namespace and drive it from the demo `tracking_namespace_test` asserts that every method reaches its own Pigeon channel with the arguments native expects, that models and the source wire values survive the crossing, that the shop id is threaded through, and that arguments are validated before the call. The demo gets a button per standard event, all calling `sdk.tracking.*`, each writing its outcome into a result line, and its two existing tracking buttons move onto the namespace. `tracking_events_test` taps those buttons and reads the line, so the run exercises every method against the real API. --- example/integration_test/test_bundle.dart | 8 +- .../tracking_events_test.dart | 71 +++++ example/lib/main.dart | 145 +++++++++- test/tracking_namespace_test.dart | 255 ++++++++++++++++++ 4 files changed, 473 insertions(+), 6 deletions(-) create mode 100644 example/integration_test/tracking_events_test.dart create mode 100644 test/tracking_namespace_test.dart diff --git a/example/integration_test/test_bundle.dart b/example/integration_test/test_bundle.dart index 4cc56c4..dd162f8 100644 --- a/example/integration_test/test_bundle.dart +++ b/example/integration_test/test_bundle.dart @@ -9,7 +9,7 @@ import 'package:patrol/src/platform/contracts/contracts.dart'; import 'package:test_api/src/backend/invoker.dart'; // START: GENERATED TEST IMPORTS -import 'search_blank_sdk_test.dart' as search_blank_sdk_test; +import 'tracking_events_test.dart' as tracking_events_test; // END: GENERATED TEST IMPORTS Future main() async { @@ -71,9 +71,9 @@ Future main() async { reportGroupStructure(dartTestGroup); }); - // START: GENERATED TEST GROUPS - group('search_blank_sdk_test', search_blank_sdk_test.main); - // END: GENERATED TEST GROUPS +// START: GENERATED TEST GROUPS + group('tracking_events_test', tracking_events_test.main); +// END: GENERATED TEST GROUPS final dartTestGroup = await testExplorationCompleter.future; final appService = PatrolAppService(topLevelDartTestGroup: dartTestGroup); diff --git a/example/integration_test/tracking_events_test.dart b/example/integration_test/tracking_events_test.dart new file mode 100644 index 0000000..d6eddbf --- /dev/null +++ b/example/integration_test/tracking_events_test.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:patrol/patrol.dart'; + +import 'package:rees46_sdk_example/main.dart' as app; + +import 'patrol_setup.dart'; + +/// Taps every button of the demo's standard-events section and reads the result line the +/// handler writes. +/// +/// The handlers call `sdk.tracking.*` against the real API, so a green run means both that the +/// bridge is wired and that every method works end to end on this platform. + +Future _initializeSdk(PatrolIntegrationTester $) async { + await $.pumpWidgetAndSettle(const app.App()); + await dismissStartupPermissionDialog($); + await $( + 'Status: Initialized', + ).waitUntilExists(timeout: const Duration(seconds: 30)); +} + +String _resultText(PatrolIntegrationTester $) { + final widget = $.tester.widget( + find.byKey(const Key('lbl_tracking_result')), + ); + return widget.data ?? ''; +} + +/// Taps [key] and waits until the result line reports on [method]. +Future _tapAndExpectSuccess( + PatrolIntegrationTester $, + String key, + String method, +) async { + await $(Key(key)).scrollTo(maxScrolls: 60); + await $(Key(key)).tap(); + + final deadline = DateTime.now().add(const Duration(seconds: 30)); + while (!_resultText($).startsWith(method)) { + if (DateTime.now().isAfter(deadline)) { + fail('$method never reported, last result: "${_resultText($)}"'); + } + await $.pump(const Duration(milliseconds: 100)); + } + + expect(_resultText($), '$method OK'); +} + +void main() { + const demos = { + 'tracking_product_view': 'productView', + 'tracking_category_view': 'categoryView', + 'tracking_search': 'search', + 'tracking_add_to_cart': 'addToCart', + 'tracking_sync_cart': 'syncCart', + 'tracking_remove_from_cart': 'removeFromCart', + 'tracking_add_to_favorites': 'addToFavorites', + 'tracking_sync_favorites': 'syncFavorites', + 'tracking_remove_from_favorites': 'removeFromFavorites', + 'tracking_set_source': 'setSource', + }; + + patrolTest('every standard event reports success', ($) async { + await _initializeSdk($); + + for (final entry in demos.entries) { + await _tapAndExpectSuccess($, entry.key, entry.value); + } + }); +} diff --git a/example/lib/main.dart b/example/lib/main.dart index 3374284..79700e7 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -31,6 +31,112 @@ class InitPage extends StatefulWidget { enum InitState { idle, initializing, initialized, failed } +/// One button of the standard-events section. +class _TrackingDemo { + const _TrackingDemo({ + required this.key, + required this.label, + required this.method, + required this.call, + }); + + final String key; + final String label; + final String method; + final Future Function(TrackingApi tracking) call; +} + +const _demoItemId = 'flutter-demo-sku-001'; +const _demoSecondItemId = 'flutter-demo-sku-002'; +const _demoCategoryId = 'flutter-demo-category'; +const _demoSearchQuery = 'demo boots'; +const _demoSourceCode = 'flutter-demo-block'; + +final List<_TrackingDemo> _trackingDemos = [ + _TrackingDemo( + key: 'tracking_product_view', + label: 'Tracking: product view', + method: 'productView', + call: (tracking) => tracking.productView( + _demoItemId, + source: const TrackingSource( + type: TrackingSourceType.dynamicBlock, + code: _demoSourceCode, + ), + ), + ), + _TrackingDemo( + key: 'tracking_category_view', + label: 'Tracking: category view', + method: 'categoryView', + call: (tracking) => tracking.categoryView(_demoCategoryId), + ), + _TrackingDemo( + key: 'tracking_search', + label: 'Tracking: search', + method: 'search', + call: (tracking) => tracking.search( + _demoSearchQuery, + results: const [_demoItemId, _demoSecondItemId], + ), + ), + _TrackingDemo( + key: 'tracking_add_to_cart', + label: 'Tracking: add to cart', + method: 'addToCart', + call: (tracking) => tracking.addToCart( + const TrackingItem(id: _demoItemId, quantity: 2, price: 49.9), + ), + ), + _TrackingDemo( + key: 'tracking_sync_cart', + label: 'Tracking: sync cart', + method: 'syncCart', + call: (tracking) => tracking.syncCart(const [ + TrackingItem(id: _demoItemId, quantity: 2, price: 49.9), + TrackingItem(id: _demoSecondItemId), + ]), + ), + _TrackingDemo( + key: 'tracking_remove_from_cart', + label: 'Tracking: remove from cart', + method: 'removeFromCart', + call: (tracking) => tracking.removeFromCart(_demoItemId), + ), + _TrackingDemo( + key: 'tracking_add_to_favorites', + label: 'Tracking: add to favorites', + method: 'addToFavorites', + call: (tracking) => tracking.addToFavorites(_demoItemId), + ), + _TrackingDemo( + key: 'tracking_sync_favorites', + label: 'Tracking: sync favorites', + method: 'syncFavorites', + call: (tracking) => tracking.syncFavorites(const [ + _demoItemId, + _demoSecondItemId, + ]), + ), + _TrackingDemo( + key: 'tracking_remove_from_favorites', + label: 'Tracking: remove from favorites', + method: 'removeFromFavorites', + call: (tracking) => tracking.removeFromFavorites(_demoItemId), + ), + _TrackingDemo( + key: 'tracking_set_source', + label: 'Tracking: set source', + method: 'setSource', + call: (tracking) => tracking.setSource( + const TrackingSource( + type: TrackingSourceType.dynamicBlock, + code: _demoSourceCode, + ), + ), + ), +]; + class _InitPageState extends State { // Initialized through the multi-instance [Rees46] facade — the same entry // point the iOS/Android demos use — so shop A is registered in the facade and @@ -545,10 +651,28 @@ class _InitPageState extends State { } } + String? _trackingResult; + + /// Runs one namespace call and shows the outcome as ` OK` / ` failed`, + /// which is what the integration test reads. + Future _runTracking( + String method, + Future Function(TrackingApi tracking) call, + ) async { + try { + await call(_sdk.tracking); + if (!mounted) return; + setState(() => _trackingResult = '$method OK'); + } catch (e) { + if (!mounted) return; + setState(() => _trackingResult = '$method failed: $e'); + } + } + Future _demoTrackEvent() async { if (_initState != InitState.initialized) return; try { - await _sdk.trackEvent( + await _sdk.tracking.custom( 'flutter_example', // 'source' is a reserved event key (collides with the SDK's own body // fields) — use a non-reserved custom key. @@ -569,7 +693,7 @@ class _InitPageState extends State { Future _demoTrackPurchase() async { if (_initState != InitState.initialized) return; try { - await _sdk.trackPurchase( + await _sdk.tracking.purchase( orderId: 'example-order-1', orderPrice: 99.0, items: const [PurchaseLineItem(id: 'sku-1', amount: 1, price: 99.0)], @@ -807,6 +931,23 @@ class _InitPageState extends State { : null, child: const Text('Send demo trackPurchase'), ), + const SizedBox(height: 24), + Text( + 'Standard events (sdk.tracking)', + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + for (final demo in _trackingDemos) ...[ + OutlinedButton( + key: Key(demo.key), + onPressed: _initState == InitState.initialized + ? () => _runTracking(demo.method, demo.call) + : null, + child: Text(demo.label), + ), + const SizedBox(height: 8), + ], + Text(key: const Key('lbl_tracking_result'), _trackingResult ?? '—'), ], ), ), diff --git a/test/tracking_namespace_test.dart b/test/tracking_namespace_test.dart new file mode 100644 index 0000000..776743a --- /dev/null +++ b/test/tracking_namespace_test.dart @@ -0,0 +1,255 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; + +/// Covers the `tracking` namespace: that every method reaches its own Pigeon channel with the +/// arguments the native side expects, and that the models are put on the wire unchanged. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const codec = pigeon.PersonalizationHostApi.pigeonChannelCodec; + const prefix = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.'; + const flutterApiPrefix = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.'; + + final mocked = []; + + void mockChannel(String channel, MessageHandler handler) { + mocked.add(channel); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMessageHandler(channel, handler); + } + + /// Captures the decoded argument list of the next call on [method]. + List Function() capture(String method) { + List? captured; + mockChannel(prefix + method, (ByteData? msg) async { + captured = codec.decodeMessage(msg) as List; + return codec.encodeMessage([]); + }); + return () => captured!; + } + + setUp(() { + // The SDK constructor claims the push channels; stub them so they stay quiet. + for (final event in ['onPushReceived', 'onPushDelivered', 'onPushClicked']) { + mockChannel( + flutterApiPrefix + event, + (ByteData? _) async => codec.encodeMessage([]), + ); + } + }); + + tearDown(() { + for (final channel in mocked) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMessageHandler(channel, null); + } + mocked.clear(); + }); + + group('events reach their channel', () { + test('productView sends the item id and no source by default', () async { + final args = capture('trackProductView'); + await PersonalizationSdk().tracking.productView('sku-1'); + + expect(args()[0], 'sku-1'); + expect(args()[1], isNull); + }); + + test('categoryView sends the category id', () async { + final args = capture('trackCategoryView'); + await PersonalizationSdk().tracking.categoryView('women-shoes'); + + expect(args()[0], 'women-shoes'); + }); + + test('search sends the query and the shown results', () async { + final args = capture('trackSearch'); + await PersonalizationSdk().tracking.search( + 'boots', + results: ['sku-1', 'sku-2'], + ); + + expect(args()[0], 'boots'); + expect(args()[1], ['sku-1', 'sku-2']); + }); + + test('addToCart carries quantity and price', () async { + final args = capture('trackAddToCart'); + await PersonalizationSdk().tracking.addToCart( + const TrackingItem(id: 'sku-1', quantity: 3, price: 49.9), + ); + + final item = args()[0] as pigeon.TrackingItemWire; + expect(item.id, 'sku-1'); + expect(item.quantity, 3); + expect(item.price, 49.9); + }); + + test('syncCart sends every line', () async { + final args = capture('trackSyncCart'); + await PersonalizationSdk().tracking.syncCart(const [ + TrackingItem(id: 'sku-1', quantity: 2, price: 10), + TrackingItem(id: 'sku-2'), + ]); + + final items = (args()[0] as List).cast(); + expect(items.length, 2); + expect(items[1].quantity, 1, reason: 'quantity defaults to one unit'); + expect(items[1].price, isNull); + }); + + test('removeFromCart sends the item id', () async { + final args = capture('trackRemoveFromCart'); + await PersonalizationSdk().tracking.removeFromCart('sku-1'); + + expect(args()[0], 'sku-1'); + }); + + test('favorites reach their own channels', () async { + final added = capture('trackAddToFavorites'); + final removed = capture('trackRemoveFromFavorites'); + final synced = capture('trackSyncFavorites'); + final sdk = PersonalizationSdk(); + + await sdk.tracking.addToFavorites('sku-1'); + await sdk.tracking.removeFromFavorites('sku-2'); + await sdk.tracking.syncFavorites(['sku-1', 'sku-3']); + + expect(added()[0], 'sku-1'); + expect(removed()[0], 'sku-2'); + expect(synced()[0], ['sku-1', 'sku-3']); + }); + + test('story events carry ids and an optional block code', () async { + final viewed = capture('trackStoryView'); + final clicked = capture('trackStoryClick'); + final sdk = PersonalizationSdk(); + + await sdk.tracking.storyView( + storyId: '42', + slideId: '3', + code: 'main_stories', + ); + await sdk.tracking.storyClick(storyId: '42', slideId: '3'); + + expect(viewed().sublist(0, 3), ['42', '3', 'main_stories']); + expect(clicked()[2], isNull, reason: 'native falls back to the loaded block'); + }); + }); + + group('attribution', () { + test('a per-call source is sent as its wire value', () async { + final args = capture('trackProductView'); + await PersonalizationSdk().tracking.productView( + 'sku-1', + source: const TrackingSource( + type: TrackingSourceType.dynamicBlock, + code: 'popular', + ), + ); + + final source = args()[1] as pigeon.TrackingSourceWire; + expect(source.type, 'dynamic'); + expect(source.code, 'popular'); + }); + + test('setSource sends the stored source', () async { + final args = capture('trackSetSource'); + await PersonalizationSdk().tracking.setSource( + const TrackingSource( + type: TrackingSourceType.fullSearch, + code: 'boots', + ), + ); + + expect((args()[0] as pigeon.TrackingSourceWire).type, 'full_search'); + }); + + test('every source type has the wire value the API expects', () { + expect( + TrackingSourceType.values.map((e) => e.wireValue), + [ + 'dynamic', + 'chain', + 'bulk', + 'transactional', + 'instant_search', + 'full_search', + 'stories', + ], + ); + }); + }); + + group('the shop id is threaded through', () { + test('a handle bound to a shop sends it as the last argument', () async { + final args = capture('trackProductView'); + await PersonalizationSdk(shopId: 'shop-a').tracking.productView('sku-1'); + + expect(args().last, 'shop-a'); + }); + + test('an unbound handle sends null', () async { + final args = capture('trackProductView'); + await PersonalizationSdk().tracking.productView('sku-1'); + + expect(args().last, isNull); + }); + }); + + group('validation happens before the channel call', () { + final sdk = PersonalizationSdk(); + + test('empty ids throw', () { + expect(() => sdk.tracking.productView(''), throwsArgumentError); + expect(() => sdk.tracking.categoryView(''), throwsArgumentError); + expect(() => sdk.tracking.search(''), throwsArgumentError); + expect(() => sdk.tracking.removeFromCart(''), throwsArgumentError); + expect(() => sdk.tracking.addToFavorites(''), throwsArgumentError); + expect( + () => sdk.tracking.addToCart(const TrackingItem(id: '')), + throwsArgumentError, + ); + expect( + () => sdk.tracking.storyView(storyId: '', slideId: '3'), + throwsArgumentError, + ); + }); + + test('empty collections throw', () { + expect(() => sdk.tracking.syncCart(const []), throwsArgumentError); + expect(() => sdk.tracking.syncFavorites(const []), throwsArgumentError); + }); + }); + + group('purchase and custom events keep working through the namespace', () { + test('purchase reaches the existing trackPurchase channel', () async { + final args = capture('trackPurchase'); + await PersonalizationSdk().tracking.purchase( + orderId: 'order-1', + orderPrice: 100, + items: const [PurchaseLineItem(id: 'sku-1', amount: 1, price: 100)], + ); + + expect(args()[0], 'order-1'); + expect(args()[1], 100.0); + }); + + test('custom reaches the existing trackEvent channel', () async { + final args = capture('trackEvent'); + await PersonalizationSdk().tracking.custom( + 'checkout_step', + time: 1000, + category: 'checkout', + ); + + expect(args()[0], 'checkout_step'); + expect(args()[1], 1000); + expect(args()[2], 'checkout'); + }); + }); +} From d366b7916b2d38f87e20038d40ffffc104e02e34 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Sun, 30 Aug 2026 19:00:53 +0400 Subject: [PATCH 4/9] fix(tracking): follow the native namespace rename and widen the source set The iOS namespace renamed its argument labels to match Android and Dart (itemId / categoryId / itemIds), so the Swift bridge follows. A story source no longer has to be dropped on the way to iOS: TrackingSource there now takes TrackingSourceType, which carries `stories`. Dart gains webPushDigest, so all three enums hold the same set. --- ios/Classes/Rees46FlutterSdkPlugin.swift | 18 +++++++++--------- lib/src/tracking/tracking_models.dart | 3 ++- test/tracking_namespace_test.dart | 1 + 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/ios/Classes/Rees46FlutterSdkPlugin.swift b/ios/Classes/Rees46FlutterSdkPlugin.swift index cd4b3c8..70dc3a0 100644 --- a/ios/Classes/Rees46FlutterSdkPlugin.swift +++ b/ios/Classes/Rees46FlutterSdkPlugin.swift @@ -856,7 +856,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { completion: @escaping (Result) -> Void ) { withTracking(shopId, completion) { tracking in - tracking.productView(id: itemId, source: source?.native) { self.report($0, completion) } + tracking.productView(itemId: itemId, source: source?.native) { self.report($0, completion) } } } @@ -866,7 +866,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { completion: @escaping (Result) -> Void ) { withTracking(shopId, completion) { tracking in - tracking.categoryView(id: categoryId) { self.report($0, completion) } + tracking.categoryView(categoryId: categoryId) { self.report($0, completion) } } } @@ -908,7 +908,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { completion: @escaping (Result) -> Void ) { withTracking(shopId, completion) { tracking in - tracking.removeFromCart(id: itemId) { self.report($0, completion) } + tracking.removeFromCart(itemId: itemId) { self.report($0, completion) } } } @@ -919,7 +919,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { completion: @escaping (Result) -> Void ) { withTracking(shopId, completion) { tracking in - tracking.addToFavorites(id: itemId, source: source?.native) { self.report($0, completion) } + tracking.addToFavorites(itemId: itemId, source: source?.native) { self.report($0, completion) } } } @@ -929,7 +929,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { completion: @escaping (Result) -> Void ) { withTracking(shopId, completion) { tracking in - tracking.syncFavorites(ids: itemIds) { self.report($0, completion) } + tracking.syncFavorites(itemIds: itemIds) { self.report($0, completion) } } } @@ -939,7 +939,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { completion: @escaping (Result) -> Void ) { withTracking(shopId, completion) { tracking in - tracking.removeFromFavorites(id: itemId) { self.report($0, completion) } + tracking.removeFromFavorites(itemId: itemId) { self.report($0, completion) } } } @@ -1175,10 +1175,10 @@ extension TrackingItemWire { } extension TrackingSourceWire { - /// An unknown source type is dropped rather than guessed — Dart only sends known values. - /// `stories` has no case in the iOS `RecommendedByCase`, so a story source is dropped here. + /// An unknown source type is dropped rather than guessed — Dart only sends known values, and the + /// Dart, Android and iOS `TrackingSourceType` enums carry the same set. var native: TrackingSource? { - guard let type = RecommendedByCase(rawValue: type) else { return nil } + guard let type = TrackingSourceType(rawValue: type) else { return nil } return TrackingSource(type: type, code: code) } } diff --git a/lib/src/tracking/tracking_models.dart b/lib/src/tracking/tracking_models.dart index 6c22534..10eeeb8 100644 --- a/lib/src/tracking/tracking_models.dart +++ b/lib/src/tracking/tracking_models.dart @@ -26,7 +26,8 @@ enum TrackingSourceType { transactional('transactional'), instantSearch('instant_search'), fullSearch('full_search'), - stories('stories'); + stories('stories'), + webPushDigest('web_push_digest'); const TrackingSourceType(this.wireValue); diff --git a/test/tracking_namespace_test.dart b/test/tracking_namespace_test.dart index 776743a..317dd06 100644 --- a/test/tracking_namespace_test.dart +++ b/test/tracking_namespace_test.dart @@ -180,6 +180,7 @@ void main() { 'instant_search', 'full_search', 'stories', + 'web_push_digest', ], ); }); From 2e8d52b36cd8573013ec4187df1f07c2f0cd6b0b Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Tue, 1 Sep 2026 17:50:42 +0400 Subject: [PATCH 5/9] chore(deps): switch to the published native SDKs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The natives shipped: Android 2.37.0 (JitPack) and iOS 3.31.0 (CocoaPods). The DEV-4409 local wiring — mavenLocal in three places and a :path pod pointing at a sibling checkout — is gone, and the plugin podspec asks for REES46 3.31.0. Both example apps build against the published artifacts. --- android/build.gradle.kts | 20 ++------------------ example/android/build.gradle.kts | 2 -- example/ios/Podfile | 5 ----- example/ios/Podfile.lock | 14 ++++++-------- ios/rees46_sdk.podspec | 2 +- 5 files changed, 9 insertions(+), 34 deletions(-) diff --git a/android/build.gradle.kts b/android/build.gradle.kts index 848a335..3b1b9e4 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -4,10 +4,6 @@ version = "1.0-SNAPSHOT" buildscript { val kotlinVersion = "2.2.20" repositories { - // LOCAL WIRING (DEV-4409): the native SDK is built from the sibling - // DEV-4409-standart-tracking-metod-unification branch and published to mavenLocal. - // Revert to JitPack coordinates once the native release ships. - mavenLocal() google() mavenCentral() maven(url = "https://jitpack.io") @@ -21,10 +17,6 @@ buildscript { allprojects { repositories { - // LOCAL WIRING (DEV-4409): the native SDK is built from the sibling - // DEV-4409-standart-tracking-metod-unification branch and published to mavenLocal. - // Revert to JitPack coordinates once the native release ships. - mavenLocal() google() mavenCentral() maven(url = "https://jitpack.io") @@ -95,16 +87,8 @@ android { dependencies { // REES46 Android SDK. - // LOCAL WIRING (DEV-4409): built from the sibling android-sdk checkout on branch - // DEV-4409-standart-tracking-metod-unification and published with - // `./gradlew :personalization-sdk:publishRees46ReleaseLibraryPublicationToMavenLocal`. - // Revert to the JitPack coordinate below once the native release ships: - // val rees46AndroidSdkVersion = "v2.36.0" - // add("rees46Implementation", "com.github.rees46:android-sdk:$rees46AndroidSdkVersion") - add( - "rees46Implementation", - "com.personalization:personalization-sdk:2.36.0", - ) + val rees46AndroidSdkVersion = "v2.37.0" + add("rees46Implementation", "com.github.rees46:android-sdk:$rees46AndroidSdkVersion") // Used directly by the push presenter (NotificationCompat / ContextCompat). The native SDK // depends on the same version but as `implementation`, so it is not exposed transitively. diff --git a/example/android/build.gradle.kts b/example/android/build.gradle.kts index c305684..eeea458 100644 --- a/example/android/build.gradle.kts +++ b/example/android/build.gradle.kts @@ -1,7 +1,5 @@ allprojects { repositories { - // LOCAL WIRING (DEV-4409) — see android/build.gradle.kts. Remove with it. - mavenLocal() google() mavenCentral() maven(url = "https://jitpack.io") diff --git a/example/ios/Podfile b/example/ios/Podfile index 63edfd1..5612959 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -30,11 +30,6 @@ flutter_ios_podfile_setup target 'Runner' do use_frameworks! - # LOCAL WIRING (DEV-4409): the native pod is taken from the sibling ios-sdk checkout on branch - # DEV-4409-standart-tracking-metod-unification. Remove this line once the release ships — the - # pod normally comes from the plugin podspec's dependency. - pod 'REES46', :path => '/Users/andreykropotov/Documents/FlutterProjects/ios-sdk' - target 'RunnerUITests' do inherit! :complete end diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index cf6adee..0fd4771 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -7,21 +7,21 @@ PODS: - CocoaAsyncSocket (~> 7.6) - Flutter - FlutterMacOS - - REES46 (3.30.0) + - REES46 (3.31.0) - rees46_sdk (0.0.1): - Flutter - - REES46 (= 3.30.0) + - REES46 (= 3.31.0) DEPENDENCIES: - Flutter (from `Flutter`) - integration_test (from `.symlinks/plugins/integration_test/ios`) - patrol (from `.symlinks/plugins/patrol/darwin`) - - REES46 (from `/Users/andreykropotov/Documents/FlutterProjects/ios-sdk`) - rees46_sdk (from `.symlinks/plugins/rees46_sdk/ios`) SPEC REPOS: trunk: - CocoaAsyncSocket + - REES46 EXTERNAL SOURCES: Flutter: @@ -30,8 +30,6 @@ EXTERNAL SOURCES: :path: ".symlinks/plugins/integration_test/ios" patrol: :path: ".symlinks/plugins/patrol/darwin" - REES46: - :path: "/Users/andreykropotov/Documents/FlutterProjects/ios-sdk" rees46_sdk: :path: ".symlinks/plugins/rees46_sdk/ios" @@ -40,9 +38,9 @@ SPEC CHECKSUMS: Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 integration_test: 4a889634ef21a45d28d50d622cf412dc6d9f586e patrol: cea8074f183a2a4232d0ebd10569ae05149ada42 - REES46: e99e94c2ae031e62b6dd62c81a0d0db37659a48c - rees46_sdk: 5677cdb063f6ed6f1fd7cfafe3cd209a47313c7c + REES46: 7ce1596d694a17cad9f5d646e37d31122520d680 + rees46_sdk: cafb55d934fd342eca9c0c4b2d3f5b2f04d2d282 -PODFILE CHECKSUM: 060e5d67fb40e2ac65b0b9bf93fba35390ac423b +PODFILE CHECKSUM: b6e248ac4c1eff5807c8b044b39b8bc326af3f5f COCOAPODS: 1.16.2 diff --git a/ios/rees46_sdk.podspec b/ios/rees46_sdk.podspec index 1a75adf..8c3c268 100644 --- a/ios/rees46_sdk.podspec +++ b/ios/rees46_sdk.podspec @@ -14,7 +14,7 @@ Flutter plugin wrapper around REES46 native SDK. s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'REES46', '3.30.0' + s.dependency 'REES46', '3.31.0' s.platform = :ios, '13.0' # Flutter.framework does not contain a i386 slice. From 68b37e4646c55e945432d8db7f5536a363bf450d Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Tue, 1 Sep 2026 18:43:15 +0400 Subject: [PATCH 6/9] test(ios): cover the Swift bridge's wire conversion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Everything Dart sends arrives as a pigeon struct and has to become a native type. That conversion had no tests, and it is exactly where the bridge can drop a value silently — a story source used to be dropped there. Seven tests over TrackingItemWire.native and TrackingSourceWire.native: field mapping, the Int64 -> Int narrowing on quantity, every wire value Dart can send resolving to a native case, an unknown type being dropped rather than guessed, and the native enum holding nothing Dart cannot produce. The last two are the regression guard for the three TrackingSourceType enums drifting apart. Added a RunnerTests scheme: the Runner scheme also carries the patrol UI-test target, which only compiles under `patrol test` and so breaks a plain `xcodebuild test`. Run with: flutter pub get && cd ios && xcodebuild -workspace Runner.xcworkspace \ -scheme RunnerTests -sdk iphonesimulator -destination '...' test --- example/ios/Runner.xcodeproj/project.pbxproj | 4 + .../xcschemes/RunnerTests.xcscheme | 119 ++++++++++++++++++ .../ios/RunnerTests/TrackingBridgeTests.swift | 82 ++++++++++++ example/pubspec.lock | 2 +- 4 files changed, 206 insertions(+), 1 deletion(-) create mode 100644 example/ios/Runner.xcodeproj/xcshareddata/xcschemes/RunnerTests.xcscheme create mode 100644 example/ios/RunnerTests/TrackingBridgeTests.swift diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index 246e0e7..a3a47ac 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + D1B0FE022F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1B0FE012F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; @@ -54,6 +55,7 @@ 25281CD9083CDCD536709C9E /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; 3059447129043636022194F8 /* Pods-Runner-RunnerUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner-RunnerUITests.release.xcconfig"; path = "Target Support Files/Pods-Runner-RunnerUITests/Pods-Runner-RunnerUITests.release.xcconfig"; sourceTree = ""; }; 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + D1B0FE012F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackingBridgeTests.swift; sourceTree = ""; }; 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 47A6BF8207A65A857E1F9E2C /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; @@ -115,6 +117,7 @@ isa = PBXGroup; children = ( 331C807B294A618700263BE5 /* RunnerTests.swift */, + D1B0FE012F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift */, ); path = RunnerTests; sourceTree = ""; @@ -477,6 +480,7 @@ buildActionMask = 2147483647; files = ( 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + D1B0FE022F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/RunnerTests.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/RunnerTests.xcscheme new file mode 100644 index 0000000..c3fedb2 --- /dev/null +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/RunnerTests.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/RunnerTests/TrackingBridgeTests.swift b/example/ios/RunnerTests/TrackingBridgeTests.swift new file mode 100644 index 0000000..bb567d8 --- /dev/null +++ b/example/ios/RunnerTests/TrackingBridgeTests.swift @@ -0,0 +1,82 @@ +import XCTest + +@testable import REES46 +@testable import rees46_sdk + +/// The Swift side of the Flutter bridge: everything Dart sends arrives as a pigeon wire struct and +/// has to be turned into a native type. That conversion is where the bridge can silently drop or +/// mangle a value — a story source used to be dropped here — so it is pinned rather than trusted. +final class TrackingBridgeTests: XCTestCase { + + // MARK: - Items + + func test_item_carriesEveryFieldThroughUnchanged() { + let wire = TrackingItemWire(id: "sku-1", quantity: 3, price: 49.9, fashionSize: "M") + + let native = wire.native + + XCTAssertEqual(native.id, "sku-1") + XCTAssertEqual(native.quantity, 3) + XCTAssertEqual(native.price, 49.9) + XCTAssertEqual(native.fashionSize, "M") + } + + func test_item_withoutOptionalFields_leavesThemNil() { + let native = TrackingItemWire(id: "sku-1", quantity: 1).native + + XCTAssertEqual(native.id, "sku-1") + XCTAssertEqual(native.quantity, 1) + XCTAssertNil(native.price) + XCTAssertNil(native.fashionSize) + } + + /// Dart sends the quantity as Int64; the native model takes Int. Large values must not wrap. + func test_item_quantity_survivesTheInt64Narrowing() { + XCTAssertEqual(TrackingItemWire(id: "sku-1", quantity: 0).native.quantity, 0) + XCTAssertEqual(TrackingItemWire(id: "sku-1", quantity: 1_000_000).native.quantity, 1_000_000) + } + + // MARK: - Sources + + /// The wire values Dart's `TrackingSourceType` can send. Every one of them must resolve: this + /// list failing is what a divergence between the Dart, Android and iOS enums looks like. + private let wireValues = [ + "dynamic", "chain", "bulk", "transactional", + "instant_search", "full_search", "stories", "web_push_digest", + ] + + func test_everySourceTypeDartCanSend_resolvesToANativeOne() { + for value in wireValues { + let native = TrackingSourceWire(type: value, code: "block-1").native + XCTAssertNotNil(native, "\(value) did not resolve — the bridge would drop it silently") + XCTAssertEqual(native?.type.rawValue, value) + XCTAssertEqual(native?.code, "block-1") + } + } + + /// `stories` has no case in the older `RecommendedByCase`, which is why the bridge used to drop + /// a story source on the floor. It must survive now. + func test_storiesSource_isNotDropped() { + let native = TrackingSourceWire(type: "stories", code: "main_stories").native + + XCTAssertEqual(native?.type, .stories) + XCTAssertEqual(native?.code, "main_stories") + } + + func test_anUnknownSourceType_isDroppedRatherThanGuessed() { + XCTAssertNil(TrackingSourceWire(type: "not_a_source", code: "x").native) + XCTAssertNil(TrackingSourceWire(type: "", code: "x").native) + XCTAssertNil(TrackingSourceWire(type: "DYNAMIC", code: "x").native, "matching is exact") + } + + /// The native enum must not grow a case Dart cannot produce, or hosts get a source through one + /// platform and not the other. + func test_theNativeEnumHasNothingDartCannotSend() { + let native: [TrackingSourceType] = [ + .dynamic, .chain, .bulk, .transactional, + .instantSearch, .fullSearch, .stories, .webPushDigest, + ] + + XCTAssertEqual(Set(native.map(\.rawValue)), Set(wireValues)) + } +} diff --git a/example/pubspec.lock b/example/pubspec.lock index 2449395..b21c337 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -256,7 +256,7 @@ packages: path: ".." relative: true source: path - version: "0.1.1" + version: "0.2.0" shelf: dependency: transitive description: From 8111944b16ffa13b8c5517807a835f7db157d7d0 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Wed, 2 Sep 2026 11:05:52 +0400 Subject: [PATCH 7/9] docs(tracking): document every standard event with an example --- README.md | 195 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) diff --git a/README.md b/README.md index 66ccf7c..e94fede 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,201 @@ without an id resolves only while exactly one shop is registered, and throws never registered). +## Track events + +Standard events live in the `tracking` namespace of the handle: + +```dart +await sdk.tracking.productView('sku-1'); +``` + +Each method returns a `Future` that completes once the native SDK has the +API's answer; a rejected request throws a `PlatformException` (`track_failed`, or +`track_event_failed` / `track_purchase_failed` for custom events and orders). +Awaiting is optional — fire-and-forget from UI code is fine. + +With several shops the namespace follows the instance: + +```dart +await Rees46.getInstance('shop-b').tracking.productView('sku-1'); +``` + +### Catalog + +```dart +// Product page opened. +await sdk.tracking.productView('sku-1'); + +// Category listing opened. +await sdk.tracking.categoryView('boots'); + +// The user searched. Pass `results` when your app runs the search itself and +// knows the ids it showed. +await sdk.tracking.search('winter boots', results: ['sku-1', 'sku-2']); +``` + +### Cart + +```dart +// One product added. +await sdk.tracking.addToCart( + const TrackingItem(id: 'sku-1', quantity: 2, price: 49.9, fashionSize: '42'), +); + +// The cart as it looks after a change — replaces the stored contents. +await sdk.tracking.syncCart(const [ + TrackingItem(id: 'sku-1', quantity: 2, price: 49.9), + TrackingItem(id: 'sku-2'), // quantity defaults to 1 +]); + +// One product removed. +await sdk.tracking.removeFromCart('sku-1'); +``` + +`TrackingItem` needs only an `id`; `quantity` defaults to `1`, `price` and +`fashionSize` are optional. + +### Favorites + +```dart +await sdk.tracking.addToFavorites('sku-1'); + +await sdk.tracking.syncFavorites(const ['sku-1', 'sku-2']); + +await sdk.tracking.removeFromFavorites('sku-1'); +``` + +`syncCart` and `syncFavorites` reject an empty list with an `ArgumentError` — +drop the last item through `removeFromCart` / `removeFromFavorites` instead. + +### Stories + +Only needed when you render stories yourself — the built-in stories view tracks +its own views and taps. + +```dart +await sdk.tracking.storyView( + storyId: '4321', + slideId: '2', + code: 'main_stories', +); + +await sdk.tracking.storyClick( + storyId: '4321', + slideId: '2', + code: 'main_stories', +); +``` + +`code` is the stories block; omit it and the native SDK uses the block it loaded +last. A tracked story also becomes the source of the events that follow it — the +same rule as [`setSource`](#attribution). + +### Purchase + +```dart +await sdk.tracking.purchase( + orderId: 'order-1024', + orderPrice: 149.8, + items: const [ + PurchaseLineItem(id: 'sku-1', amount: 2, price: 49.9, fashionSize: '42'), + PurchaseLineItem(id: 'sku-2', amount: 1, price: 50.0), + ], +); +``` + +Those three are required; everything else is optional: + +```dart +await sdk.tracking.purchase( + orderId: 'order-1024', + orderPrice: 149.8, + items: const [PurchaseLineItem(id: 'sku-1', amount: 1, price: 149.8)], + deliveryType: 'courier', + deliveryAddress: 'Tverskaya 1, Moscow', + paymentType: 'card', + isTaxFree: false, + promocode: 'WINTER20', + orderCash: 100.0, + orderBonuses: 49.8, + orderDelivery: 5.0, + orderDiscount: 20.0, + channel: 'mobile_app', + custom: const {'store_id': 'msk-01'}, + recommendedSource: const {'from': 'dynamic', 'code': 'main_page_block'}, + stream: 'flutter', + segment: 'a', +); +``` + +`custom` goes on the wire under `custom`; keys that collide with the order's own +fields (`order_id`, `items`, `event`, `shop_id`, …) are rejected natively. + +### Custom event + +```dart +await sdk.tracking.custom( + 'subscribed_to_newsletter', + category: 'account', + label: 'footer_form', + value: 1, + time: DateTime.now().millisecondsSinceEpoch ~/ 1000, // UNIX seconds + customFields: const {'plan': 'weekly'}, +); +``` + +`customFields` is the free-form part: its entries are sent at the top level and +duplicated under `payload`. The SDK's own keys are reserved and rejected — +`event`, `time`, `category`, `label`, `value`, `source`, `payload`, `from`, +`code`, `stream`, `shop_id`, `did`, `sid`, `seance`, `segment`. + +### Attribution + +Events can carry the tool the user came from. Per call, for one event: + +```dart +await sdk.tracking.productView( + 'sku-1', + source: const TrackingSource( + type: TrackingSourceType.dynamicBlock, + code: 'main_page_block', + ), +); +``` + +`source` is accepted by `productView`, `addToCart` and `addToFavorites` — the +events a recommendation leads to. + +Or stored once, for the events that follow — the case where the source outlives +a single call, such as a user entering the catalog from a recommender block: + +```dart +await sdk.tracking.setSource( + const TrackingSource( + type: TrackingSourceType.dynamicBlock, + code: 'main_page_block', + ), +); + +// Carries source=main_page_block without being told to. +await sdk.tracking.productView('sku-1'); +``` + +The stored source lives natively per shop, survives restarts, and is kept for 48 +hours or until it is replaced. A per-call `source` wins over the stored one, and +an order is attributed by the `recommendedSource` of the `purchase` call itself. + +| `TrackingSourceType` | Wire value | Set by | +|---|---|---| +| `dynamicBlock` | `dynamic` | Dynamic recommender block | +| `chain` | `chain` | Recommendation chain | +| `bulk` | `bulk` | Bulk mailing | +| `transactional` | `transactional` | Transactional mailing | +| `instantSearch` | `instant_search` | Search suggestions | +| `fullSearch` | `full_search` | Full search results page | +| `stories` | `stories` | Stories block | +| `webPushDigest` | `web_push_digest` | Web push digest | + ## License MIT — see [LICENSE](LICENSE). From 6906a031038c082cb7bea541e777830f6f694426 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Wed, 2 Sep 2026 22:06:18 +0400 Subject: [PATCH 8/9] fix(ci): tag only the commit that bumps the version, sync only on release --- .github/workflows/deploy.yaml | 11 +++++++++++ .github/workflows/sync.yaml | 16 +++++++++------- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index 59c169e..2df1987 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -56,10 +56,21 @@ jobs: uses: actions/checkout@v4 with: token: ${{ steps.app-token.outputs.token }} + # Two commits, so the step below can diff HEAD against its parent. + fetch-depth: 2 - name: Tag if version is new if: steps.ready.outputs.ready == 'true' run: | + # Tag only the commit that introduced the version. This job runs on + # every push to the trunk, so most runs read a pubspec that was tagged + # releases ago — harmless while that tag exists, but the moment one is + # missing it would pin the old name onto a much later commit. + if ! git diff --name-only HEAD~1 HEAD | grep -qx 'pubspec.yaml'; then + echo "pubspec.yaml unchanged in HEAD — not a release commit" + exit 0 + fi + VERSION=$(grep '^version:' pubspec.yaml | awk '{print $2}') TAG="v$VERSION" if git ls-remote --exit-code --tags origin "refs/tags/$TAG" \ diff --git a/.github/workflows/sync.yaml b/.github/workflows/sync.yaml index b9c5033..a99df6b 100644 --- a/.github/workflows/sync.yaml +++ b/.github/workflows/sync.yaml @@ -1,19 +1,21 @@ name: Repository synchronization +# Triggered by the release commit itself rather than by the completion of the +# Deploy workflow. Deploy completes on every push to the trunk — once for the +# change, once again for the release commit — so a single release used to reach +# the mirror as two synchronization PRs carrying the same version. on: - workflow_run: - workflows: - - Deploy - types: - - completed + push: + branches: + - master workflow_dispatch: jobs: prepare: if: | + !contains(github.repository_owner, 'personaclick') && (github.event_name == 'workflow_dispatch' || - github.event.workflow_run.conclusion == 'success') && - !contains(github.repository_owner, 'personaclick') + startsWith(github.event.head_commit.message, 'chore(release):')) runs-on: ubuntu-latest outputs: replacements: ${{ steps.getReplacementsStep.outputs.replacements }} From 27e9e207b7af333273f3533b990ea36f6b2aec4c Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Wed, 2 Sep 2026 22:45:04 +0400 Subject: [PATCH 9/9] style: format the tracking changes `dart format --set-exit-if-changed` is part of PR checks and these four files were never run through it. --- example/integration_test/test_bundle.dart | 4 +-- example/lib/main.dart | 6 ++-- pigeons/personalization_api.dart | 32 +++++++++++++++++---- test/tracking_namespace_test.dart | 35 +++++++++++++---------- 4 files changed, 51 insertions(+), 26 deletions(-) diff --git a/example/integration_test/test_bundle.dart b/example/integration_test/test_bundle.dart index dd162f8..398b569 100644 --- a/example/integration_test/test_bundle.dart +++ b/example/integration_test/test_bundle.dart @@ -71,9 +71,9 @@ Future main() async { reportGroupStructure(dartTestGroup); }); -// START: GENERATED TEST GROUPS + // START: GENERATED TEST GROUPS group('tracking_events_test', tracking_events_test.main); -// END: GENERATED TEST GROUPS + // END: GENERATED TEST GROUPS final dartTestGroup = await testExplorationCompleter.future; final appService = PatrolAppService(topLevelDartTestGroup: dartTestGroup); diff --git a/example/lib/main.dart b/example/lib/main.dart index 79700e7..fdc94c2 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -113,10 +113,8 @@ final List<_TrackingDemo> _trackingDemos = [ key: 'tracking_sync_favorites', label: 'Tracking: sync favorites', method: 'syncFavorites', - call: (tracking) => tracking.syncFavorites(const [ - _demoItemId, - _demoSecondItemId, - ]), + call: (tracking) => + tracking.syncFavorites(const [_demoItemId, _demoSecondItemId]), ), _TrackingDemo( key: 'tracking_remove_from_favorites', diff --git a/pigeons/personalization_api.dart b/pigeons/personalization_api.dart index 78e7cec..0c6c074 100644 --- a/pigeons/personalization_api.dart +++ b/pigeons/personalization_api.dart @@ -262,7 +262,11 @@ abstract class PersonalizationHostApi { // `purchase` members. @async - void trackProductView(String itemId, TrackingSourceWire? source, String? shopId); + void trackProductView( + String itemId, + TrackingSourceWire? source, + String? shopId, + ); @async void trackCategoryView(String categoryId, String? shopId); @@ -271,7 +275,11 @@ abstract class PersonalizationHostApi { void trackSearch(String query, List? results, String? shopId); @async - void trackAddToCart(TrackingItemWire item, TrackingSourceWire? source, String? shopId); + void trackAddToCart( + TrackingItemWire item, + TrackingSourceWire? source, + String? shopId, + ); @async void trackSyncCart(List items, String? shopId); @@ -280,7 +288,11 @@ abstract class PersonalizationHostApi { void trackRemoveFromCart(String itemId, String? shopId); @async - void trackAddToFavorites(String itemId, TrackingSourceWire? source, String? shopId); + void trackAddToFavorites( + String itemId, + TrackingSourceWire? source, + String? shopId, + ); @async void trackSyncFavorites(List itemIds, String? shopId); @@ -289,10 +301,20 @@ abstract class PersonalizationHostApi { void trackRemoveFromFavorites(String itemId, String? shopId); @async - void trackStoryView(String storyId, String slideId, String? code, String? shopId); + void trackStoryView( + String storyId, + String slideId, + String? code, + String? shopId, + ); @async - void trackStoryClick(String storyId, String slideId, String? code, String? shopId); + void trackStoryClick( + String storyId, + String slideId, + String? code, + String? shopId, + ); /// Stores the attribution source natively for the next event. void trackSetSource(TrackingSourceWire source, String? shopId); diff --git a/test/tracking_namespace_test.dart b/test/tracking_namespace_test.dart index 317dd06..be6076a 100644 --- a/test/tracking_namespace_test.dart +++ b/test/tracking_namespace_test.dart @@ -34,7 +34,11 @@ void main() { setUp(() { // The SDK constructor claims the push channels; stub them so they stay quiet. - for (final event in ['onPushReceived', 'onPushDelivered', 'onPushClicked']) { + for (final event in [ + 'onPushReceived', + 'onPushDelivered', + 'onPushClicked', + ]) { mockChannel( flutterApiPrefix + event, (ByteData? _) async => codec.encodeMessage([]), @@ -137,7 +141,11 @@ void main() { await sdk.tracking.storyClick(storyId: '42', slideId: '3'); expect(viewed().sublist(0, 3), ['42', '3', 'main_stories']); - expect(clicked()[2], isNull, reason: 'native falls back to the loaded block'); + expect( + clicked()[2], + isNull, + reason: 'native falls back to the loaded block', + ); }); }); @@ -170,19 +178,16 @@ void main() { }); test('every source type has the wire value the API expects', () { - expect( - TrackingSourceType.values.map((e) => e.wireValue), - [ - 'dynamic', - 'chain', - 'bulk', - 'transactional', - 'instant_search', - 'full_search', - 'stories', - 'web_push_digest', - ], - ); + expect(TrackingSourceType.values.map((e) => e.wireValue), [ + 'dynamic', + 'chain', + 'bulk', + 'transactional', + 'instant_search', + 'full_search', + 'stories', + 'web_push_digest', + ]); }); });