diff --git a/README.md b/README.md index a8f658d..0fab9e1 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ repository. The tag is the version the plugin requires — the `REES46` dependen [`ios/rees46_sdk.podspec`](ios/rees46_sdk.podspec): ```ruby -pod 'REES46', :git => 'https://github.com/rees46/ios-sdk.git', :tag => 'v3.37.1' +pod 'REES46', :git => 'https://github.com/rees46/ios-sdk.git', :tag => 'v3.37.2' ``` `pod install` then runs as part of `flutter run`. Update the tag together with the @@ -99,7 +99,9 @@ synchronously** and starts native initialization in the background; calls issued right after are queued natively until the session is ready, so the handle is usable straight away. A broken setup surfaces as a `PlatformException` on the first call you make with it (`bad_args` for an empty `shopId`, `init_failed` if -native init threw). +native init threw). To learn the outcome of the init itself, await the handle's +`ready`: it fails with that `PlatformException`. On Android it completes as soon +as the native init starts. `shopId` is the only required field: diff --git a/android/build.gradle.kts b/android/build.gradle.kts index 9957070..2af68f3 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -87,7 +87,7 @@ android { dependencies { // REES46 Android SDK. - val rees46AndroidSdkVersion = "v2.47.0" + val rees46AndroidSdkVersion = "v2.48.0" add("rees46Implementation", "com.github.rees46:android-sdk:$rees46AndroidSdkVersion") // Used directly by the push presenter (NotificationCompat / ContextCompat). The native SDK 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 3be10ca..fd2b716 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 @@ -241,15 +241,7 @@ class Rees46FlutterSdkPlugin : try { sdk(shopId).productsManager.getProductInfo( itemId = itemId, - listener = object : OnApiCallbackListener() { - override fun onSuccess(response: org.json.JSONObject?) { - if (response != null) { - callback(Result.success(response.toString())) - } else { - callback(Result.failure(FlutterError("product_info_failed", "Empty response", null))) - } - } - } + listener = jsonObjectListener("product_info_failed", callback) ) } catch (t: Throwable) { callback(Result.failure(FlutterError("product_info_failed", t.message, null))) @@ -276,15 +268,7 @@ class Rees46FlutterSdkPlugin : limit = limit, page = page, filters = filters, - listener = object : OnApiCallbackListener() { - override fun onSuccess(response: org.json.JSONObject?) { - if (response != null) { - callback(Result.success(response.toString())) - } else { - callback(Result.failure(FlutterError("products_list_failed", "Empty response", null))) - } - } - } + listener = jsonObjectListener("products_list_failed", callback) ) } catch (t: Throwable) { callback(Result.failure(FlutterError("products_list_failed", t.message, null))) @@ -1264,3 +1248,28 @@ private class ShareSheetWatcher( const val NO_SHEET_MS = 1500L } } + +/** + * A listener for a call answered with JSON. Every answer completes the Dart `Future` — an object, + * an array, an error: a listener with only `onSuccess(JSONObject)` left it waiting for good. + */ +internal fun jsonObjectListener(errorCode: String, callback: (Result) -> Unit) = + object : OnApiCallbackListener() { + override fun onSuccess(response: org.json.JSONObject?) { + if (response != null) { + callback(Result.success(response.toString())) + } else { + callback(Result.failure(FlutterError(errorCode, "Empty response", null))) + } + } + + override fun onSuccess(response: org.json.JSONArray) { + callback(Result.success(response.toString())) + } + + override fun onError(code: Int, msg: String?) { + // The SDK passes an error answer's body, empty for most: the status says what failed. + val message = msg?.takeIf { it.isNotBlank() } ?: "error $code" + callback(Result.failure(FlutterError(errorCode, message, null))) + } + } diff --git a/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/JsonObjectListenerTest.kt b/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/JsonObjectListenerTest.kt new file mode 100644 index 0000000..daba9c8 --- /dev/null +++ b/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/JsonObjectListenerTest.kt @@ -0,0 +1,59 @@ +package com.rees46.rees46_flutter_sdk + +import com.rees46.rees46_flutter_sdk.pigeon.FlutterError +import org.json.JSONArray +import org.mockito.Mockito +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * `getProductInfo` and `getProductsList` answer through [jsonObjectListener]: the Dart `Future` + * completes on an error and on any answer. A listener with only `onSuccess` left it waiting for good. + */ +internal class JsonObjectListenerTest { + + @Test + fun anErrorCompletesTheCallWithTheError() { + val results = mutableListOf>() + + jsonObjectListener("products_list_failed") { results += it }.onError(500, "server error") + + assertEquals(1, results.size, "the call never completed") + val error = results.single().exceptionOrNull() as FlutterError + assertEquals("products_list_failed", error.code) + assertEquals("server error", error.message) + } + + @Test + fun anErrorWithAnEmptyBodyNamesItsStatus() { + val results = mutableListOf>() + + // The SDK hands over the error answer's body, empty for most errors. + jsonObjectListener("product_info_failed") { results += it }.onError(404, "") + + val error = results.single().exceptionOrNull() as FlutterError + assertEquals("product_info_failed", error.code) + assertEquals("error 404", error.message) + } + + @Test + fun anArrayAnswerCompletesTheCall() { + val results = mutableListOf>() + val array = Mockito.mock(JSONArray::class.java) + Mockito.`when`(array.toString()).thenReturn("[]") + + jsonObjectListener("products_list_failed") { results += it }.onSuccess(array) + + assertEquals("[]", results.single().getOrNull()) + } + + @Test + fun anEmptyAnswerCompletesTheCallWithAnError() { + val results = mutableListOf>() + + jsonObjectListener("product_info_failed") { results += it }.onSuccess(null as org.json.JSONObject?) + + assertTrue(results.single().isFailure) + } +} diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index a3a47ac..d050793 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -10,6 +10,7 @@ 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 */; }; + 450B506B499A1CF4D761FCF0 /* CatalogBridgeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A7476EABE9FDB3B87ADF52 /* CatalogBridgeTests.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 */; }; @@ -56,6 +57,7 @@ 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 = ""; }; + F6A7476EABE9FDB3B87ADF52 /* CatalogBridgeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatalogBridgeTests.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 = ""; }; @@ -118,6 +120,7 @@ children = ( 331C807B294A618700263BE5 /* RunnerTests.swift */, D1B0FE012F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift */, + F6A7476EABE9FDB3B87ADF52 /* CatalogBridgeTests.swift */, ); path = RunnerTests; sourceTree = ""; @@ -481,6 +484,7 @@ files = ( 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, D1B0FE022F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift in Sources */, + 450B506B499A1CF4D761FCF0 /* CatalogBridgeTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/example/ios/RunnerTests/CatalogBridgeTests.swift b/example/ios/RunnerTests/CatalogBridgeTests.swift new file mode 100644 index 0000000..568a9bd --- /dev/null +++ b/example/ios/RunnerTests/CatalogBridgeTests.swift @@ -0,0 +1,123 @@ +import Flutter +import UIKit +import XCTest + +@testable import REES46 +@testable import rees46_sdk + +/// The catalog calls of the Swift bridge: which native call a Dart call reaches, and what of the +/// native answer reaches Dart. +final class CatalogBridgeTests: XCTestCase { + + private let shopId = "bridge-shop" + private var native: RecordingSDK! + private var plugin: PersonalizationHostApiImpl! + + override func setUp() { + super.setUp() + native = RecordingSDK(shopId: shopId) + SdkRegistry.shared.register(shopId: shopId, sdk: native) + plugin = PersonalizationHostApiImpl(popupApi: PersonalizationPopupFlutterApi(binaryMessenger: SilentMessenger())) + } + + override func tearDown() { + SdkRegistry.shared.reset() + super.tearDown() + } + + func test_instantSearch_isTheNativeSuggest_notTheFullSearch() { + plugin.searchInstant(query: "shoes", paramsJson: #"{"locations":"msk","excluded_brands":["b1"]}"#, shopId: shopId) { _ in } + + XCTAssertEqual(native.suggestCalls.map(\.query), ["shoes"]) + XCTAssertEqual(native.suggestCalls.first?.locations, "msk") + XCTAssertEqual(native.suggestCalls.first?.excludedBrands ?? [], ["b1"]) + XCTAssertTrue(native.searchQueries.isEmpty, "instant search went out as the full search") + } + + func test_categoryAnswer_carriesTheFacetsAndThePriceRange() { + let answer = CategoryResponse(json: [ + "products_total": 2, + "products": [], + "brands": [["name": "Acme", "count": 2]], + "filters": ["Цвет": ["count": 2, "values": ["Красный": 2]]], + "price_range": ["min": 100.0, "max": 900.0], + "categories": [["id": "7", "name": "Обувь", "count": 2]], + ]) + + let dict = PersonalizationHostApiImpl._categoryResponseToDict(answer) + + let filters = dict["filters"] as? [String: [String: Any]] + XCTAssertEqual(filters?["Цвет"]?["values"] as? [String: Int], ["Красный": 2]) + let priceRange = dict["price_range"] as? [String: Double] + XCTAssertEqual(priceRange?["min"], 100) + XCTAssertEqual(priceRange?["max"], 900) + XCTAssertTrue(JSONSerialization.isValidJSONObject(dict)) + } +} + +/// Takes the popup channel's messages and answers none: the catalog calls do not use it. +private final class SilentMessenger: NSObject, FlutterBinaryMessenger { + func send(onChannel channel: String, message: Data?) {} + func send(onChannel channel: String, message: Data?, binaryReply callback: FlutterBinaryReply? = nil) {} + func setMessageHandlerOnChannel(_ channel: String, binaryMessageHandler handler: FlutterBinaryMessageHandler? = nil) -> FlutterBinaryMessengerConnection { 0 } + func cleanUpConnection(_ connection: FlutterBinaryMessengerConnection) {} +} + +/// A native SDK that records the search calls and answers none; the rest is a no-op. +private final class RecordingSDK: PersonalizationSDK { + struct Suggest { + let query: String + let locations: String? + let excludedBrands: [String]? + } + + private(set) var suggestCalls: [Suggest] = [] + private(set) var searchQueries: [String] = [] + + var shopId: String + var deviceId = "bridge-device" + var userSeance = "bridge-seance" + var segment = "A" + var storiesCode: String? + let sessionQueue = SessionQueue(name: "bridge-tests") + var parentViewController: UIViewController? + var urlSession: URLSession = .shared + var popupPresentationDelegate: PopupPresentationDelegate? + var enableAutoPopupPresentation = false + lazy var popupPresenter: PopupPresenter = PopupPresenter(sdk: self) + + init(shopId: String) { self.shopId = shopId } + + func suggest(query: String, locations: String?, excludedMerchants: [String]?, excludedBrands: [String]?, timeOut: Double?, extended: String?, completion: @escaping (Result) -> Void) { + suggestCalls.append(Suggest(query: query, locations: locations, excludedBrands: excludedBrands)) + } + + func search(query: String, limit: Int?, offset: Int?, categoryLimit: Int?, brandLimit: Int?, categories: [Int]?, extended: String?, sortBy: String?, sortDir: String?, locations: String?, excludedMerchants: [String]?, excludedBrands: [String]?, brands: String?, filters: [String: Any]?, priceMin: Double?, priceMax: Double?, colors: [String]?, fashionSizes: [String]?, exclude: String?, email: String?, timeOut: Double?, disableClarification: Bool?, completion: @escaping (Result) -> Void) { + searchQueries.append(query) + } + + func postRequest(path: String, params: [String: Any], completion: @escaping (Result<[String: Any], SdkError>) -> Void) {} + func getRequest(path: String, params: [String: String], _ isInit: Bool, completion: @escaping (Result<[String: Any], SdkError>) -> Void) {} + func configureURLSession(configuration: URLSessionConfiguration) {} + func generateString(array: [String]) -> String { "" } + func trackPurchase(_ request: PurchaseTrackingRequest, recommendedBy: RecomendedBy?, completion: @escaping (Result) -> Void) {} + func trackSource(source: RecommendedByCase, code: String) {} + func trackPopupShown(popupId: Int, completion: @escaping (Result) -> Void) {} + func getProductInfo(id: String, completion: @escaping (Result) -> Void) {} + func getLastOrderProducts(completion: @escaping (Result) -> Void) {} + func getLoyaltyStatus(identifier: String, completion: @escaping (Result) -> Void) {} + func getProfile(completion: @escaping (Result) -> Void) {} + func getProductCounters(item: String, completion: @escaping (Result) -> Void) {} + func getDeviceId() -> String { deviceId } + func setParentViewController(controller: UIViewController, completion: @escaping () -> Void) {} + func getNotificationWidget() -> NotificationWidget? { nil } + func getSession() -> String { userSeance } + func getCurrentSegment() -> String { segment } + func getShopId() -> String { shopId } + func searchBlank(completion: @escaping (Result) -> Void) {} + func notificationDelivered(type: String, code: String, completion: @escaping (Result) -> Void) {} + func notificationReceived(type: String, code: String, completion: @escaping (Result) -> Void) {} + func getStories(code: String, completion: @escaping (Result) -> Void) {} + func configuration() -> SdkConfiguration.Type { SdkConfiguration.self } + func sendIDFARequest(idfa: UUID, completion: @escaping (Result) -> Void) {} +} diff --git a/ios/rees46_sdk.podspec b/ios/rees46_sdk.podspec index b762d25..ff84a82 100644 --- a/ios/rees46_sdk.podspec +++ b/ios/rees46_sdk.podspec @@ -20,7 +20,7 @@ Flutter plugin wrapper around REES46 native SDK. # Keep in step with the dependency in rees46_sdk/Package.swift. CocoaPods trunk is # read-only, so a version newer than the last one there resolves only through the # app's Podfile (see "iOS" in README.md). - s.dependency 'REES46', '3.37.1' + s.dependency 'REES46', '3.37.2' s.platform = :ios, '13.0' # Flutter.framework does not contain a i386 slice. diff --git a/ios/rees46_sdk/Package.swift b/ios/rees46_sdk/Package.swift index 1b43949..0389e89 100644 --- a/ios/rees46_sdk/Package.swift +++ b/ios/rees46_sdk/Package.swift @@ -13,7 +13,7 @@ let package = Package( ], dependencies: [ // Keep in step with the dependency in ../rees46_sdk.podspec. - .package(url: "https://github.com/rees46/ios-sdk.git", exact: "3.37.1") + .package(url: "https://github.com/rees46/ios-sdk.git", exact: "3.37.2") ], targets: [ .target( diff --git a/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift b/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift index 8afd3df..5cd1185 100644 --- a/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift +++ b/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift @@ -373,15 +373,10 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { "products_total": r.productsTotal, "categories": r.categories.map { _categoryToDict($0) }, ] - if let pr = r.priceRange { - dict["price_range"] = ["min": pr.min, "max": pr.max] - } + _addFacets(to: &dict, priceRange: r.priceRange, filters: r.filters) if let brands = r.brands { dict["brands"] = brands } - if let filters = r.filters { - dict["filters"] = filters.mapValues { ["count": $0.count, "values": $0.values] as [String: Any] } - } return dict } @@ -470,29 +465,15 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { let locations = p?["locations"] as? String let excludedBrands = p?["excluded_brands"] as? [String] - sdk.search( + // Instant search is the native `suggest` (`type=instant_search`), as on Android; `search` + // sent the full search. + sdk.suggest( query: query, - limit: nil, - offset: nil, - categoryLimit: nil, - brandLimit: nil, - categories: nil, - extended: nil, - sortBy: nil, - sortDir: nil, locations: locations, excludedMerchants: nil, excludedBrands: excludedBrands, - brands: nil, - filters: nil, - priceMin: nil, - priceMax: nil, - colors: nil, - fashionSizes: nil, - exclude: nil, - email: nil, timeOut: nil, - disableClarification: nil + extended: nil ) { result in switch result { case .success(let response): @@ -594,15 +575,10 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { "products_total": r.productsTotal, "queries": r.queries.map { ["name": $0.name, "url": $0.url] }, ] - if let pr = r.priceRange { - dict["price_range"] = ["min": pr.min, "max": pr.max] - } + _addFacets(to: &dict, priceRange: r.priceRange, filters: r.filters) if let brands = r.brands { dict["brands"] = brands } - if let filters = r.filters { - dict["filters"] = filters.mapValues { ["count": $0.count, "values": $0.values] as [String: Any] } - } if let industrial = r.industrialFilters { dict["industrial_filters"] = [ "colors": industrial.fashionColors.map { ["color": $0.color, "count": $0.count] }, @@ -968,8 +944,21 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { return d } - private static func _categoryResponseToDict(_ r: CategoryResponse) -> [String: Any] { - return [ + /// The facets of a listing — its price range and the shop's filters — as the Dart models read + /// them. The search, the products list and the category send the same shape. + private static func _addFacets(to dict: inout [String: Any], priceRange: PriceRange?, filters: [String: Filter]?) { + if let pr = priceRange { + dict["price_range"] = ["min": pr.min, "max": pr.max] + } + if let filters = filters { + dict["filters"] = filters.mapValues { ["count": $0.count, "values": $0.values] as [String: Any] } + } + } + + /// The category listing for the Dart `CategoryResponse`: the facets and the price range go + /// along, as in the search and the products list. + static func _categoryResponseToDict(_ r: CategoryResponse) -> [String: Any] { + var dict: [String: Any] = [ "products_total": r.productsTotal, "products": r.products.map { _categoryProductToDict($0) }, "brands": r.brands.compactMap { b -> [String: Any]? in @@ -979,6 +968,8 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { return d }, ] + _addFacets(to: &dict, priceRange: r.priceRange, filters: r.filters) + return dict } private static func _collectionResponseToDict(_ r: CollectionResponse) -> [String: Any] { @@ -1143,8 +1134,9 @@ 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. + // Most methods hand straight to the native `tracking` namespace of the resolved instance; + // `trackEvent`, `trackPopupShown` and `trackPurchase` go to the SDK's own methods of those + // names, which send the same requests. The wire models are translated one to one. func trackProductView( itemId: String, diff --git a/lib/src/category/category_response.dart b/lib/src/category/category_response.dart index b2c5afe..d45918f 100644 --- a/lib/src/category/category_response.dart +++ b/lib/src/category/category_response.dart @@ -11,9 +11,6 @@ export '../products/products_list_response.dart' show Product; /// with a category as with full search. Products are parsed with the shared /// [Product] model (Android returns a richer product than iOS; the parser tolerates /// the missing fields). -/// -/// On iOS only [brands] arrive for now: the native category model has no filters -/// or price range. class CategoryResponse { final int productsTotal; final List products; diff --git a/lib/src/multi_instance/rees46.dart b/lib/src/multi_instance/rees46.dart index a424142..5cd2bce 100644 --- a/lib/src/multi_instance/rees46.dart +++ b/lib/src/multi_instance/rees46.dart @@ -21,11 +21,12 @@ typedef REES46SdkFactory = PersonalizationSdk Function(REES46Config config); /// ```dart /// // Single shop: /// final sdk = REES46.initialize(REES46Config(shopId: 'SHOP_ID')); -/// sdk.trackEvent('category', ...); +/// await sdk.ready; // optional: the outcome of the native init +/// sdk.tracking.categoryView('category-1'); /// /// // Several shops, initialized lazily on first use: /// REES46.registerShops([REES46Config(shopId: 'shop-a'), REES46Config(shopId: 'shop-b')]); -/// REES46.getInstance('shop-a').trackEvent('category', ...); +/// REES46.getInstance('shop-a').tracking.categoryView('category-1'); /// ``` /// /// ## Why the facade holds a shop-id mirror @@ -38,11 +39,8 @@ typedef REES46SdkFactory = PersonalizationSdk Function(REES46Config config); /// contract synchronously, identically to native. The native `SdkRegistry` /// remains the source of truth for the instances themselves. /// -/// Per-call routing to a specific native instance (threading `shopId` through -/// every Pigeon call) lands once the native `REES46` facade ships in the -/// consumed artifacts — see the plan (`Multi-instance — Flutter Plan`, step F3). -/// Until then single-shop [initialize] is fully functional and the resolution -/// contract below is complete and tested. +/// Every call of a handle carries its `shopId` to the native instance of that +/// shop. class REES46 { REES46._(); @@ -60,9 +58,12 @@ class REES46 { static PersonalizationSdk _defaultFactory(REES46Config config) { final sdk = PersonalizationSdk(shopId: config.shopId); - // F1: delegates to the existing single-shop native init. Per-call `shopId` - // routing to the native `REES46` facade lands in plan step F3. - sdk.initialize(config.toSdkInitConfig()); + // The handle goes back at once; the outcome is in [PersonalizationSdk.ready]. + // Listened to here, a failed init is not an unhandled error when the app does + // not await `ready`. + sdk.initialize(config.toSdkInitConfig()).catchError((Object error) { + debugPrint('REES46: init of shop ${config.shopId} failed: $error'); + }); return sdk; } @@ -72,7 +73,8 @@ class REES46 { /// Initializes an SDK instance for [config] immediately and returns it. The /// instance is registered, so it is also reachable via [getInstance]. Any - /// pending registration for the same shop is cleared. + /// pending registration for the same shop is cleared. The native init goes on + /// after the handle is back; its outcome is [PersonalizationSdk.ready]. static PersonalizationSdk initialize(REES46Config config) => _instance._initialize(config); diff --git a/lib/src/personalization_sdk.dart b/lib/src/personalization_sdk.dart index 8a11eb8..9cd8258 100644 --- a/lib/src/personalization_sdk.dart +++ b/lib/src/personalization_sdk.dart @@ -111,9 +111,18 @@ class PersonalizationSdk { // The native side reports popups under the shop id it was initialized with. PopupDispatcher.instance.register(config.shopId, _popups); PopupsV3Hooks.initialized(tracking, config); - return _initHandler.initialize(config); + return _ready = _initHandler.initialize(config); } + Future? _ready; + + /// The outcome of the native initialization: completes when it is done, with its + /// error when it fails. [REES46.initialize] hands the handle back at once — await + /// this to learn whether the shop is up. On Android the native SDK does not report + /// when its initialization ends, so it completes as soon as the init starts. Before + /// [initialize] is called it completes at once. + Future get ready => _ready ?? Future.value(); + /// Whether the SDK shows popups by itself: the server popups while no [onPopup] is /// set, and the other popups the SDK shows by itself (one shown by hand is shown all /// the same). @@ -287,9 +296,9 @@ class PersonalizationSdk { /// response lists them in [CategoryResponse.filters]. /// /// [priceMin], [priceMax], [sortBy] (`price`, `discount`, …) and [sortDir] - /// (`asc` / `desc`) are sent, but not applied yet: the native SDKs this plugin - /// is built against take no price range or sort for a category. They apply with - /// no change to the call once the plugin moves to native releases that do. + /// (`asc` / `desc`) narrow and order the listing. The response carries the + /// shop's facets ([CategoryResponse.filters]) and the price range of the + /// listing ([CategoryResponse.priceRange]) on both platforms. Future getCategory( String category, { int? limit, diff --git a/lib/src/search/search_params.dart b/lib/src/search/search_params.dart index 1c57076..f2c3104 100644 --- a/lib/src/search/search_params.dart +++ b/lib/src/search/search_params.dart @@ -74,10 +74,8 @@ class SearchParams { /// Parameters for [PersonalizationSdk.searchInstant]. /// -/// Android passes these directly to `searchManager.searchInstant()`. -/// iOS passes them to `sdk.search()` with the remaining fields set to nil. -/// -/// Excluded Android-only params: `excludedMerchants`. +/// The bridges pass them to the native instant search: `searchManager.searchInstant()` on +/// Android, `sdk.suggest()` on iOS. class SearchInstantParams { final String? locations; final List? excludedBrands; diff --git a/lib/src/tracking/tracking_api.dart b/lib/src/tracking/tracking_api.dart index 79eea4c..d64fc20 100644 --- a/lib/src/tracking/tracking_api.dart +++ b/lib/src/tracking/tracking_api.dart @@ -8,8 +8,10 @@ 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. +/// An event fired from Dart is the same request the native SDKs send. Most methods go to the +/// method of the same name in the native `tracking` namespace; on iOS [custom], [popupShown] and +/// [purchase] go to the native SDK's own `trackEvent`, `trackPopupShown` and `trackPurchase`, +/// which send the same requests. class TrackingApi { TrackingApi( this._api, diff --git a/test/multi_instance/init_outcome_test.dart b/test/multi_instance/init_outcome_test.dart new file mode 100644 index 0000000..5fcd279 --- /dev/null +++ b/test/multi_instance/init_outcome_test.dart @@ -0,0 +1,57 @@ +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; + +const _initChannel = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.initialize'; + +// `REES46.initialize` hands the shop's handle back at once and the native init goes on. Its +// outcome is the handle's `ready`; a failed init is not left as an unhandled error. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + void answerInit(List reply) { + messenger.setMockMessageHandler( + _initChannel, + (_) async => + pigeon.PersonalizationHostApi.pigeonChannelCodec.encodeMessage(reply), + ); + } + + tearDown(() { + messenger.setMockMessageHandler(_initChannel, null); + REES46.reset(); + }); + + test('a failed native init is not left as an unhandled error', () async { + answerInit(['init_failed', 'shop refused', null]); + + REES46.initialize(const REES46Config(shopId: 'refused-shop')); + await pumpEventQueue(); + }); + + test('a failed native init reaches ready', () async { + answerInit(['init_failed', 'shop refused', null]); + + final sdk = REES46.initialize(const REES46Config(shopId: 'refused-shop')); + + await expectLater( + sdk.ready, + throwsA( + isA().having((e) => e.code, 'code', 'init_failed'), + ), + ); + }); + + test('a native init that succeeds completes ready', () async { + answerInit([]); + + final sdk = REES46.initialize(const REES46Config(shopId: 'live-shop')); + + await expectLater(sdk.ready, completes); + }); +}