Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion android/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand All @@ -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)))
Expand Down Expand Up @@ -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<String>) -> 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)))
}
}
Original file line number Diff line number Diff line change
@@ -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<Result<String>>()

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<Result<String>>()

// 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<Result<String>>()
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<Result<String>>()

jsonObjectListener("product_info_failed") { results += it }.onSuccess(null as org.json.JSONObject?)

assertTrue(results.single().isFailure)
}
}
4 changes: 4 additions & 0 deletions example/ios/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -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 */; };
Expand Down Expand Up @@ -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 = "<group>"; };
331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
D1B0FE012F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackingBridgeTests.swift; sourceTree = "<group>"; };
F6A7476EABE9FDB3B87ADF52 /* CatalogBridgeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatalogBridgeTests.swift; sourceTree = "<group>"; };
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 = "<group>"; };
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 = "<group>"; };
Expand Down Expand Up @@ -118,6 +120,7 @@
children = (
331C807B294A618700263BE5 /* RunnerTests.swift */,
D1B0FE012F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift */,
F6A7476EABE9FDB3B87ADF52 /* CatalogBridgeTests.swift */,
);
path = RunnerTests;
sourceTree = "<group>";
Expand Down Expand Up @@ -481,6 +484,7 @@
files = (
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */,
D1B0FE022F0A1B2C3D4E5F70 /* TrackingBridgeTests.swift in Sources */,
450B506B499A1CF4D761FCF0 /* CatalogBridgeTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
123 changes: 123 additions & 0 deletions example/ios/RunnerTests/CatalogBridgeTests.swift
Original file line number Diff line number Diff line change
@@ -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<SearchResponse, SdkError>) -> 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<SearchResponse, SdkError>) -> 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, SdkError>) -> Void) {}
func trackSource(source: RecommendedByCase, code: String) {}
func trackPopupShown(popupId: Int, completion: @escaping (Result<Void, SdkError>) -> Void) {}
func getProductInfo(id: String, completion: @escaping (Result<ProductInfo, SdkError>) -> Void) {}
func getLastOrderProducts(completion: @escaping (Result<LastOrderProductsResponse, SdkError>) -> Void) {}
func getLoyaltyStatus(identifier: String, completion: @escaping (Result<LoyaltyStatusResponse, SdkError>) -> Void) {}
func getProfile(completion: @escaping (Result<GetProfileResponse, SdkError>) -> Void) {}
func getProductCounters(item: String, completion: @escaping (Result<ProductCountersResponse, SdkError>) -> 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<SearchBlankResponse, SdkError>) -> Void) {}
func notificationDelivered(type: String, code: String, completion: @escaping (Result<Void, SdkError>) -> Void) {}
func notificationReceived(type: String, code: String, completion: @escaping (Result<Void, SdkError>) -> Void) {}
func getStories(code: String, completion: @escaping (Result<StoryContent, SdkError>) -> Void) {}
func configuration() -> SdkConfiguration.Type { SdkConfiguration.self }
func sendIDFARequest(idfa: UUID, completion: @escaping (Result<InitResponse, SdkError>) -> Void) {}
}
2 changes: 1 addition & 1 deletion ios/rees46_sdk.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion ios/rees46_sdk/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading