diff --git a/.swiftlint.yml b/.swiftlint.yml index 4438158e..a9410d0d 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -11,9 +11,19 @@ included: - REES46/Classes/Sdk - REES46/Classes/Notifications - REES46/Classes/Tracking + - REES46/Classes/Cart + - REES46/Classes/Stories/API + - REES46/Classes/Predict + - REES46/Classes/Loyalty + - REES46/Classes/Sliders + - REES46/Classes/Reviews - REES46/Classes/Search + - REES46/Classes/Products + - REES46/Classes/Collections + - REES46/Classes/Recommendations - REES46/Classes/Profile - REES46/Classes/Subscription + - REES46/Classes/Segments - REES46/Classes/Infrastructure - REES46/Classes/Domain - REES46/Classes/Errors diff --git a/DemoApp/REES46.xcodeproj/project.pbxproj b/DemoApp/REES46.xcodeproj/project.pbxproj index 1cafceb6..a3b1706d 100644 --- a/DemoApp/REES46.xcodeproj/project.pbxproj +++ b/DemoApp/REES46.xcodeproj/project.pbxproj @@ -74,6 +74,12 @@ 594249BD4A084A1291AC0F14 /* CoreGapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89006D3670A5461885FC8A49 /* CoreGapTests.swift */; }; 681654724B174266BAACBDED /* LegacyParityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 342B105ADE434053B9010136 /* LegacyParityTests.swift */; }; 338497F3341748CF98532803 /* LogContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAFAFC3C25EF4765AEFF7116 /* LogContractTests.swift */; }; + ED4F1F73046637700C291754 /* ContractFixtures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5303A085EFA968B3C5E5E3ED /* ContractFixtures.swift */; }; + 99279C14206F92436874AAF2 /* NamespaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2594C3E42C2DED097333738A /* NamespaceRequestTests.swift */; }; + B848252E6A7B409E541A0448 /* NotificationsNamespaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BEED1DF803C0BFAAA2076B5 /* NotificationsNamespaceTests.swift */; }; + A484DC14FFC3DBEE88C44402 /* StoriesPredictLoyaltySlidersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F9A6D6CEF6BF5A0DFE5E7F5 /* StoriesPredictLoyaltySlidersTests.swift */; }; + BA2C8CBC07DA3021B357CFBC /* ReviewsFixtureCalls.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CA5AE7365436E9358EAC2AC /* ReviewsFixtureCalls.swift */; }; + 0D3AA528DCB53AF45AC77B9B /* ReviewsRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66F14F2D81655D203B087AA1 /* ReviewsRequestTests.swift */; }; AD0C7CD9B2C94E6C92EBD76F /* CoreDecisionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3DA0647150D46F59A45438E /* CoreDecisionTests.swift */; }; 185F659CDBE840968B74E646 /* CoreScenarioHarness.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72D6FEB5A43445D6A6B07DF7 /* CoreScenarioHarness.swift */; }; F82D9C817E27477A8B593D7E /* CoreSessionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44D8CA2308D2429180F2E4D5 /* CoreSessionTests.swift */; }; @@ -90,9 +96,13 @@ 95300191D926BCFFE887810F /* StubServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B4279E67656DEE2726F5841 /* StubServer.swift */; }; 7009DFFB0CC821D8EC72C77F /* LiveServerGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9781E60804825F760ADE3929 /* LiveServerGuard.swift */; }; BACD7D59FBD148E5323B1DF8 /* SearchContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44467285AA63CD86B8846549 /* SearchContractTests.swift */; }; + 035807D5C47B5617327F47D1 /* AgentSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BAE8CAA1C23AD95B3A659DB /* AgentSearchTests.swift */; }; EE982672942F5A449BD9638A /* SubscriptionContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B9603C298AB34B96D5A8DFC /* SubscriptionContractTests.swift */; }; D3AE962D3B176281495DE5D5 /* LoyaltyAndOrdersContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50C0DF3B30B0FE718D4EF061 /* LoyaltyAndOrdersContractTests.swift */; }; + 34E845DAF87173E0BF25FAB9 /* PredictContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 062EA46B15C13F384C2591CE /* PredictContractTests.swift */; }; + 6844E30F231FF22F293ABDC0 /* ClientNamespaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB7C9148EBDAEAFFE3F6B662 /* ClientNamespaceTests.swift */; }; AADD17FBB7174736D09B40FA /* CatalogContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6373AE16A13EA446ECFA658A /* CatalogContractTests.swift */; }; + 2D62BB4EF7EDEC67BEFDB85A /* CatalogNamespaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAD942DCBA67544649FFB028 /* CatalogNamespaceTests.swift */; }; 2E817004C18D1F584765B326 /* ContractTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4980EAC03CBF4DB6CD3DE938 /* ContractTestCase.swift */; }; 7587149C2C6CDF62008E5E4E /* SDKConfigProviderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7587149B2C6CDF62008E5E4E /* SDKConfigProviderTests.swift */; }; 758714A82C6CF1EB008E5E4E /* AppEnvironments.struct.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758714A62C6CF1EB008E5E4E /* AppEnvironments.struct.swift */; }; @@ -345,6 +355,12 @@ 89006D3670A5461885FC8A49 /* CoreGapTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CoreGapTests.swift; sourceTree = ""; }; 342B105ADE434053B9010136 /* LegacyParityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LegacyParityTests.swift; sourceTree = ""; }; DAFAFC3C25EF4765AEFF7116 /* LogContractTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LogContractTests.swift; sourceTree = ""; }; + 5303A085EFA968B3C5E5E3ED /* ContractFixtures.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ContractFixtures.swift; path = ../Tests/REES46CoreTests/ContractFixtures.swift; sourceTree = SOURCE_ROOT; }; + 2594C3E42C2DED097333738A /* NamespaceRequestTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NamespaceRequestTests.swift; sourceTree = ""; }; + 9BEED1DF803C0BFAAA2076B5 /* NotificationsNamespaceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NotificationsNamespaceTests.swift; sourceTree = ""; }; + 5F9A6D6CEF6BF5A0DFE5E7F5 /* StoriesPredictLoyaltySlidersTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StoriesPredictLoyaltySlidersTests.swift; sourceTree = ""; }; + 4CA5AE7365436E9358EAC2AC /* ReviewsFixtureCalls.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReviewsFixtureCalls.swift; path = ../Tests/REES46CoreTests/ReviewsFixtureCalls.swift; sourceTree = SOURCE_ROOT; }; + 66F14F2D81655D203B087AA1 /* ReviewsRequestTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ReviewsRequestTests.swift; sourceTree = ""; }; D3DA0647150D46F59A45438E /* CoreDecisionTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CoreDecisionTests.swift; sourceTree = ""; }; 72D6FEB5A43445D6A6B07DF7 /* CoreScenarioHarness.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CoreScenarioHarness.swift; sourceTree = ""; }; 44D8CA2308D2429180F2E4D5 /* CoreSessionTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CoreSessionTests.swift; sourceTree = ""; }; @@ -361,9 +377,13 @@ 1B4279E67656DEE2726F5841 /* StubServer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StubServer.swift; sourceTree = ""; }; 9781E60804825F760ADE3929 /* LiveServerGuard.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LiveServerGuard.swift; sourceTree = ""; }; 44467285AA63CD86B8846549 /* SearchContractTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SearchContractTests.swift; sourceTree = ""; }; + 5BAE8CAA1C23AD95B3A659DB /* AgentSearchTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AgentSearchTests.swift; sourceTree = ""; }; 1B9603C298AB34B96D5A8DFC /* SubscriptionContractTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SubscriptionContractTests.swift; sourceTree = ""; }; 50C0DF3B30B0FE718D4EF061 /* LoyaltyAndOrdersContractTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LoyaltyAndOrdersContractTests.swift; sourceTree = ""; }; + 062EA46B15C13F384C2591CE /* PredictContractTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PredictContractTests.swift; sourceTree = ""; }; + CB7C9148EBDAEAFFE3F6B662 /* ClientNamespaceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ClientNamespaceTests.swift; sourceTree = ""; }; 6373AE16A13EA446ECFA658A /* CatalogContractTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CatalogContractTests.swift; sourceTree = ""; }; + BAD942DCBA67544649FFB028 /* CatalogNamespaceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CatalogNamespaceTests.swift; sourceTree = ""; }; 4980EAC03CBF4DB6CD3DE938 /* ContractTestCase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ContractTestCase.swift; sourceTree = ""; }; B57812A2700376CF0EC5D913 /* Pods_REES46Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_REES46Tests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; B5AD555A428611EB01D95215 /* PushPayloadParserTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PushPayloadParserTests.swift; sourceTree = ""; }; @@ -561,6 +581,12 @@ 89006D3670A5461885FC8A49 /* CoreGapTests.swift */, 342B105ADE434053B9010136 /* LegacyParityTests.swift */, DAFAFC3C25EF4765AEFF7116 /* LogContractTests.swift */, + 5303A085EFA968B3C5E5E3ED /* ContractFixtures.swift */, + 2594C3E42C2DED097333738A /* NamespaceRequestTests.swift */, + 9BEED1DF803C0BFAAA2076B5 /* NotificationsNamespaceTests.swift */, + 5F9A6D6CEF6BF5A0DFE5E7F5 /* StoriesPredictLoyaltySlidersTests.swift */, + 4CA5AE7365436E9358EAC2AC /* ReviewsFixtureCalls.swift */, + 66F14F2D81655D203B087AA1 /* ReviewsRequestTests.swift */, D3DA0647150D46F59A45438E /* CoreDecisionTests.swift */, 72D6FEB5A43445D6A6B07DF7 /* CoreScenarioHarness.swift */, 44D8CA2308D2429180F2E4D5 /* CoreSessionTests.swift */, @@ -577,9 +603,13 @@ 1B4279E67656DEE2726F5841 /* StubServer.swift */, 9781E60804825F760ADE3929 /* LiveServerGuard.swift */, 44467285AA63CD86B8846549 /* SearchContractTests.swift */, + 5BAE8CAA1C23AD95B3A659DB /* AgentSearchTests.swift */, 1B9603C298AB34B96D5A8DFC /* SubscriptionContractTests.swift */, 50C0DF3B30B0FE718D4EF061 /* LoyaltyAndOrdersContractTests.swift */, + 062EA46B15C13F384C2591CE /* PredictContractTests.swift */, + CB7C9148EBDAEAFFE3F6B662 /* ClientNamespaceTests.swift */, 6373AE16A13EA446ECFA658A /* CatalogContractTests.swift */, + BAD942DCBA67544649FFB028 /* CatalogNamespaceTests.swift */, 4980EAC03CBF4DB6CD3DE938 /* ContractTestCase.swift */, 6493F884A898C533B4817F97 /* SdkRegistryTests.swift */, 50CF8287AA77C0C1D6CD5046 /* StoragePartitionTests.swift */, @@ -1176,6 +1206,12 @@ 594249BD4A084A1291AC0F14 /* CoreGapTests.swift in Sources */, 681654724B174266BAACBDED /* LegacyParityTests.swift in Sources */, 338497F3341748CF98532803 /* LogContractTests.swift in Sources */, + ED4F1F73046637700C291754 /* ContractFixtures.swift in Sources */, + 99279C14206F92436874AAF2 /* NamespaceRequestTests.swift in Sources */, + B848252E6A7B409E541A0448 /* NotificationsNamespaceTests.swift in Sources */, + A484DC14FFC3DBEE88C44402 /* StoriesPredictLoyaltySlidersTests.swift in Sources */, + BA2C8CBC07DA3021B357CFBC /* ReviewsFixtureCalls.swift in Sources */, + 0D3AA528DCB53AF45AC77B9B /* ReviewsRequestTests.swift in Sources */, AD0C7CD9B2C94E6C92EBD76F /* CoreDecisionTests.swift in Sources */, 185F659CDBE840968B74E646 /* CoreScenarioHarness.swift in Sources */, F82D9C817E27477A8B593D7E /* CoreSessionTests.swift in Sources */, @@ -1192,9 +1228,13 @@ 95300191D926BCFFE887810F /* StubServer.swift in Sources */, 7009DFFB0CC821D8EC72C77F /* LiveServerGuard.swift in Sources */, BACD7D59FBD148E5323B1DF8 /* SearchContractTests.swift in Sources */, + 035807D5C47B5617327F47D1 /* AgentSearchTests.swift in Sources */, EE982672942F5A449BD9638A /* SubscriptionContractTests.swift in Sources */, D3AE962D3B176281495DE5D5 /* LoyaltyAndOrdersContractTests.swift in Sources */, + 34E845DAF87173E0BF25FAB9 /* PredictContractTests.swift in Sources */, + 6844E30F231FF22F293ABDC0 /* ClientNamespaceTests.swift in Sources */, AADD17FBB7174736D09B40FA /* CatalogContractTests.swift in Sources */, + 2D62BB4EF7EDEC67BEFDB85A /* CatalogNamespaceTests.swift in Sources */, 2E817004C18D1F584765B326 /* ContractTestCase.swift in Sources */, 67B36DC5275BCA31AB0A0363 /* SdkRegistryTests.swift in Sources */, DFDB6BC32790E30AA243B4E9 /* StoragePartitionTests.swift in Sources */, diff --git a/DemoApp/Rees46DemoTests/AgentSearchTests.swift b/DemoApp/Rees46DemoTests/AgentSearchTests.swift new file mode 100644 index 00000000..dc7ba613 --- /dev/null +++ b/DemoApp/Rees46DemoTests/AgentSearchTests.swift @@ -0,0 +1,176 @@ +// +// AgentSearchTests.swift +// REES46Tests +// +// The search agent of `search` end to end over the stub server: `agentDialog` and `agent` go to +// `Rees46Config.appDomain` with the common fields — `agent` with its own read timeout of 60 seconds —, +// `agentEnabled` follows `search.blank_mode` of the instance's `/init`, and on the old core the agent +// is off and its methods are `notInitialized`. The cases of each request and answer are the +// package's (`CatalogPackageTests`, `search.json`). +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class AgentSearchTests: CoreScenarioTestCase { + + private static let path = "/api/v3/storefront/search/agent" + + private let dialog = #"{"sessions": [{"id": 12, "title": "Flash drive"}], "session": {"id": 12, "messages": [{"id": 1, "role": "user", "content": "1 TB"}]}}"# + private let reply = #"{"session": {"id": 12}, "message": {"id": 2, "role": "assistant", "content": "Here", "products": [{"id": "1", "price": 10, "reason": "fits"}]}}"# + + private func agentDialog(_ sdk: PersonalizationSDK, sessionId: Int? = nil) -> Result? { + let done = expectation(description: "agentDialog") + let outcome = Locked?>(nil) + sdk.search.agentDialog(sessionId: sessionId) { result in + XCTAssertTrue(Thread.isMainThread) + outcome.current = result + done.fulfill() + } + wait(for: [done], timeout: 5) + return outcome.current + } + + private func agent(_ sdk: PersonalizationSDK, _ message: String, sessionId: Int? = nil) -> Result? { + let done = expectation(description: "agent") + let outcome = Locked?>(nil) + sdk.search.agent(message: message, sessionId: sessionId, locations: ["10"]) { result in + XCTAssertTrue(Thread.isMainThread) + outcome.current = result + done.fulfill() + } + wait(for: [done], timeout: 5) + return outcome.current + } + + private func failure(_ result: Result?) -> Rees46.SdkError? { + if case .failure(let error)? = result { return error } + return nil + } + + // MARK: - The host of API v3 + + func test_the_dialog_and_a_message_go_to_the_app_domain_with_the_common_fields() throws { + let shop = newShop() + let sdk = makeV2(shop) + answer(Self.path, StubReply(json: dialog)) + let read = try XCTUnwrap(agentDialog(sdk, sessionId: 12)?.get()) + XCTAssertEqual(read.sessions.map(\.id), [12]) + XCTAssertEqual(read.session?.messages.first?.role, .user) + let get = try XCTUnwrap(requests(Self.path, shop).last) + XCTAssertEqual(get.method, "GET") + XCTAssertEqual(get.url?.host, Rees46Config.defaultAppDomain) + XCTAssertEqual(get.query["session_id"], "12") + XCTAssertEqual(get.query["shop_id"], shop) + XCTAssertEqual(get.query["did"], "d") + XCTAssertEqual(get.query["sid"], sdk.sessionId) + XCTAssertEqual(get.timeout, NetworkClient.defaultTimeout, "the dialog has the common timeout") + + answer(Self.path, StubReply(json: reply)) + let answered = try XCTUnwrap(agent(sdk, "something cheaper?", sessionId: 12)?.get()) + XCTAssertEqual(answered.session.id, 12) + XCTAssertEqual(answered.message.products.map(\.reason), ["fits"]) + let post = try XCTUnwrap(requests(Self.path, shop).last) + XCTAssertEqual(post.method, "POST") + XCTAssertEqual(post.url?.host, Rees46Config.defaultAppDomain) + XCTAssertEqual(post.header("Content-Type"), "application/json") + XCTAssertEqual(post.body["message"] as? String, "something cheaper?") + XCTAssertEqual(post.body["session_id"] as? Int, 12) + XCTAssertEqual(post.body["location"] as? String, "10") + XCTAssertEqual(post.body["shop_id"] as? String, shop) + XCTAssertEqual(post.body["did"] as? String, "d") + XCTAssertEqual(post.body["sid"] as? String, sdk.sessionId) + XCTAssertEqual(post.timeout, 60, "the agent answers in up to 40 seconds and two more tries of its model") + sdk.release() + } + + func test_the_agent_goes_to_the_shops_own_app_domain() { + CoreFlag.reset() + let shop = newShop() + let config = Rees46Config(shopId: shop, apiDomain: "stub.test", appDomain: "app.cluster.test", autoSendPushToken: false) + guard let sdk = Rees46.initializeBridge(config) as? SimplePersonalizationSDK else { + return XCTFail("no instance") + } + answer(Self.path, StubReply(json: reply)) + let done = expectation(description: "agent") + sdk.search.agent(message: "hi") { _ in done.fulfill() } + wait(for: [done], timeout: 15) + XCTAssertEqual(requests(Self.path, shop).last?.url?.host, "app.cluster.test") + sdk.release() + } + + func test_the_agents_errors_are_http_with_their_code_and_the_instance_goes_on() { + let shop = newShop() + let sdk = makeV2(shop) + for code in [400, 402, 404, 429, 503] { + answer(Self.path, StubReply(code, json: #"{"error": "no"}"#)) + XCTAssertEqual(failure(agent(sdk, "hi")), .http(code: code, serverCode: nil), "\(code)") + XCTAssertEqual(failure(agentDialog(sdk)), .http(code: code, serverCode: nil), "\(code)") + } + XCTAssertEqual(sdk.state, .ready) + sdk.release() + } + + func test_a_message_the_server_would_refuse_is_refused_before_anything_is_sent() { + let shop = newShop() + let sdk = makeV2(shop) + if case .invalidArgument? = failure(agent(sdk, " ")) {} else { XCTFail("an empty message") } + if case .invalidArgument? = failure(agent(sdk, String(repeating: "я", count: 501))) {} else { XCTFail("a message of 501 characters") } + XCTAssertTrue(requests(Self.path, shop).isEmpty) + XCTAssertTrue(eventually { self.logged(shop, "invalid_argument").contains { $0.context["call"] == "search.agent" } }) + sdk.release() + } + + func test_the_async_forms() { + let shop = newShop() + let sdk = makeV2(shop) + answer(Self.path, StubReply(json: reply)) + let done = expectation(description: "async") + let ids = Locked<[Int]>([]) + _Concurrency.Task { + let dialog = try? await sdk.search.agentDialog() + let answer = try? await sdk.search.agent(message: "hi") + ids.current = [dialog?.sessions.count ?? -1, answer?.session.id ?? -1] + done.fulfill() + } + wait(for: [done], timeout: 5) + XCTAssertEqual(ids.current, [0, 12], "the reply is no dialog: no sessions") + sdk.release() + } + + // MARK: - agentEnabled + + func test_agent_enabled_follows_the_blank_mode_of_the_last_init() { + let shop = newShop() + answer("/init", StubReply(json: #"{"did": "d", "seance": "s-1", "search": {"enabled": true, "blank_mode": "agent"}}"#)) + let sdk = makeV2(shop, settled: false) + XCTAssertTrue(eventually { sdk.search.agentEnabled }, "agent") + answer("/init", StubReply(json: #"{"did": "d", "seance": "s-2", "search": {"enabled": true, "blank_mode": "history"}}"#)) + sdk.deleteUserCredentials() + XCTAssertTrue(eventually { !sdk.search.agentEnabled }, "history, after the next /init") + sdk.release() + } + + func test_without_an_answer_of_init_the_agent_is_off() { + let shop = newShop() + hold("/init") + let sdk = makeV2(shop, identity: InMemoryUserIdentityRepository(), settled: false) + XCTAssertFalse(sdk.search.agentEnabled) + release("/init") + sdk.release() + } + + // MARK: - The old core + + func test_on_the_old_core_the_agent_is_off_and_its_methods_are_not_initialized() { + let shop = newShop() + answer("/init", StubReply(json: #"{"did": "d", "seance": "s-1", "search": {"blank_mode": "agent"}}"#)) + let sdk = makeLegacy(shop) + XCTAssertFalse(sdk.search.agentEnabled) + XCTAssertEqual(failure(agentDialog(sdk)), .notInitialized) + XCTAssertEqual(failure(agent(sdk, "hi")), .notInitialized) + XCTAssertTrue(requests(Self.path, shop).isEmpty) + XCTAssertTrue(eventually { Set(self.logged(shop, "core_flag_mismatch").compactMap { $0.context["call"] }) == ["search.agentDialog", "search.agent"] }) + sdk.release() + } +} diff --git a/DemoApp/Rees46DemoTests/CatalogNamespaceTests.swift b/DemoApp/Rees46DemoTests/CatalogNamespaceTests.swift new file mode 100644 index 00000000..b033e0c0 --- /dev/null +++ b/DemoApp/Rees46DemoTests/CatalogNamespaceTests.swift @@ -0,0 +1,252 @@ +// +// CatalogNamespaceTests.swift +// REES46Tests +// +// The catalog's namespaces end to end over the stub server — `products`, `collections`, +// `recommendations` and the search of `search` —: each method sends its request with the common fields +// and reads the answer, in `completion` and in `async` code; on the old core each one is +// `notInitialized`, sends nothing and logs its name; a refused argument sends nothing. The cases of +// each request and answer are the package's (`CatalogPackageTests`). +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class CatalogNamespaceTests: CoreScenarioTestCase { + + /// One method of the catalog, called with arguments it sends. + private struct Method { + /// What the log calls it. + let name: String + /// The stub's path of its request. + let path: String + /// The fields of the query it sends for these arguments. + let sends: [String: String] + /// An answer it reads. + let answer: String + let call: (PersonalizationSDK, @escaping (Rees46.SdkError?) -> Void) -> Void + let callAsync: (PersonalizationSDK) async throws -> Void + } + + private let methods: [Method] = [ + Method( + name: "products.getInfo", path: "/products/get", sends: ["item_id": "37"], + answer: #"{"id": "37", "uniqid": "37", "name": "Phone", "url": "https://shop.example/37", "price": "99", "currency": "$"}"#, + call: { sdk, done in sdk.products.getInfo(itemId: "37") { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.products.getInfo(itemId: "37") } + ), + Method( + name: "products.getList", path: "/products", sends: ["limit": "5", "sort_by": "price"], + answer: #"{"products_total": 0, "products": []}"#, + call: { sdk, done in sdk.products.getList(Rees46.ProductsListRequest(sortBy: .price, limit: 5)) { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.products.getList(Rees46.ProductsListRequest(sortBy: .price, limit: 5)) } + ), + Method( + name: "products.getCounters", path: "/products/counters", sends: ["item": "37"], + answer: #"{"daily": {"view": 1, "cart": 0, "purchase": 0}}"#, + call: { sdk, done in sdk.products.getCounters(itemId: "37") { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.products.getCounters(itemId: "37") } + ), + Method( + name: "products.getCategory", path: "/products", sends: ["categories": "15"], + answer: #"{"products": []}"#, + call: { sdk, done in sdk.products.getCategory(categoryId: "15") { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.products.getCategory(categoryId: "15") } + ), + Method( + name: "collections.get", path: "/collection/12", sends: [:], + answer: #"{"products": []}"#, + call: { sdk, done in sdk.collections.get(collectionId: "12") { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.collections.get(collectionId: "12") } + ), + Method( + name: "recommendations.get", path: "/recommend/block-1", sends: ["extended": "true", "item_id": "37"], + answer: #"{"id": 1, "title": "Similar", "recommends": []}"#, + call: { sdk, done in sdk.recommendations.get(code: "block-1", request: Rees46.RecommendationRequest(itemId: "37")) { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.recommendations.get(code: "block-1", request: Rees46.RecommendationRequest(itemId: "37")) } + ), + Method( + name: "search.blank", path: "/search/blank", sends: [:], + answer: #"{"last_products": false}"#, + call: { sdk, done in sdk.search.blank { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.search.blank() } + ), + Method( + name: "search.instant", path: "/search", sends: ["type": "instant_search", "search_query": "phone"], + answer: #"{"products": []}"#, + call: { sdk, done in sdk.search.instant(query: "phone") { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.search.instant(query: "phone") } + ), + Method( + name: "search.full", path: "/search", sends: ["type": "full_search", "search_query": "phone", "page": "2"], + answer: #"{"products": []}"#, + call: { sdk, done in sdk.search.full(query: "phone", request: Rees46.SearchFullRequest(page: 2)) { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.search.full(query: "phone", request: Rees46.SearchFullRequest(page: 2)) } + ), + ] + + /// How `method` ended with `completion`, which comes on the main thread. + private func outcome(_ method: Method, _ sdk: PersonalizationSDK, file: StaticString = #filePath, line: UInt = #line) -> Rees46.SdkError? { + let done = expectation(description: method.name) + let error = Locked(nil) + method.call(sdk) { failure in + XCTAssertTrue(Thread.isMainThread, "\(method.name): completion on the main thread", file: file, line: line) + error.current = failure + done.fulfill() + } + wait(for: [done], timeout: 5) + return error.current + } + + /// How `method` ended in `async` code. + private func asyncOutcome(_ method: Method, _ sdk: PersonalizationSDK) -> Rees46.SdkError? { + let done = expectation(description: "async \(method.name)") + let error = Locked(nil) + _Concurrency.Task { + do { + try await method.callAsync(sdk) + } catch let failure as Rees46.SdkError { + error.current = failure + } catch { + XCTFail("\(method.name): not an SdkError: \(error)") + } + done.fulfill() + } + wait(for: [done], timeout: 5) + return error.current + } + + // MARK: - The new core + + func test_each_method_sends_its_request_with_the_common_fields_and_reads_the_answer() throws { + let shop = newShop() + let sdk = makeV2(shop) + for method in methods { + answer(method.path, StubReply(json: method.answer)) + let before = requests(method.path, shop).count + XCTAssertNil(outcome(method, sdk), method.name) + let sent = requests(method.path, shop) + XCTAssertEqual(sent.count, before + 1, "\(method.name): one request") + let request = try XCTUnwrap(sent.last, method.name) + XCTAssertEqual(request.method, "GET", method.name) + for (key, value) in method.sends { + XCTAssertEqual(request.query[key], value, "\(method.name): \(key)") + } + XCTAssertEqual(request.query["shop_id"], shop, method.name) + XCTAssertEqual(request.query["did"], "d", method.name) + XCTAssertEqual(request.query["sid"], sdk.sessionId, method.name) + XCTAssertEqual(request.query["seance"], sdk.sessionId, method.name) + XCTAssertEqual(request.query["stream"], "ios", method.name) + XCTAssertEqual(request.query["segment"], sdk.segment, method.name) + XCTAssertEqual(request.timeout, NetworkClient.defaultTimeout, method.name) + } + sdk.release() + } + + func test_each_method_returns_its_value_in_async_code() { + let shop = newShop() + let sdk = makeV2(shop) + for method in methods { + answer(method.path, StubReply(json: method.answer)) + XCTAssertNil(asyncOutcome(method, sdk), method.name) + } + answer("/recommend/block-1", StubReply(404, json: #"{"status": "error", "message": "not found"}"#)) + XCTAssertEqual(asyncOutcome(methods[5], sdk), .http(code: 404, serverCode: nil)) + sdk.release() + } + + func test_the_values_come_whole_through_the_core() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/products/get", StubReply(json: #"{"id": "1", "uniqid": "A-1", "name": "Phone", "url": "u", "price": "99.5", "oldprice": 0, "currency": "$"}"#)) + let done = expectation(description: "products.getInfo") + let product = Locked(nil) + sdk.products.getInfo(itemId: "A-1") { result in + product.current = (try? result.get()) ?? nil + done.fulfill() + } + wait(for: [done], timeout: 5) + XCTAssertEqual(product.current?.id, "A-1") + XCTAssertEqual(product.current?.price, 99.5) + XCTAssertNil(product.current?.oldPrice) + sdk.release() + } + + func test_a_collection_id_and_a_block_code_go_encoded_in_the_path() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/collection/a/b c", StubReply(json: #"{"products": []}"#)) + let collection = expectation(description: "collections.get") + sdk.collections.get(collectionId: "a/b c") { result in + XCTAssertNotNil(try? result.get()) + collection.fulfill() + } + let block = expectation(description: "recommendations.get") + sdk.recommendations.get(code: "блок 1") { _ in block.fulfill() } + wait(for: [collection, block], timeout: 5) + XCTAssertEqual(requests("/collection/a/b c", shop).last?.url?.absoluteString.contains("/collection/a%2Fb%20c?"), true) + XCTAssertEqual(requests("/recommend/блок 1", shop).last?.url?.absoluteString.contains("/recommend/%D0%B1%D0%BB%D0%BE%D0%BA%201?"), true) + sdk.release() + } + + func test_a_refused_argument_sends_nothing_and_is_logged_with_the_call() { + let shop = newShop() + let sdk = makeV2(shop) + let done = expectation(description: "refused") + done.expectedFulfillmentCount = 3 + let errors = Locked<[Rees46.SdkError]>([]) + sdk.products.getInfo(itemId: " ") { result in + if case .failure(let error) = result { errors.mutate { $0.append(error) } } + done.fulfill() + } + sdk.search.full(query: "phone", request: Rees46.SearchFullRequest(limit: 0)) { result in + if case .failure(let error) = result { errors.mutate { $0.append(error) } } + done.fulfill() + } + sdk.recommendations.get(code: "b", request: Rees46.RecommendationRequest(extended: false, withLocations: true)) { result in + if case .failure(let error) = result { errors.mutate { $0.append(error) } } + done.fulfill() + } + wait(for: [done], timeout: 5) + XCTAssertEqual(errors.current.count, 3) + XCTAssertTrue(errors.current.allSatisfy { if case .invalidArgument = $0 { return true } else { return false } }, "\(errors.current)") + XCTAssertTrue(requests("/products/get", shop).isEmpty) + XCTAssertTrue(requests("/search", shop).isEmpty) + XCTAssertTrue(requests("/recommend/b", shop).isEmpty) + XCTAssertTrue(waitForLog(shop, "invalid_argument")) + XCTAssertTrue(eventually { Set(self.logged(shop, "invalid_argument").compactMap { $0.context["call"] }).isSuperset(of: ["products.getInfo", "search.full", "recommendations.get"]) }) + sdk.release() + } + + // MARK: - The old core + + func test_on_the_old_core_each_method_is_not_initialized_sends_nothing_and_logs_its_name() { + let shop = newShop() + let sdk = makeLegacy(shop) + for method in methods { + XCTAssertEqual(outcome(method, sdk), .notInitialized, method.name) + XCTAssertEqual(asyncOutcome(method, sdk), .notInitialized, method.name) + XCTAssertTrue(requests(method.path, shop).isEmpty, method.name) + } + XCTAssertTrue(waitForLog(shop, "core_flag_mismatch")) + let names = Set(methods.map(\.name)) + XCTAssertTrue(eventually { Set(self.logged(shop, "core_flag_mismatch").compactMap { $0.context["call"] }) == names }) + XCTAssertTrue(logged(shop, "core_flag_mismatch").allSatisfy { $0.level == .warning }) + sdk.release() + } + + func test_another_conformer_of_the_protocol_is_not_initialized() { + let fake = FakeSDK(shopId: "fake-\(UUID().uuidString)") + for method in methods { + XCTAssertEqual(outcome(method, fake), .notInitialized, method.name) + } + } +} + +private extension Result { + + var failure: Failure? { + if case .failure(let error) = self { return error } + return nil + } +} diff --git a/DemoApp/Rees46DemoTests/ClientNamespaceTests.swift b/DemoApp/Rees46DemoTests/ClientNamespaceTests.swift new file mode 100644 index 00000000..5b7b1c2b --- /dev/null +++ b/DemoApp/Rees46DemoTests/ClientNamespaceTests.swift @@ -0,0 +1,274 @@ +// +// ClientNamespaceTests.swift +// REES46Tests +// +// The client's namespaces end to end over the stub server — `profile`, `subscriptions`, `segments` —: +// each method sends its request with the common fields and reads the answer, in `completion` and in +// `async` code; on the old core each one is `notInitialized`, sends nothing and logs its name; the A/B +// group is the device's on either core. The cases of each request and answer are the package's +// (`ClientPackageTests`). +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class ClientNamespaceTests: CoreScenarioTestCase { + + /// One method of the client, called with arguments it sends. + private struct Method { + /// What the log calls it. + let name: String + let httpMethod: String + /// The stub's path of its request. + let path: String + /// The fields of the query or the body it sends for these arguments, as text. + let sends: [String: String] + /// An answer it reads. + let answer: String + let call: (PersonalizationSDK, @escaping (Rees46.SdkError?) -> Void) -> Void + let callAsync: (PersonalizationSDK) async throws -> Void + } + + private let methods: [Method] = [ + Method( + name: "profile.get", httpMethod: "GET", path: "/profile", sends: [:], + answer: #"{"id": "1", "gender": "f"}"#, + call: { sdk, done in sdk.profile.get { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.profile.get() } + ), + Method( + name: "profile.set", httpMethod: "POST", path: "/profile/set", + sends: ["external_id": "ext-1", "id": "ext-1", "birthday": "1990-05-17", "vip": "1"], + answer: #"{"status": "success"}"#, + call: { sdk, done in + sdk.profile.set(Rees46.ProfileUpdateRequest(externalId: "ext-1", birthday: "1990-05-17", customProperties: ["vip": true])) { done($0.failure) } + }, + callAsync: { sdk in try await sdk.profile.set(Rees46.ProfileUpdateRequest(externalId: "ext-1", birthday: "1990-05-17", customProperties: ["vip": true])) } + ), + Method( + name: "profile.getLastOrder", httpMethod: "GET", path: "/orders/last_for_user", sends: [:], + answer: #"[{"id": "1", "name": "Phone", "url": "u", "price": 1, "currency": "$"}]"#, + call: { sdk, done in sdk.profile.getLastOrder { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.profile.getLastOrder() } + ), + Method( + name: "subscriptions.manage", httpMethod: "POST", path: "/subscriptions/manage", sends: ["email_bulk": "1", "sms_chain": "0"], + answer: "{}", + call: { sdk, done in sdk.subscriptions.manage(Rees46.SubscriptionsUpdateRequest(emailBulk: true, smsChain: false)) { done($0.failure) } }, + callAsync: { sdk in try await sdk.subscriptions.manage(Rees46.SubscriptionsUpdateRequest(emailBulk: true, smsChain: false)) } + ), + Method( + name: "subscriptions.check", httpMethod: "GET", path: "/subscriptions/check", sends: [:], + answer: #"{"exists": true, "email_bulk": true}"#, + call: { sdk, done in sdk.subscriptions.check { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.subscriptions.check() } + ), + Method( + name: "subscriptions.subscribeForPriceDrop", httpMethod: "POST", path: "/subscriptions/subscribe_for_product_price", + sends: ["item_id": "37", "price": "99.5"], answer: "{}", + call: { sdk, done in sdk.subscriptions.subscribeForPriceDrop(itemId: "37", currentPrice: 99.5) { done($0.failure) } }, + callAsync: { sdk in try await sdk.subscriptions.subscribeForPriceDrop(itemId: "37", currentPrice: 99.5) } + ), + Method( + name: "subscriptions.unsubscribeFromPriceDrop", httpMethod: "POST", path: "/subscriptions/unsubscribe_from_product_price", + sends: ["item_ids": "37,38"], answer: "{}", + call: { sdk, done in sdk.subscriptions.unsubscribeFromPriceDrop(itemIds: ["37", "38"]) { done($0.failure) } }, + callAsync: { sdk in try await sdk.subscriptions.unsubscribeFromPriceDrop(itemIds: ["37", "38"]) } + ), + Method( + name: "subscriptions.subscribeForBackInStock", httpMethod: "POST", path: "/subscriptions/subscribe_for_product_available", + sends: ["item_id": "37"], answer: "{}", + call: { sdk, done in + sdk.subscriptions.subscribeForBackInStock(itemId: "37", properties: Rees46.BackInStockProperties(fashionSize: "M")) { done($0.failure) } + }, + callAsync: { sdk in try await sdk.subscriptions.subscribeForBackInStock(itemId: "37", properties: Rees46.BackInStockProperties(fashionSize: "M")) } + ), + Method( + name: "subscriptions.unsubscribeFromBackInStock", httpMethod: "POST", path: "/subscriptions/unsubscribe_from_product_available", + sends: ["item_ids": ""], answer: "{}", + call: { sdk, done in sdk.subscriptions.unsubscribeFromBackInStock(itemIds: []) { done($0.failure) } }, + callAsync: { sdk in try await sdk.subscriptions.unsubscribeFromBackInStock(itemIds: []) } + ), + Method( + name: "segments.add", httpMethod: "POST", path: "/segments/add", sends: ["segment_id": "313"], + answer: #"{"status": "success"}"#, + call: { sdk, done in sdk.segments.add(segmentId: 313) { done($0.failure) } }, + callAsync: { sdk in try await sdk.segments.add(segmentId: 313) } + ), + Method( + name: "segments.remove", httpMethod: "POST", path: "/segments/remove", sends: ["segment_id": "313", "email": "jane@example.com"], + answer: #"{"status": "success"}"#, + call: { sdk, done in sdk.segments.remove(segmentId: 313, email: "jane@example.com") { done($0.failure) } }, + callAsync: { sdk in try await sdk.segments.remove(segmentId: 313, email: "jane@example.com") } + ), + Method( + name: "segments.get", httpMethod: "GET", path: "/segments/get", sends: [:], + answer: #"[{"id": 313, "type": "static"}]"#, + call: { sdk, done in sdk.segments.get { done($0.failure) } }, + callAsync: { sdk in _ = try await sdk.segments.get() } + ), + ] + + /// How `method` ended with `completion`, which comes on the main thread. + private func outcome(_ method: Method, _ sdk: PersonalizationSDK, file: StaticString = #filePath, line: UInt = #line) -> Rees46.SdkError? { + let done = expectation(description: method.name) + let error = Locked(nil) + method.call(sdk) { failure in + XCTAssertTrue(Thread.isMainThread, "\(method.name): completion on the main thread", file: file, line: line) + error.current = failure + done.fulfill() + } + wait(for: [done], timeout: 5) + return error.current + } + + /// How `method` ended in `async` code. + private func asyncOutcome(_ method: Method, _ sdk: PersonalizationSDK) -> Rees46.SdkError? { + let done = expectation(description: "async \(method.name)") + let error = Locked(nil) + _Concurrency.Task { + do { + try await method.callAsync(sdk) + } catch let failure as Rees46.SdkError { + error.current = failure + } catch { + XCTFail("\(method.name): not an SdkError: \(error)") + } + done.fulfill() + } + wait(for: [done], timeout: 5) + return error.current + } + + // MARK: - The new core + + func test_each_method_sends_its_request_with_the_common_fields_and_reads_the_answer() throws { + let shop = newShop() + let sdk = makeV2(shop) + for method in methods { + answer(method.path, StubReply(json: method.answer)) + let before = requests(method.path, shop).count + XCTAssertNil(outcome(method, sdk), method.name) + let sent = requests(method.path, shop) + XCTAssertEqual(sent.count, before + 1, "\(method.name): one request") + let request = try XCTUnwrap(sent.last, method.name) + XCTAssertEqual(request.method, method.httpMethod, method.name) + let fields: [String: String] = method.httpMethod == "GET" ? request.query : request.body.mapValues { "\($0)" } + for (key, value) in method.sends { + XCTAssertEqual(fields[key], value, "\(method.name): \(key)") + } + XCTAssertEqual(fields["shop_id"], shop, method.name) + XCTAssertEqual(fields["did"], "d", method.name) + XCTAssertEqual(fields["sid"], sdk.sessionId, method.name) + XCTAssertEqual(fields["seance"], sdk.sessionId, method.name) + XCTAssertEqual(fields["stream"], "ios", method.name) + XCTAssertEqual(fields["segment"], sdk.segment, method.name) + XCTAssertNil(fields["shop_secret"], method.name) + } + sdk.release() + } + + func test_each_method_returns_its_value_in_async_code() { + let shop = newShop() + let sdk = makeV2(shop) + for method in methods { + answer(method.path, StubReply(json: method.answer)) + XCTAssertNil(asyncOutcome(method, sdk), method.name) + } + answer("/subscriptions/check", StubReply(400, json: #"{"status": "error", "message": "Client not found"}"#)) + XCTAssertEqual(asyncOutcome(methods[4], sdk), .http(code: 400, serverCode: nil)) + sdk.release() + } + + func test_the_values_come_whole_through_the_core() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/profile", StubReply(json: #"{"id": 7, "gender": "m", "custom_properties": {"vip": true, "tags": ["a"]}}"#)) + answer("/segments/get", StubReply(json: #"[{"id": "313", "type": "static"}, {"type": "dynamic"}]"#)) + let done = expectation(description: "values") + done.expectedFulfillmentCount = 2 + let profile = Locked(nil) + let segments = Locked<[Rees46.Segment]>([]) + sdk.profile.get { result in + profile.current = try? result.get() + done.fulfill() + } + sdk.segments.get { result in + segments.current = (try? result.get()) ?? [] + done.fulfill() + } + wait(for: [done], timeout: 5) + XCTAssertEqual(profile.current?.id, "7") + XCTAssertEqual(profile.current?.gender, .male) + XCTAssertEqual(profile.current?.customProperties?["vip"] as? Bool, true) + XCTAssertEqual(segments.current, [Rees46.Segment(id: 313, type: "static")]) + sdk.release() + } + + func test_a_refused_argument_sends_nothing_and_is_logged_with_the_call() { + let shop = newShop() + let sdk = makeV2(shop) + let done = expectation(description: "refused") + done.expectedFulfillmentCount = 3 + let errors = Locked<[Rees46.SdkError]>([]) + let record: (Result) -> Void = { result in + if case .failure(let error) = result { errors.mutate { $0.append(error) } } + done.fulfill() + } + sdk.profile.set(Rees46.ProfileUpdateRequest(customProperties: ["when": Date()]), completion: record) + sdk.subscriptions.manage(Rees46.SubscriptionsUpdateRequest(email: "jane@example.com"), completion: record) + sdk.segments.add(segmentId: 0, completion: record) + wait(for: [done], timeout: 5) + XCTAssertEqual(errors.current.count, 3) + XCTAssertTrue(errors.current.allSatisfy { if case .invalidArgument = $0 { return true } else { return false } }, "\(errors.current)") + XCTAssertTrue(requests("/profile/set", shop).isEmpty) + XCTAssertTrue(requests("/subscriptions/manage", shop).isEmpty) + XCTAssertTrue(requests("/segments/add", shop).isEmpty) + XCTAssertTrue(eventually { Set(self.logged(shop, "invalid_argument").compactMap { $0.context["call"] }).isSuperset(of: ["profile.set", "subscriptions.manage", "segments.add"]) }) + sdk.release() + } + + func test_the_ab_group_is_the_devices_on_either_core() { + let v2 = makeV2(newShop()) + XCTAssertEqual(v2.segments.getAbGroup(), v2.segment) + XCTAssertTrue(["A", "B"].contains(v2.segments.getAbGroup())) + v2.release() + XCTAssertEqual(v2.segments.getAbGroup(), v2.segment, "the device's, after release() too") + CoreFlag.reset() + let legacy = makeLegacy(newShop()) + XCTAssertEqual(legacy.segments.getAbGroup(), legacy.segment) + legacy.release() + } + + // MARK: - The old core + + func test_on_the_old_core_each_method_is_not_initialized_sends_nothing_and_logs_its_name() { + let shop = newShop() + let sdk = makeLegacy(shop) + for method in methods { + XCTAssertEqual(outcome(method, sdk), .notInitialized, method.name) + XCTAssertEqual(asyncOutcome(method, sdk), .notInitialized, method.name) + XCTAssertTrue(requests(method.path, shop).isEmpty, method.name) + } + XCTAssertTrue(waitForLog(shop, "core_flag_mismatch")) + let names = Set(methods.map(\.name)) + XCTAssertTrue(eventually { Set(self.logged(shop, "core_flag_mismatch").compactMap { $0.context["call"] }) == names }) + XCTAssertTrue(logged(shop, "core_flag_mismatch").allSatisfy { $0.level == .warning }) + sdk.release() + } + + func test_another_conformer_of_the_protocol_is_not_initialized() { + let fake = FakeSDK(shopId: "fake-\(UUID().uuidString)") + for method in methods { + XCTAssertEqual(outcome(method, fake), .notInitialized, method.name) + } + } +} + +private extension Result { + + var failure: Failure? { + if case .failure(let error) = self { return error } + return nil + } +} diff --git a/DemoApp/Rees46DemoTests/ContractTestCase.swift b/DemoApp/Rees46DemoTests/ContractTestCase.swift index 9816da31..e28e1612 100644 --- a/DemoApp/Rees46DemoTests/ContractTestCase.swift +++ b/DemoApp/Rees46DemoTests/ContractTestCase.swift @@ -33,20 +33,20 @@ class ContractTestCase: XCTestCase { } /// Runs `body` with a ready SDK of a new shop on each core: the contract is the same on both. - func onBothCores(_ body: (SimplePersonalizationSDK) -> Void) { + func onBothCores(appDomain: String = Rees46Config.defaultAppDomain, _ body: (SimplePersonalizationSDK) -> Void) { for coreV2 in [false, true] { XCTContext.runActivity(named: coreV2 ? "the new core" : "the old core") { _ in - body(readySDK(coreV2: coreV2)) + body(readySDK(coreV2: coreV2, appDomain: appDomain)) } } } /// A ready SDK of a new shop over the stub server: its `/init` answered with the stub's device id. - func readySDK(coreV2: Bool) -> SimplePersonalizationSDK { + func readySDK(coreV2: Bool, appDomain: String = Rees46Config.defaultAppDomain) -> SimplePersonalizationSDK { let shop = StubSDK.shopId() shops.append(shop) let ready = expectation(description: "init") - let sdk = StubSDK.make(shopId: shop, coreV2: coreV2) { _ in ready.fulfill() } + let sdk = StubSDK.make(shopId: shop, coreV2: coreV2, appDomain: appDomain) { _ in ready.fulfill() } made.append(sdk) wait(for: [ready], timeout: 5) return sdk diff --git a/DemoApp/Rees46DemoTests/CoreGapTests.swift b/DemoApp/Rees46DemoTests/CoreGapTests.swift index 7492b507..304bdd32 100644 --- a/DemoApp/Rees46DemoTests/CoreGapTests.swift +++ b/DemoApp/Rees46DemoTests/CoreGapTests.swift @@ -810,6 +810,42 @@ final class CoreGapTests: CoreScenarioTestCase { after?.release() } + func test_the_shops_instance_keeps_the_app_domain_of_its_config() { + CoreFlag.reset() + let shop = newShop() + let config = Rees46Config(shopId: shop, apiDomain: "stub.test", appDomain: "app.cluster.test", autoSendPushToken: false) + let sdk = Rees46.initializeBridge(config) as? SimplePersonalizationSDK + XCTAssertEqual(sdk?.config.appDomain, "app.cluster.test") + XCTAssertEqual(sdk?.usesCoreV2, true) + + // The same shop with another host keeps the one it was made with, and says so. + _ = Rees46.initializeBridge(Rees46Config(shopId: shop, apiDomain: "stub.test", appDomain: "app.other.test", autoSendPushToken: false)) + XCTAssertTrue(waitForLog(shop, "invalid_config", reason: "already_initialized")) + XCTAssertEqual(sdk?.config.appDomain, "app.cluster.test") + sdk?.release() + } + + func test_the_bridges_async_delete_user_credentials_returns_once_the_customer_is_wiped_on_both_cores() { + for coreV2 in [true, false] { + let shop = newShop() + let identity = knownIdentity(did: "deleted") + let sdk = coreV2 ? makeV2(shop, identity: identity) : makeLegacy(shop, identity: identity) + XCTAssertEqual(sdk.deviceId, "deleted") + let bridge: PersonalizationSDK = sdk + let done = expectation(description: "deleteUserCredentials, coreV2 = \(coreV2)") + _Concurrency.Task { + await bridge.deleteUserCredentials() + done.fulfill() + } + wait(for: [done], timeout: 5) + XCTAssertNotEqual(identity.deviceId, "deleted", "coreV2 = \(coreV2)") + XCTAssertNotEqual(sdk.deviceId, "deleted", "coreV2 = \(coreV2)") + // The next /init asks for a new device id. + XCTAssertTrue(eventually { self.inits(shop).contains { $0.query["did"] == nil } }, "coreV2 = \(coreV2)") + sdk.release() + } + } + func test_initialize_bridge_brings_its_ab_group_only_to_a_device_that_has_none() { let deviceSuite = UserDefaults(suiteName: DeviceStore.suiteName) ?? .standard let before = deviceSuite.string(forKey: DeviceStore.abGroupKey) diff --git a/DemoApp/Rees46DemoTests/CoreHarnessTests.swift b/DemoApp/Rees46DemoTests/CoreHarnessTests.swift index bc8c4b7e..dd38db4d 100644 --- a/DemoApp/Rees46DemoTests/CoreHarnessTests.swift +++ b/DemoApp/Rees46DemoTests/CoreHarnessTests.swift @@ -198,29 +198,9 @@ final class Locked { // MARK: - Contract fixtures -/// The contract fixtures shared by every SDK, from `Tests/REES46CoreTests/Fixtures/contract-`. -/// Read from the source tree (the simulator reads the Mac's file system), so the copy is one for the -/// demo-app tests and the package tests. -enum ContractFixtures { - static let version = "0" - - static func url(_ name: String, sourceFile: StaticString = #filePath) -> URL { - URL(fileURLWithPath: "\(sourceFile)") - .deletingLastPathComponent() // Rees46DemoTests - .deletingLastPathComponent() // DemoApp - .deletingLastPathComponent() // repository root - .appendingPathComponent("Tests/REES46CoreTests/Fixtures/contract-\(version)/\(name).json") - } - - static func load(_ name: String) throws -> [String: Any] { - let data = try Data(contentsOf: url(name)) - return try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:] - } - - static func cases(_ name: String) throws -> [[String: Any]] { - try load(name)["cases"] as? [[String: Any]] ?? [] - } -} +// `ContractFixtures`, the loader of the contract's shared fixtures, is the package tests' own file +// (`Tests/REES46CoreTests/ContractFixtures.swift`), which this target compiles too: the simulator reads +// the Mac's file system, so the copy of the fixtures is one for both. // MARK: - Tests diff --git a/DemoApp/Rees46DemoTests/LogContractTests.swift b/DemoApp/Rees46DemoTests/LogContractTests.swift index 7f7e3547..bb653982 100644 --- a/DemoApp/Rees46DemoTests/LogContractTests.swift +++ b/DemoApp/Rees46DemoTests/LogContractTests.swift @@ -22,8 +22,8 @@ enum LogContract { let openReasons: Bool } - static func url(sourceFile: StaticString = #filePath) -> URL { - ContractFixtures.url("logging", sourceFile: sourceFile).deletingPathExtension().appendingPathExtension("md") + static func url() -> URL { + ContractFixtures.url("logging", extension: "md") } /// The contract's own file, when the contract is checked out next to this repository. diff --git a/DemoApp/Rees46DemoTests/NamespaceRequestTests.swift b/DemoApp/Rees46DemoTests/NamespaceRequestTests.swift new file mode 100644 index 00000000..9f1fe27b --- /dev/null +++ b/DemoApp/Rees46DemoTests/NamespaceRequestTests.swift @@ -0,0 +1,319 @@ +// +// NamespaceRequestTests.swift +// REES46Tests +// +// The base of the namespaces end to end, through `cart.get` over the stub server: the request the +// fixture names with the common fields, every answer of the fixture, no network, a timeout, a shop that +// refused, the old core's refusal, `completion` once on the main thread, the `async` form and its +// cancellation, `release()`. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class NamespaceRequestTests: CoreScenarioTestCase { + + // MARK: - Calls + + /// `cart.get` with `completion`: what it got, called on the main thread. + private func get(_ sdk: PersonalizationSDK, file: StaticString = #filePath, line: UInt = #line) -> Result<[CartItem], Rees46.SdkError>? { + let done = expectation(description: "cart.get") + let outcome = Locked?>(nil) + sdk.cart.get { result in + XCTAssertTrue(Thread.isMainThread, "completion on the main thread", file: file, line: line) + outcome.current = result + done.fulfill() + } + wait(for: [done], timeout: 5) + return outcome.current + } + + /// `cart.get` in `async` code, cancelled by `cancel` when it is given. + private func getAsync( + _ sdk: PersonalizationSDK, + cancel: ((_Concurrency.Task<[CartItem], Error>) -> Void)? = nil + ) -> Result<[CartItem], Rees46.SdkError>? { + let done = expectation(description: "async cart.get") + let outcome = Locked?>(nil) + let task = _Concurrency.Task { try await sdk.cart.get() } + _Concurrency.Task { + do { + outcome.current = .success(try await task.value) + } catch let error as Rees46.SdkError { + outcome.current = .failure(error) + } catch { + XCTFail("not an SdkError: \(error)") + } + done.fulfill() + } + cancel?(task) + wait(for: [done], timeout: 5) + return outcome.current + } + + private func error(of result: Result<[CartItem], Rees46.SdkError>?) -> Rees46.SdkError? { + if case .failure(let error)? = result { return error } + return nil + } + + /// Waits until a call waits for the instance: the timeout of its wait is on the test's scheduler. + private func awaitWaitingCall(_ before: Int, file: StaticString = #filePath, line: UInt = #line) { + XCTAssertTrue(eventually { self.waitsOfACall > before }, "the call waits for the instance", file: file, line: line) + } + + /// The waits of a request's timeout on the scheduler. + private var waitsOfACall: Int { + scheduler.pendingDelays.filter { abs($0 - NetworkClient.defaultTimeout) < 0.001 }.count + } + + // MARK: - The fixture + + func test_cart_get_sends_the_fixtures_request_with_the_common_fields() throws { + let shop = newShop() + let sdk = makeV2(shop) + let cases = try ContractFixtures.fixture("cart", from: .proposed).filter { $0.request != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let expected = try XCTUnwrap(item.request) + _ = get(sdk) + let sent = try XCTUnwrap(requests("/" + expected.path, shop).last, item.name) + XCTAssertEqual(sent.method, expected.method, item.name) + for (key, value) in expected.query { + XCTAssertEqual(sent.query[key], value, "\(item.name): \(key)") + } + // What the core adds: the API finds the cart by the device id. + XCTAssertEqual(sent.query["shop_id"], shop) + XCTAssertEqual(sent.query["did"], "d") + XCTAssertEqual(sent.query["sid"], sdk.sessionId) + XCTAssertEqual(sent.query["seance"], sdk.sessionId) + XCTAssertEqual(sent.query["stream"], "ios") + XCTAssertEqual(sent.query["segment"], sdk.segment) + XCTAssertEqual(sent.timeout, NetworkClient.defaultTimeout) + } + sdk.release() + } + + func test_cart_get_ends_as_the_fixture_says_for_each_answer_without_a_repeat() throws { + let shop = newShop() + let sdk = makeV2(shop) + let cases = try ContractFixtures.fixture("cart", from: .proposed).filter { $0.response != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let response = try XCTUnwrap(item.response) + // No status: no answer — a connection never made. + answer("/products/cart", response.status.map { StubReply($0, json: String(decoding: response.body, as: UTF8.self)) } ?? StubReply.noAnswer) + let before = requests("/products/cart", shop).count + let result = get(sdk) + XCTAssertEqual(requests("/products/cart", shop).count, before + 1, "\(item.name): one request, not repeated") + switch result { + case .success(let items)?: + XCTAssertNil(item.expectedError, "\(item.name): \(items)") + let expected = (item.expect["result"] as? [[String: Any]] ?? []).map { "\($0["id"] ?? "")×\($0["quantity"] ?? "")" } + XCTAssertEqual(items.map { "\($0.id)×\($0.quantity)" }, expected, item.name) + case .failure(let error)?: + XCTAssertTrue(item.expectedError?.matches(error) == true, "\(item.name): \(error)") + case nil: + XCTFail("\(item.name): no outcome") + } + } + // The state of the instance does not move on an error of one request. + XCTAssertEqual(sdk.state, .ready) + sdk.release() + } + + func test_an_answer_without_a_body_is_an_empty_cart_and_an_empty_object_is_decoding() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/products/cart", StubReply(200, json: "")) + XCTAssertEqual(try? get(sdk)?.get().count, 0) + answer("/products/cart", StubReply(204, json: "")) + XCTAssertEqual(try? get(sdk)?.get().count, 0) + answer("/products/cart", StubReply(200, json: "{}")) + XCTAssertEqual(error(of: get(sdk)), .decoding) + XCTAssertTrue(waitForLog(shop, "decoding_failed")) + XCTAssertEqual(logged(shop, "decoding_failed").last?.context["call"], "cart.get") + sdk.release() + } + + // MARK: - Errors without an answer + + func test_without_network_the_call_fails_at_once_with_network_and_sends_nothing() { + let shop = newShop() + let sdk = makeV2(shop) + network.isOnline = false + XCTAssertEqual(error(of: get(sdk)), .network) + XCTAssertTrue(requests("/products/cart", shop).isEmpty) + + // Online, but the connection is never made. + network.isOnline = true + answer("/products/cart", StubReply.noAnswer) + XCTAssertEqual(error(of: get(sdk)), .network) + sdk.release() + } + + func test_an_answer_the_read_timeout_cut_is_timeout() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/products/cart", StubReply(200, json: #"{"status":"success","data":{"items":[]}}"#, cutAfter: 8, cutWith: .timedOut)) + XCTAssertEqual(error(of: get(sdk)), .timeout) + sdk.release() + } + + func test_a_shop_that_is_not_usable_within_the_calls_timeout_ends_it_with_timeout() { + let shop = newShop() + hold("/init") + let sdk = makeV2(shop, identity: InMemoryUserIdentityRepository(), settled: false) + let before = waitsOfACall + let done = expectation(description: "cart.get") + let outcome = Locked?>(nil) + sdk.cart.get { outcome.current = $0; done.fulfill() } + awaitWaitingCall(before) + scheduler.advance(by: NetworkClient.defaultTimeout) + wait(for: [done], timeout: 5) + XCTAssertEqual(error(of: outcome.current), .timeout) + XCTAssertTrue(requests("/products/cart", shop).isEmpty) + release("/init") + sdk.release() + } + + func test_a_refused_shop_is_shop_blocked_and_sends_nothing() { + let shop = newShop() + answer("/init", StubReply(402, json: #"{"status":"error","message":"Restricted Mode"}"#)) + let sdk = makeV2(shop, settled: false) + XCTAssertTrue(eventually { sdk.state == .refused }) + XCTAssertEqual(error(of: get(sdk)), .shopBlocked) + XCTAssertEqual(error(of: getAsync(sdk)), .shopBlocked) + XCTAssertTrue(requests("/products/cart", shop).isEmpty) + sdk.release() + } + + // MARK: - The new core only + + func test_on_the_old_core_every_call_is_not_initialized_and_sends_nothing() { + let shop = newShop() + let sdk = makeLegacy(shop) + XCTAssertEqual(error(of: get(sdk)), .notInitialized) + XCTAssertEqual(error(of: getAsync(sdk)), .notInitialized) + XCTAssertTrue(requests("/products/cart", shop).isEmpty) + // The code Android logs for it too. + XCTAssertTrue(waitForLog(shop, "core_flag_mismatch")) + let message = logged(shop, "core_flag_mismatch").first + XCTAssertEqual(message?.context["call"], "cart.get") + XCTAssertEqual(message?.level, .warning) + XCTAssertTrue(message?.message.contains("Rees46.initializeBridge") == true, message?.message ?? "") + XCTAssertTrue(heard.filter { $0.shopId == shop }.allSatisfy(LogContract.allows)) + sdk.release() + } + + func test_another_conformer_of_the_protocol_is_not_initialized() { + let fake = FakeSDK(shopId: "fake-\(UUID().uuidString)") + XCTAssertEqual(error(of: get(fake)), .notInitialized) + XCTAssertTrue(waitForLog(nil, "not_implemented")) + } + + // MARK: - completion + + func test_completion_comes_once_on_the_main_thread_whatever_thread_calls() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/products/cart", StubReply(json: #"{"status":"success","data":{"items":[{"uniqid":"37","quantity":2}]}}"#)) + let once = expectation(description: "completion") + let again = expectation(description: "a second completion") + again.isInverted = true + let calls = Locked(0) + let items = Locked<[CartItem]>([]) + DispatchQueue.global().async { + sdk.cart.get { result in + XCTAssertTrue(Thread.isMainThread) + calls.mutate { $0 += 1 } + items.current = (try? result.get()) ?? [] + if calls.current == 1 { once.fulfill() } else { again.fulfill() } + } + } + wait(for: [once], timeout: 5) + wait(for: [again], timeout: 0.5) + XCTAssertEqual(items.current.map(\.id), ["37"]) + XCTAssertEqual(items.current.map(\.quantity), [2]) + sdk.release() + } + + // MARK: - release() + + func test_release_cancels_the_call_in_flight_and_later_calls_are_not_initialized() { + let shop = newShop() + let sdk = makeV2(shop) + hold("/products/cart") + let done = expectation(description: "cart.get") + let outcome = Locked?>(nil) + sdk.cart.get { outcome.current = $0; done.fulfill() } + XCTAssertTrue(eventually { self.requests("/products/cart", shop).count == 1 }, "the request is on its way") + sdk.release() + wait(for: [done], timeout: 5) + XCTAssertEqual(error(of: outcome.current), .cancelled) + release("/products/cart") + XCTAssertEqual(error(of: get(sdk)), .notInitialized) + XCTAssertEqual(error(of: getAsync(sdk)), .notInitialized) + } + + func test_release_cancels_a_call_that_waits_for_the_instance() { + let shop = newShop() + hold("/init") + let sdk = makeV2(shop, identity: InMemoryUserIdentityRepository(), settled: false) + let before = waitsOfACall + let done = expectation(description: "cart.get") + let outcome = Locked?>(nil) + sdk.cart.get { outcome.current = $0; done.fulfill() } + awaitWaitingCall(before) + sdk.release() + wait(for: [done], timeout: 5) + XCTAssertEqual(error(of: outcome.current), .cancelled) + XCTAssertTrue(requests("/products/cart", shop).isEmpty) + release("/init") + } + + // MARK: - async + + func test_the_async_form_returns_the_value_and_throws_the_error() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/products/cart", StubReply(json: #"{"status":"success","payload":{"cart_items":[{"uniqid":"7","quantity":"3"}]}}"#)) + let items = try? getAsync(sdk)?.get() + XCTAssertEqual(items?.map(\.id), ["7"]) + XCTAssertEqual(items?.map(\.quantity), [3]) + answer("/products/cart", StubReply(404, json: #"{"status":"error","message":"Client not found"}"#)) + XCTAssertEqual(error(of: getAsync(sdk)), .http(code: 404, serverCode: nil)) + sdk.release() + } + + func test_cancelling_the_task_ends_a_call_that_waits_for_the_instance_at_once() { + let shop = newShop() + hold("/init") + let sdk = makeV2(shop, identity: InMemoryUserIdentityRepository(), settled: false) + let before = waitsOfACall + let result = getAsync(sdk) { task in + self.awaitWaitingCall(before) + task.cancel() + } + XCTAssertEqual(error(of: result), .cancelled) + XCTAssertEqual(waitsOfACall, before, "its wait is over") + XCTAssertTrue(requests("/products/cart", shop).isEmpty) + release("/init") + sdk.release() + } + + func test_cancelling_the_task_cancels_the_request_in_flight() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/products/cart", StubReply(json: #"{"status":"success","data":{"items":[]}}"#)) + hold("/products/cart") + let result = getAsync(sdk) { task in + XCTAssertTrue(self.eventually { self.requests("/products/cart", shop).count == 1 }) + task.cancel() + } + XCTAssertEqual(error(of: result), .cancelled) + release("/products/cart") + // The instance goes on. + XCTAssertEqual(try? get(sdk)?.get().count, 0) + sdk.release() + } +} diff --git a/DemoApp/Rees46DemoTests/NotificationsNamespaceTests.swift b/DemoApp/Rees46DemoTests/NotificationsNamespaceTests.swift new file mode 100644 index 00000000..a5ad8b09 --- /dev/null +++ b/DemoApp/Rees46DemoTests/NotificationsNamespaceTests.swift @@ -0,0 +1,527 @@ +// +// NotificationsNamespaceTests.swift +// REES46Tests +// +// `sdk.notifications` over the stub server: the requests of the proposed fixture with what the core +// adds, its refusals and answers, one event per message whoever sends it, the source of a click, no +// callback for an event the app sends, the device's token, the shop's callbacks, the old core's +// refusal, `release()`, a refused shop, `completion` once on the main thread, the `async` forms. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class NotificationsNamespaceTests: CoreScenarioTestCase { + + // MARK: - The fixture's cases + + /// The cases of the proposed `notifications` fixture for iOS: those of no platform and of iOS. + private static func iosCases() throws -> [ContractCase] { + try ContractFixtures.cases("notifications", from: .proposed) + .filter { ($0["platform"] as? String ?? "ios") == "ios" } + .map(ContractCase.init) + } + + /// The event of a `track…` method of the fixture. + private static func event(of method: String) -> Rees46.PushEvent? { + guard method.hasPrefix("track") else { return nil } + return Rees46.PushEvent(rawValue: method.dropFirst("track".count).lowercased()) + } + + // MARK: - Calls + + /// A call with `completion` and what it got, called on the main thread. + private func outcome( + file: StaticString = #filePath, + line: UInt = #line, + _ start: (@escaping (Result) -> Void) -> Void + ) -> Result? { + let done = expectation(description: "completion") + let result = Locked?>(nil) + start { value in + XCTAssertTrue(Thread.isMainThread, "completion on the main thread", file: file, line: line) + result.current = value + done.fulfill() + } + wait(for: [done], timeout: 5) + return result.current + } + + /// The fixture's `call` on `sdk`. + private func run(_ call: ContractCase.Call, on sdk: PersonalizationSDK, completion: @escaping (Result) -> Void) { + let code = call.args["code"] as? String ?? "" + let type = call.args["type"] as? String ?? "" + switch call.method { + case "trackDelivered": + sdk.notifications.trackDelivered(code: code, type: type, completion: completion) + case "trackOpened": + sdk.notifications.trackOpened(code: code, type: type, completion: completion) + case "trackClicked": + sdk.notifications.trackClicked(code: code, type: type, completion: completion) + case "trackClosed": + sdk.notifications.trackClosed(code: code, type: type, completion: completion) + case "setPushToken": + guard let provider = Rees46.PushProvider(rawValue: call.args["provider"] as? String ?? "") else { + return XCTFail("\(call.name): no provider") + } + sdk.notifications.setPushToken(call.args["token"] as? String ?? "", provider: provider, completion: completion) + default: + XCTFail("\(call.name) is not a method of notifications") + } + } + + private func error(of result: Result?) -> Rees46.SdkError? { + if case .failure(let error)? = result { return error } + return nil + } + + private func succeeded(_ result: Result?) -> Bool { + if case .success? = result { return true } + return false + } + + /// An `async` call and what it threw, `nil` for none. + private func thrown(cancel: ((_Concurrency.Task) -> Void)? = nil, _ body: @escaping () async throws -> Void) -> Rees46.SdkError?? { + let done = expectation(description: "async") + let result = Locked(nil) + let task = _Concurrency.Task { try await body() } + _Concurrency.Task { + do { + try await task.value + result.current = .some(nil) + } catch let error as Rees46.SdkError { + result.current = .some(error) + } catch { + XCTFail("not an SdkError: \(error)") + } + done.fulfill() + } + cancel?(task) + wait(for: [done], timeout: 5) + return result.current + } + + /// The paths of the events of pushes and the token's. + private static let paths = ["/track/delivered", "/track/opened", "/track/clicked", "/track/closed", "/track/received", "/mobile_push_tokens"] + + private func sentNothing(_ shop: String) -> Bool { + Self.paths.allSatisfy { requests($0, shop).isEmpty } + } + + // MARK: - The fixture + + func test_each_call_of_the_fixture_sends_its_request_with_the_shop_and_the_device() throws { + let cases = try Self.iosCases().filter { $0.request != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let call = try XCTUnwrap(item.call, item.name) + let expected = try XCTUnwrap(item.request, item.name) + // A shop each: an event goes once per message, a token once a week. + let shop = newShop() + let sdk = makeV2(shop) + XCTAssertTrue(succeeded(outcome { run(call, on: sdk, completion: $0) }), item.name) + XCTAssertTrue(eventually { self.requests("/" + expected.path, shop).count == 1 }, item.name) + let sent = try XCTUnwrap(requests("/" + expected.path, shop).first, item.name) + XCTAssertEqual(sent.method, expected.method, item.name) + for (key, value) in expected.body { + XCTAssertEqual(sent.body[key] as? String, value as? String, "\(item.name): \(key)") + } + XCTAssertEqual(sent.body["shop_id"] as? String, shop, item.name) + XCTAssertEqual(sent.body["did"] as? String, "d", item.name) + XCTAssertNil(sent.body["push_provider"], "\(item.name): iOS sends none") + if call.method.hasPrefix("track") { + XCTAssertEqual(sent.body["stream"] as? String, "ios", item.name) + XCTAssertNil(sent.body["sid"], "\(item.name): the server does not read it") + XCTAssertNil(sent.body["seance"], item.name) + XCTAssertNil(sent.body["source"], item.name) + } + XCTAssertTrue(queueIdle(sdk)) + XCTAssertEqual(Self.paths.map { requests($0, shop).count }.reduce(0, +), 1, "\(item.name): that request alone") + sdk.release() + } + } + + func test_each_refusal_of_the_fixture_sends_nothing_and_says_which_call() throws { + let cases = try Self.iosCases().filter { $0.call != nil && $0.request == nil && $0.response == nil } + XCTAssertFalse(cases.isEmpty) + let shop = newShop() + let sdk = makeV2(shop) + for item in cases { + let call = try XCTUnwrap(item.call, item.name) + let expected = try XCTUnwrap(item.expectedError, item.name) + let result = outcome { run(call, on: sdk, completion: $0) } + XCTAssertTrue(error(of: result).map(expected.matches) == true, "\(item.name): \(String(describing: result))") + XCTAssertTrue(logged(shop, "invalid_argument").contains { $0.context["call"] == call.name }, item.name) + } + XCTAssertTrue(queueIdle(sdk)) + XCTAssertTrue(sentNothing(shop)) + XCTAssertTrue(files(sdk.storage).isEmpty) + XCTAssertTrue(heard.filter { $0.shopId == shop }.allSatisfy(LogContract.allows)) + sdk.release() + } + + func test_each_answer_of_the_fixture_ends_the_call_as_the_fixture_says() throws { + let cases = try Self.iosCases().filter { $0.response != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let call = try XCTUnwrap(item.call, item.name) + let response = try XCTUnwrap(item.response, item.name) + let path = call.method == "setPushToken" ? "/mobile_push_tokens" : "/track/\(Self.event(of: call.method)?.rawValue ?? "")" + let shop = newShop() + answer(path, response.status.map { StubReply($0, json: String(decoding: response.body, as: UTF8.self)) } ?? StubReply.noAnswer) + let sdk = makeV2(shop) + let result = outcome { run(call, on: sdk, completion: $0) } + if let expected = item.expectedError { + XCTAssertTrue(error(of: result).map(expected.matches) == true, "\(item.name): \(String(describing: result))") + } else { + XCTAssertTrue(succeeded(result), "\(item.name): \(String(describing: result))") + } + XCTAssertTrue(eventually { !self.requests(path, shop).isEmpty }, "\(item.name): it went") + if call.method.hasPrefix("track") { + // Not taken by the server: the event waits in the queue for the next try. + sdk.eventQueue?.settle() + XCTAssertEqual(files(sdk.storage).count, 1, "\(item.name): on disk") + } else { + XCTAssertEqual(requests(path, shop).count, 1, "\(item.name): not repeated") + } + // The state of the instance does not move on an answer of one request. + XCTAssertEqual(sdk.state, .ready, item.name) + sdk.release() + } + } + + // MARK: - Events + + func test_an_event_of_a_message_goes_once_whoever_sends_it() { + let shop = newShop() + let sdk = makeV2(shop) + XCTAssertEqual(Rees46.handlePush(pushPayload(shop, code: "m-1"), event: .clicked), shop) + XCTAssertTrue(eventually { self.requests("/track/clicked", shop).count == 1 }) + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackClicked(code: "m-1", type: "bulk", completion: $0) }), "a repeat succeeds") + + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackDelivered(code: "m-2", type: "bulk", completion: $0) })) + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackDelivered(code: "m-2", type: "bulk", completion: $0) })) + Rees46.handlePush(pushPayload(shop, code: "m-2"), event: .delivered) + // Another event of the same message is its own. + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackClosed(code: "m-2", type: "bulk", completion: $0) })) + + XCTAssertTrue(queueIdle(sdk)) + XCTAssertEqual(requests("/track/clicked", shop).count, 1) + XCTAssertEqual(requests("/track/delivered", shop).map { $0.body["code"] as? String }, ["m-2"]) + XCTAssertEqual(requests("/track/closed", shop).count, 1) + XCTAssertTrue(requests("/track/received", shop).isEmpty) + sdk.release() + } + + func test_a_code_or_type_of_blanks_is_refused_too() { + let shop = newShop() + let sdk = makeV2(shop) + guard case .invalidArgument? = error(of: outcome({ sdk.notifications.trackOpened(code: " ", type: "bulk", completion: $0) })) else { + return XCTFail("a code of blanks") + } + guard case .invalidArgument? = error(of: outcome({ sdk.notifications.trackClosed(code: "m-1", type: "\n", completion: $0) })) else { + return XCTFail("a type of blanks") + } + XCTAssertTrue(queueIdle(sdk)) + XCTAssertTrue(sentNothing(shop)) + sdk.release() + } + + func test_an_event_the_server_does_not_take_is_still_accepted_and_waits_for_the_next_try() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/track/closed", StubReply(500, json: "")) + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackClosed(code: "m-1", type: "bulk", completion: $0) }), "no network error") + XCTAssertTrue(eventually { self.requests("/track/closed", shop).count == 1 }) + sdk.eventQueue?.settle() + XCTAssertEqual(files(sdk.storage).count, 1, "on disk for the next try") + XCTAssertEqual(sdk.state, .ready) + sdk.release() + } + + func test_an_event_waits_in_the_queue_offline_and_its_call_succeeds_at_once() { + let shop = newShop() + let sdk = makeV2(shop) + network.isOnline = false + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackOpened(code: "m-1", type: "bulk", completion: $0) })) + sdk.eventQueue?.settle() + XCTAssertEqual(files(sdk.storage).count, 1, "on disk") + XCTAssertTrue(requests("/track/opened", shop).isEmpty) + network.isOnline = true + XCTAssertTrue(eventually { self.requests("/track/opened", shop).count == 1 }) + XCTAssertTrue(eventually { self.files(sdk.storage).isEmpty }) + sdk.release() + } + + func test_a_click_stores_the_source_and_no_event_the_app_sends_calls_a_callback() { + let shop = newShop() + let sdk = makeV2(shop) + let heardEvents = Locked<[String]>([]) + let record: (String) -> (Rees46.PushPayload) -> Void = { who in { _ in heardEvents.mutate { $0.append(who) } } } + Rees46.setPushCallbacks(Rees46.PushCallbacks( + onDelivered: record("facade"), onOpened: record("facade"), onClicked: record("facade"), onClosed: record("facade") + )) + sdk.notifications.setCallbacks(Rees46.PushCallbacks( + onDelivered: record("own"), onOpened: record("own"), onClicked: record("own"), onClosed: record("own") + )) + let listener = Rees46.onPushEvent { event, _ in heardEvents.mutate { $0.append("bridge \(event.rawValue)") } } + + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackDelivered(code: "c-7", type: "chain", completion: $0) })) + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackOpened(code: "c-7", type: "chain", completion: $0) })) + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackClicked(code: "c-7", type: "chain", completion: $0) })) + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackClosed(code: "c-7", type: "chain", completion: $0) })) + XCTAssertEqual(sdk.sourceStore.currentSource()?.type, "chain") + XCTAssertEqual(sdk.sourceStore.currentSource()?.code, "c-7") + + sdk.tracking.productView(itemId: "37") + XCTAssertTrue(eventually { self.requests("/push", shop).count == 1 }) + XCTAssertEqual(requests("/push", shop).first?.body["source"] as? [String: String], ["from": "chain", "code": "c-7"]) + XCTAssertNil(requests("/track/clicked", shop).first?.body["source"]) + + // A type that is not a source changes nothing. + XCTAssertTrue(succeeded(outcome { sdk.notifications.trackClicked(code: "dg-1", type: "digest", completion: $0) })) + XCTAssertEqual(sdk.sourceStore.currentSource()?.code, "c-7") + + XCTAssertTrue(queueIdle(sdk)) + drainMainQueue() + XCTAssertEqual(heardEvents.current, [], "the app knows of the events it sends") + listener.cancel() + sdk.release() + } + + func test_the_events_without_a_completion_go_too() { + let shop = newShop() + let sdk = makeV2(shop) + sdk.notifications.trackDelivered(code: "m-1", type: "bulk") + sdk.notifications.trackOpened(code: "m-1", type: "bulk") + sdk.notifications.trackClicked(code: "m-1", type: "bulk") + sdk.notifications.trackClosed(code: "m-1", type: "bulk") + for event in Rees46.PushEvent.allCases { + XCTAssertTrue(eventually { self.requests("/" + event.path, shop).count == 1 }, event.rawValue) + } + sdk.release() + } + + // MARK: - The token + + func test_get_push_token_reads_the_tokens_without_the_network() { + let shop = newShop() + let sdk = makeV2(shop) + XCTAssertNil(sdk.notifications.getPushToken()) + Rees46.PushProvider.allCases.forEach { XCTAssertNil(sdk.notifications.getPushToken(provider: $0), $0.rawValue) } + + XCTAssertTrue(succeeded(outcome { sdk.notifications.setPushToken("a-1", provider: .apns, completion: $0) })) + XCTAssertEqual(sdk.notifications.getPushToken(), Rees46.PushToken(token: "a-1", provider: .apns)) + clock.advance(by: 60) + XCTAssertTrue(succeeded(outcome { sdk.notifications.setPushToken("f-1", provider: .fcm, completion: $0) })) + XCTAssertEqual(sdk.notifications.getPushToken(), Rees46.PushToken(token: "f-1", provider: .fcm), "the one the shop sent last") + XCTAssertEqual(sdk.notifications.getPushToken(provider: .apns), Rees46.PushToken(token: "a-1", provider: .apns)) + XCTAssertEqual(sdk.notifications.getPushToken(provider: .fcm), Rees46.PushToken(token: "f-1", provider: .fcm)) + XCTAssertNil(sdk.notifications.getPushToken(provider: .hms), "iOS has none") + + // The token the SDK got from APNs itself. + clock.advance(by: 60) + NotificationService(sdk: sdk, notificationLogger: NotificationLogger()).didRegisterForRemoteNotificationsWithDeviceToken(deviceToken: Data([0xAB, 0x01])) + XCTAssertEqual(sdk.notifications.getPushToken(provider: .apns), Rees46.PushToken(token: "ab01", provider: .apns)) + XCTAssertTrue(eventually { self.requests("/mobile_push_tokens", shop).count == 3 }) + XCTAssertTrue(eventually { sdk.notifications.getPushToken() == Rees46.PushToken(token: "ab01", provider: .apns) }) + sdk.release() + + // A shop that sent none: the device's last token. + let other = newShop() + let fresh = makeV2(other) + fresh.deviceStore.deviceToken = Rees46.PushToken(token: "f-2", provider: .fcm) + XCTAssertEqual(fresh.notifications.getPushToken(), Rees46.PushToken(token: "f-2", provider: .fcm)) + XCTAssertEqual(fresh.notifications.getPushToken(provider: .fcm), Rees46.PushToken(token: "f-2", provider: .fcm)) + XCTAssertTrue(requests("/mobile_push_tokens", other).isEmpty) + fresh.release() + } + + func test_set_push_token_waits_for_the_device_id_and_goes_once_a_week() { + let shop = newShop() + hold("/init") + let sdk = makeV2(shop, identity: InMemoryUserIdentityRepository(), settled: false) + let done = expectation(description: "setPushToken") + let result = Locked?>(nil) + sdk.notifications.setPushToken("t-1", provider: .apns) { result.current = $0; done.fulfill() } + XCTAssertTrue(waitForLog(shop, "push_token_skipped", reason: "no_device_id")) + XCTAssertNil(result.current, "waiting is no failure") + release("/init") + wait(for: [done], timeout: 5) + XCTAssertTrue(succeeded(result.current)) + XCTAssertEqual(requests("/mobile_push_tokens", shop).count, 1) + XCTAssertEqual(requests("/mobile_push_tokens", shop).first?.body["did"] as? String, sdk.deviceId) + + // The same token within its week: nothing goes, and it is a success. + XCTAssertTrue(succeeded(outcome { sdk.notifications.setPushToken("t-1", provider: .apns, completion: $0) })) + XCTAssertEqual(requests("/mobile_push_tokens", shop).count, 1) + // A new one goes at once. + XCTAssertTrue(succeeded(outcome { sdk.notifications.setPushToken("t-2", provider: .apns, completion: $0) })) + XCTAssertEqual(requests("/mobile_push_tokens", shop).count, 2) + sdk.release() + } + + // MARK: - Callbacks + + func test_the_shops_own_callbacks_win_over_the_facades_and_empty_ones_remove_them() { + let shop = newShop() + let sdk = makeV2(shop) + let heardClicks = Locked<[String]>([]) + Rees46.setPushCallbacks(Rees46.PushCallbacks(onClicked: { push in heardClicks.mutate { $0.append("facade \(push.code)") } })) + sdk.notifications.setCallbacks(Rees46.PushCallbacks(onClicked: { push in heardClicks.mutate { $0.append("own \(push.code)") } })) + Rees46.handlePush(pushPayload(shop, code: "m-1"), event: .clicked) + XCTAssertTrue(eventually { heardClicks.current == ["own m-1"] }, "\(heardClicks.current)") + + sdk.notifications.setCallbacks(Rees46.PushCallbacks()) + Rees46.handlePush(pushPayload(shop, code: "m-2"), event: .clicked) + XCTAssertTrue(eventually { heardClicks.current == ["own m-1", "facade m-2"] }, "\(heardClicks.current)") + sdk.release() + } + + // MARK: - The new core only + + func test_on_the_old_core_every_method_is_not_initialized_sends_and_sets_nothing() { + let shop = newShop() + let sdk = makeLegacy(shop) + let before = Self.paths.map { requests($0, shop).count } + let source = sdk.sourceStore.currentSource().map { "\($0.type) \($0.code)" } + XCTAssertEqual(error(of: outcome { sdk.notifications.trackDelivered(code: "m-1", type: "bulk", completion: $0) }), .notInitialized) + XCTAssertEqual(error(of: outcome { sdk.notifications.trackOpened(code: "m-1", type: "bulk", completion: $0) }), .notInitialized) + XCTAssertEqual(error(of: outcome { sdk.notifications.trackClicked(code: "m-1", type: "bulk", completion: $0) }), .notInitialized) + XCTAssertEqual(error(of: outcome { sdk.notifications.trackClosed(code: "m-1", type: "bulk", completion: $0) }), .notInitialized) + XCTAssertEqual(error(of: outcome { sdk.notifications.setPushToken("t-1", provider: .apns, completion: $0) }), .notInitialized) + XCTAssertEqual(thrown { try await sdk.notifications.trackClicked(code: "m-1", type: "bulk") }, .some(.notInitialized)) + XCTAssertEqual(thrown { try await sdk.notifications.setPushToken("t-1", provider: .apns) }, .some(.notInitialized)) + XCTAssertNil(sdk.notifications.getPushToken()) + sdk.notifications.setCallbacks(Rees46.PushCallbacks(onClicked: { _ in })) + XCTAssertNil(sdk.pushCallbackBox.callbacks) + + XCTAssertEqual(Self.paths.map { requests($0, shop).count }, before, "nothing went") + XCTAssertEqual(sdk.sourceStore.currentSource().map { "\($0.type) \($0.code)" }, source, "a click stored no source") + XCTAssertNil(sdk.deviceStore.deviceToken(.apns)) + XCTAssertTrue(waitForLog(shop, "core_flag_mismatch")) + let calls = Set(logged(shop, "core_flag_mismatch").compactMap { $0.context["call"] }) + XCTAssertEqual(calls, [ + "notifications.trackDelivered", "notifications.trackOpened", "notifications.trackClicked", + "notifications.trackClosed", "notifications.setPushToken", "notifications.getPushToken", + "notifications.setCallbacks", + ]) + XCTAssertTrue(logged(shop, "core_flag_mismatch").allSatisfy { $0.level == .warning }) + XCTAssertTrue(heard.filter { $0.shopId == shop }.allSatisfy(LogContract.allows)) + sdk.release() + } + + func test_another_conformer_of_the_protocol_is_not_initialized() { + let fake = FakeSDK(shopId: "fake-\(UUID().uuidString)") + XCTAssertEqual(error(of: outcome { fake.notifications.trackDelivered(code: "m-1", type: "bulk", completion: $0) }), .notInitialized) + XCTAssertEqual(error(of: outcome { fake.notifications.setPushToken("t-1", provider: .apns, completion: $0) }), .notInitialized) + XCTAssertNil(fake.notifications.getPushToken()) + fake.notifications.setCallbacks(Rees46.PushCallbacks()) + XCTAssertTrue(waitForLog(nil, "not_implemented")) + XCTAssertTrue(logged(nil, "not_implemented").contains { $0.context["call"] == "notifications.setCallbacks" }) + } + + func test_after_release_every_method_is_not_initialized_and_sends_nothing() { + let shop = newShop() + let sdk = makeV2(shop) + sdk.release() + XCTAssertEqual(error(of: outcome { sdk.notifications.trackDelivered(code: "m-1", type: "bulk", completion: $0) }), .notInitialized) + XCTAssertEqual(error(of: outcome { sdk.notifications.trackClicked(code: "m-1", type: "bulk", completion: $0) }), .notInitialized) + XCTAssertEqual(error(of: outcome { sdk.notifications.setPushToken("t-1", provider: .apns, completion: $0) }), .notInitialized) + XCTAssertNil(sdk.notifications.getPushToken()) + XCTAssertTrue(sentNothing(shop)) + XCTAssertFalse(PushCenter.isTaken(.clicked, code: "m-1", shopId: shop), "nothing counted as sent") + + // The shop's next instance sends the event. + let next = makeV2(shop) + XCTAssertTrue(succeeded(outcome { next.notifications.trackClicked(code: "m-1", type: "bulk", completion: $0) })) + XCTAssertTrue(eventually { self.requests("/track/clicked", shop).count == 1 }) + next.release() + } + + func test_a_refused_shop_is_shop_blocked_and_sends_nothing() { + let shop = newShop() + answer("/init", StubReply(402, json: #"{"status":"error","message":"Restricted Mode"}"#)) + let sdk = makeV2(shop, settled: false) + XCTAssertTrue(eventually { sdk.state == .refused }) + XCTAssertEqual(error(of: outcome { sdk.notifications.trackDelivered(code: "m-1", type: "bulk", completion: $0) }), .shopBlocked) + XCTAssertEqual(error(of: outcome { sdk.notifications.setPushToken("t-1", provider: .apns, completion: $0) }), .shopBlocked) + XCTAssertEqual(thrown { try await sdk.notifications.trackClosed(code: "m-1", type: "bulk") }, .some(.shopBlocked)) + XCTAssertTrue(sentNothing(shop)) + sdk.release() + } + + // MARK: - completion and async + + func test_completion_comes_once_on_the_main_thread_whatever_thread_calls() { + let shop = newShop() + let sdk = makeV2(shop) + let calls = Locked(0) + let all = expectation(description: "completions") + all.expectedFulfillmentCount = 3 + DispatchQueue.global().async { + let completion: (Result) -> Void = { _ in + XCTAssertTrue(Thread.isMainThread) + calls.mutate { $0 += 1 } + all.fulfill() + } + sdk.notifications.trackDelivered(code: "m-1", type: "bulk", completion: completion) + sdk.notifications.trackDelivered(code: "", type: "bulk", completion: completion) + sdk.notifications.setPushToken("t-1", provider: .fcm, completion: completion) + } + wait(for: [all], timeout: 5) + drainMainQueue() + XCTAssertEqual(calls.current, 3) + sdk.release() + } + + func test_the_async_forms_return_and_throw_the_result() { + let shop = newShop() + let sdk = makeV2(shop) + XCTAssertEqual(thrown { try await sdk.notifications.trackDelivered(code: "m-1", type: "bulk") }, .some(nil)) + XCTAssertEqual(thrown { try await sdk.notifications.trackOpened(code: "m-1", type: "bulk") }, .some(nil)) + XCTAssertEqual(thrown { try await sdk.notifications.trackClicked(code: "m-1", type: "bulk") }, .some(nil)) + XCTAssertEqual(thrown { try await sdk.notifications.trackClosed(code: "m-1", type: "bulk") }, .some(nil)) + guard case .invalidArgument?? = thrown(cancel: nil, { try await sdk.notifications.trackClicked(code: "", type: "bulk") }) else { + return XCTFail("a blank code") + } + XCTAssertEqual(thrown { try await sdk.notifications.setPushToken("t-1", provider: .fcm) }, .some(nil)) + answer("/mobile_push_tokens", StubReply(400, json: #"{"error":"Token is missing"}"#)) + XCTAssertEqual(thrown { try await sdk.notifications.setPushToken("t-2", provider: .fcm) }, .some(.http(code: 400, serverCode: nil))) + for event in Rees46.PushEvent.allCases { + XCTAssertTrue(eventually { self.requests("/" + event.path, shop).count == 1 }, event.rawValue) + } + sdk.release() + } + + func test_a_cancelled_task_sends_no_event_and_a_cancelled_wait_for_the_token_keeps_it() { + let shop = newShop() + let sdk = makeV2(shop) + let event: Rees46.SdkError?? = thrown(cancel: { $0.cancel() }) { + withUnsafeCurrentTask { $0?.cancel() } + try await sdk.notifications.trackDelivered(code: "m-1", type: "bulk") + } + XCTAssertEqual(event, .some(.cancelled)) + XCTAssertTrue(queueIdle(sdk)) + XCTAssertTrue(requests("/track/delivered", shop).isEmpty) + XCTAssertFalse(PushCenter.isTaken(.delivered, code: "m-1", shopId: shop)) + + // The token waits for a device id; the task stops waiting, the SDK sends it once it has one. + let pending = newShop() + hold("/init") + let waiting = makeV2(pending, identity: InMemoryUserIdentityRepository(), settled: false) + let token: Rees46.SdkError?? = thrown(cancel: { task in + XCTAssertTrue(self.waitForLog(pending, "push_token_skipped", reason: "no_device_id")) + task.cancel() + }) { + try await waiting.notifications.setPushToken("t-1", provider: .apns) + } + XCTAssertEqual(token, .some(.cancelled)) + XCTAssertTrue(requests("/mobile_push_tokens", pending).isEmpty) + release("/init") + XCTAssertTrue(eventually { self.requests("/mobile_push_tokens", pending).count == 1 }) + XCTAssertEqual(waiting.notifications.getPushToken(provider: .apns)?.token, "t-1") + waiting.release() + sdk.release() + } +} diff --git a/DemoApp/Rees46DemoTests/PredictContractTests.swift b/DemoApp/Rees46DemoTests/PredictContractTests.swift new file mode 100644 index 00000000..fccbd569 --- /dev/null +++ b/DemoApp/Rees46DemoTests/PredictContractTests.swift @@ -0,0 +1,114 @@ +// +// PredictContractTests.swift +// REES46Tests +// +// The root method `getProbabilityToPurchase(params:completion:)` on either core, against the contract +// (`sdk/contract/predict.md`): `GET /api/v3/cdp/users/probability-to-purchase` on the shop's +// `appDomain` with the device id and no contact, the answer's `payload` read into the old model, the +// old errors. +// + +import XCTest +@testable import REES46 + +final class PredictContractTests: ContractTestCase { + + private static let path = "/api/v3/cdp/users/probability-to-purchase" + private static let appDomain = "app.cluster.test" + + func test_the_forecast_is_asked_on_the_app_host_for_the_device_and_read_from_the_payload() { + onBothCores(appDomain: Self.appDomain) { sdk in + answer(Self.path, json: #"{"status": "success", "payload": {"probability": 0.42, "client_id": 12345}}"#) + + let params = PurchasePredictParams(email: "buyer@example.com", phone: "+79990000000", telegramId: "777", loyaltyId: "L-1") + let forecast = success(outcome { sdk.getProbabilityToPurchase(params: params, completion: $0) }) + + let sent = request(sdk, Self.path) + XCTAssertEqual(sent?.method, "GET") + XCTAssertEqual(sent?.url?.host, Self.appDomain, "the host of API v3, the shop's appDomain") + XCTAssertEqual(sent?.query["shop_id"], sdk.shopId) + XCTAssertEqual(sent?.query["did"], "stub-did") + XCTAssertEqual(sent?.query["sid"], sdk.getSession()) + XCTAssertEqual(sent?.query["stream"], "ios") + XCTAssertEqual(sent?.query["segment"], sdk.segment) + for contact in ["email", "phone", "telegram_id", "loyalty_id", "external_id", "shop_secret"] { + XCTAssertNil(sent?.query[contact], "the customer is the device id: no \(contact)") + } + XCTAssertTrue(StubURLProtocol.requests(to: "/predict/probability-to-purchase", shop: sdk.shopId).isEmpty, "not the API host's path") + XCTAssertEqual(forecast?.probability, 0.42) + XCTAssertEqual(forecast?.clientId, "12345", "the client's number as a string") + } + } + + func test_a_customer_the_server_does_not_know_is_a_success_with_an_empty_client() { + onBothCores { sdk in + answer(Self.path, json: #"{"status": "success", "payload": {"probability": 0, "client_id": null}}"#) + + let forecast = success(outcome { sdk.getProbabilityToPurchase(params: PurchasePredictParams(), completion: $0) }) + + XCTAssertEqual(sent(sdk)?.url?.host, Rees46Config.defaultAppDomain) + XCTAssertEqual(forecast?.probability, 0) + XCTAssertEqual(forecast?.clientId, "") + } + } + + func test_a_customer_without_events_has_a_zero_probability_and_the_client() { + onBothCores { sdk in + answer(Self.path, json: #"{"status": "success", "payload": {"probability": "0.0", "client_id": "98765"}}"#) + + let forecast = success(outcome { sdk.getProbabilityToPurchase(params: PurchasePredictParams(), completion: $0) }) + + XCTAssertEqual(forecast?.probability, 0) + XCTAssertEqual(forecast?.clientId, "98765") + } + } + + func test_an_error_answer_of_the_server_fails_as_an_invalid_response() { + let refusals = [ + (400, "Shop ID and user identifier are required"), + (402, "Shop does not have access to cdp"), + (403, "Shop is not active"), + (404, "Shop not found"), + ] + onBothCores { sdk in + for (status, message) in refusals { + answer(Self.path, status: status, json: #"{"status": "fail", "message": "\#(message)"}"#) + + let result = outcome { sdk.getProbabilityToPurchase(params: PurchasePredictParams(), completion: $0) } + + guard case .failure(.invalidResponse)? = result else { + XCTFail("\(status): \(String(describing: result))") + continue + } + } + } + } + + func test_an_answer_without_a_numeric_probability_in_its_payload_is_a_decode_error() { + let answers = [ + #"{"status": "success", "payload": {"probability": null, "client_id": 1}}"#, + #"{"status": "success", "payload": {"client_id": 1}}"#, + #"{"status": "success", "payload": {"probability": "high", "client_id": 1}}"#, + #"{"status": "success"}"#, + // The old path's answer, without the payload. + #"{"probability": 0.42, "client_id": 12345}"#, + ] + onBothCores { sdk in + for json in answers { + answer(Self.path, json: json) + + let result = outcome { sdk.getProbabilityToPurchase(params: PurchasePredictParams(), completion: $0) } + + guard case .failure(.decodeError)? = result else { + XCTFail("\(json): \(String(describing: result))") + continue + } + } + } + } + + /// The last request of `sdk`'s shop for the forecast. + private func sent(_ sdk: SimplePersonalizationSDK) -> StubRequest? { + request(sdk, Self.path) + } +} diff --git a/DemoApp/Rees46DemoTests/ReviewsRequestTests.swift b/DemoApp/Rees46DemoTests/ReviewsRequestTests.swift new file mode 100644 index 00000000..eee45469 --- /dev/null +++ b/DemoApp/Rees46DemoTests/ReviewsRequestTests.swift @@ -0,0 +1,241 @@ +// +// ReviewsRequestTests.swift +// REES46Tests +// +// `reviews` end to end over the stub server: each call of the proposed fixture sends its request to its +// host — the polls to `appDomain`, the reviews of products to the API — with the common fields, or +// refuses its argument and sends nothing; each answer ends as the fixture says, its `completion` on the +// main thread; the `async` forms; the old core's refusal of every method. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class ReviewsRequestTests: CoreScenarioTestCase { + + /// The fields the core adds to every request but `/init`. + private static let commonFields: Set = ["shop_id", "did", "sid", "seance", "stream", "segment"] + + /// The paths of the namespace on the stub server. + private static let paths = [ + "/api/v3/polls/nps/reviews", "/api/v3/polls/csat/reviews", "/api/v3/polls/ces/reviews", + "/api/v3/polls/nps/categories", "/api/v3/polls/nps/channels", "/api/v3/polls/csat/campaigns", + "/api/v3/polls/ces/campaigns", "/reviews/product", "/reviews/client", + ] + + private func fixture() throws -> [ContractCase] { + try ContractFixtures.fixture("reviews", from: .proposed) + } + + /// The call of `item` through `sdk.reviews`: what its `completion` got, on the main thread. + private func run(_ item: ContractCase, on sdk: PersonalizationSDK, file: StaticString = #filePath, line: UInt = #line) -> Result? { + guard let call = item.call else { return nil } + let done = expectation(description: item.name) + let outcome = Locked?>(nil) + ReviewsFixtureCalls.run(call, on: sdk.reviews) { result in + XCTAssertTrue(Thread.isMainThread, "\(item.name): completion on the main thread", file: file, line: line) + outcome.current = result + done.fulfill() + } + wait(for: [done], timeout: 5) + return outcome.current + } + + private func sentToTheNamespace(_ shop: String) -> Int { + Self.paths.reduce(0) { $0 + requests($1, shop).count } + } + + // MARK: - Requests + + func test_each_call_of_the_fixture_sends_its_request_to_its_host_with_the_common_fields() throws { + let shop = newShop() + let sdk = makeV2(shop) + let cases = try fixture().filter { $0.request != nil } + XCTAssertGreaterThanOrEqual(cases.count, 12) + for item in cases { + let expected = try XCTUnwrap(item.request) + _ = run(item, on: sdk) + let sent = try XCTUnwrap(requests("/" + expected.path, shop).last, item.name) + XCTAssertEqual(sent.method, expected.method, item.name) + // The polls on the host of API v3 — `app.rees46.ru` unless the config names another —, the + // reviews of products on the API's. + let host = ReviewsFixtureCalls.host(of: expected.path) == .app ? Rees46Config(shopId: shop).appDomain : "stub.test" + XCTAssertEqual(sent.url?.host, host, item.name) + XCTAssertEqual(sent.url?.scheme, "https", item.name) + let isGet = expected.method == "GET" + let fields: [String: Any] = isGet ? sent.query as [String: Any] : sent.body + let listed = isGet ? Array(expected.query.keys) : Array(expected.body.keys) + XCTAssertEqual(Set(fields.keys).subtracting(Self.commonFields), Set(listed), "\(item.name): only the fields the case lists") + if isGet { + for (key, value) in expected.query { + XCTAssertEqual(sent.query[key], value, "\(item.name): \(key)") + } + } else { + for (key, value) in expected.body { + XCTAssertEqual(ReviewsFixtureCalls.canonical(sent.body[key] ?? NSNull()), ReviewsFixtureCalls.canonical(value), "\(item.name): \(key)") + } + } + // What the core adds, on either host: the API v3 finds the customer by the device id too. + XCTAssertEqual(fields["shop_id"] as? String, shop, item.name) + XCTAssertEqual(fields["did"] as? String, "d", item.name) + XCTAssertEqual(fields["sid"] as? String, sdk.sessionId, item.name) + XCTAssertEqual(fields["seance"] as? String, sdk.sessionId, item.name) + XCTAssertEqual(fields["stream"] as? String, "ios", item.name) + XCTAssertEqual(fields["segment"] as? String, sdk.segment, item.name) + XCTAssertEqual(sent.timeout, NetworkClient.defaultTimeout, item.name) + } + sdk.release() + } + + func test_a_call_the_fixture_refuses_is_invalid_argument_and_sends_nothing() throws { + let shop = newShop() + let sdk = makeV2(shop) + let cases = try fixture().filter { $0.call != nil && $0.request == nil && $0.response == nil } + XCTAssertGreaterThanOrEqual(cases.count, 15) + for item in cases { + let result = run(item, on: sdk) + guard case .failure(let error)? = result else { + XCTFail("\(item.name): \(String(describing: result))") + continue + } + XCTAssertTrue(item.expectedError?.matches(error) == true, "\(item.name): \(error)") + } + XCTAssertEqual(sentToTheNamespace(shop), 0, "nothing was sent") + XCTAssertTrue(waitForLog(shop, "invalid_argument")) + XCTAssertTrue(logged(shop, "invalid_argument").allSatisfy { $0.context["call"]?.hasPrefix("reviews.") == true }) + sdk.release() + } + + // MARK: - Answers + + func test_each_answer_of_the_fixture_ends_as_the_fixture_says_without_a_repeat() throws { + let shop = newShop() + let sdk = makeV2(shop) + let cases = try fixture().filter { $0.response != nil } + XCTAssertGreaterThanOrEqual(cases.count, 20) + for item in cases { + let call = try XCTUnwrap(item.call, item.name) + let response = try XCTUnwrap(item.response) + let path = "/" + (try ReviewsFixtureCalls.request(for: call).path) + // No status: no answer — a connection never made. + answer(path, response.status.map { StubReply($0, json: String(decoding: response.body, as: UTF8.self)) } ?? StubReply.noAnswer) + let before = requests(path, shop).count + let result = run(item, on: sdk) + XCTAssertEqual(requests(path, shop).count, before + 1, "\(item.name): one request, not repeated") + switch result { + case .success(let value)?: + XCTAssertNil(item.expectedError, "\(item.name): \(value)") + XCTAssertTrue( + ReviewsFixtureCalls.matches(value, item.expect["result"]), + "\(item.name): \(ReviewsFixtureCalls.canonical(ReviewsFixtureCalls.json(value)))" + ) + case .failure(let error)?: + XCTAssertTrue(item.expectedError?.matches(error) == true, "\(item.name): \(error)") + case nil: + XCTFail("\(item.name): no outcome") + } + } + // A 402, 403 or 404 of one service does not move the state of the instance. + XCTAssertEqual(sdk.state, .ready) + sdk.release() + } + + // MARK: - The host of API v3 + + func test_the_polls_go_to_the_app_domain_of_the_config_and_the_reviews_of_products_to_the_api() { + CoreFlag.reset() + let shop = newShop() + let config = Rees46Config(shopId: shop, apiDomain: "stub.test", appDomain: "app.cluster.test", autoSendPushToken: false) + guard let sdk = Rees46.initializeBridge(config) as? SimplePersonalizationSDK else { + return XCTFail("no instance") + } + answer("/api/v3/polls/nps/channels", StubReply(json: #"{"status":"success","payload":{"channels":[{"code":"ios_app","name":"App"}]}}"#)) + let channels = expectation(description: "getNpsChannels") + let read = Locked<[PollChannel]>([]) + sdk.reviews.getNpsChannels { result in + read.current = (try? result.get()) ?? [] + channels.fulfill() + } + wait(for: [channels], timeout: 15) + XCTAssertEqual(read.current, [PollChannel(code: "ios_app", name: "App")]) + XCTAssertEqual(requests("/api/v3/polls/nps/channels", shop).last?.url?.host, "app.cluster.test") + + let reviews = expectation(description: "getProductReviews") + sdk.reviews.getProductReviews(itemId: "37") { _ in reviews.fulfill() } + wait(for: [reviews], timeout: 15) + XCTAssertEqual(requests("/reviews/product", shop).last?.url?.host, "stub.test") + XCTAssertEqual(requests("/reviews/product", shop).last?.query["product"], "37") + sdk.release() + } + + // MARK: - async + + func test_the_async_forms_return_the_value_and_throw_the_error() { + let shop = newShop() + let sdk = makeV2(shop) + answer("/api/v3/polls/nps/reviews", StubReply(json: #"{"status":"success","payload":{"review":{"id":512}}}"#)) + answer("/api/v3/polls/ces/reviews", StubReply(404, json: #"{"status":"fail","message":"Campaign not found"}"#)) + answer("/reviews/client", StubReply(json: #"{"status":"success","payload":{"reviews":[{"id":1,"product":"37","order":"A-1","rating":5,"state":"published","created_at":"2026-11-10T12:00:00+03:00"}]}}"#)) + let reviews: ReviewsAPI = sdk.reviews + let done = expectation(description: "async") + let outcome = Locked<(PollReview?, Rees46.SdkError?, [ClientReview], Rees46.SdkError?)>((nil, nil, [], nil)) + _Concurrency.Task { + let score = try? await reviews.createNps(rate: 10, channel: "ios_app", category: "delivery") + var failed: Rees46.SdkError? + do { + _ = try await reviews.createCes(rate: 7, channel: "ios_app", campaign: "checkout", orderId: "A-1", comment: nil, label: nil) + } catch { + failed = error as? Rees46.SdkError + } + let mine = (try? await reviews.getClientReviews(orderId: "A-1")) ?? [] + var refused: Rees46.SdkError? + do { + _ = try await reviews.getProductReviews(itemId: "37", limit: 0, offset: nil) + } catch { + refused = error as? Rees46.SdkError + } + outcome.current = (score, failed, mine, refused) + done.fulfill() + } + wait(for: [done], timeout: 10) + XCTAssertEqual(outcome.current.0, PollReview(id: 512)) + XCTAssertEqual(outcome.current.1, .http(code: 404, serverCode: nil)) + XCTAssertEqual(outcome.current.2, [ClientReview(id: 1, itemId: "37", orderId: "A-1", rating: 5, state: .published, createdAt: "2026-11-10T12:00:00+03:00")]) + XCTAssertEqual(outcome.current.3, .invalidArgument("limit must be from 1 to 100")) + // The call without the optional arguments sends none of them. + let score = requests("/api/v3/polls/nps/reviews", shop).last?.body ?? [:] + XCTAssertEqual(Set(score.keys).subtracting(Self.commonFields), ["rate", "channel", "category"]) + XCTAssertEqual(requests("/api/v3/polls/ces/reviews", shop).last?.body["order_id"] as? String, "A-1") + XCTAssertTrue(requests("/reviews/product", shop).isEmpty) + sdk.release() + } + + // MARK: - The new core only + + func test_on_the_old_core_every_method_is_not_initialized_sends_nothing_and_says_why() throws { + let shop = newShop() + let sdk = makeLegacy(shop) + // One call of each method, with arguments it would take. + var calls: [String: ContractCase] = [:] + for item in try fixture() where item.request != nil { + if let method = item.call?.method, calls[method] == nil { + calls[method] = item + } + } + XCTAssertEqual(calls.count, 9) + for item in calls.values { + guard case .failure(let error)? = run(item, on: sdk) else { + XCTFail("\(item.name): not refused") + continue + } + XCTAssertEqual(error, .notInitialized, item.name) + } + XCTAssertEqual(sentToTheNamespace(shop), 0) + XCTAssertTrue(eventually { Set(self.logged(shop, "core_flag_mismatch").compactMap { $0.context["call"] }).count == 9 }) + let said = Set(logged(shop, "core_flag_mismatch").compactMap { $0.context["call"] }) + XCTAssertEqual(said, Set(calls.keys.map { "reviews.\($0)" })) + XCTAssertTrue(logged(shop, "core_flag_mismatch").allSatisfy { $0.level == .warning }) + XCTAssertTrue(heard.filter { $0.shopId == shop }.allSatisfy(LogContract.allows)) + sdk.release() + } +} diff --git a/DemoApp/Rees46DemoTests/StoriesPredictLoyaltySlidersTests.swift b/DemoApp/Rees46DemoTests/StoriesPredictLoyaltySlidersTests.swift new file mode 100644 index 00000000..0ffa09b1 --- /dev/null +++ b/DemoApp/Rees46DemoTests/StoriesPredictLoyaltySlidersTests.swift @@ -0,0 +1,342 @@ +// +// StoriesPredictLoyaltySlidersTests.swift +// REES46Tests +// +// `stories`, `predict`, `loyalty`, `sliders` and the banner events of `tracking` end to end over the +// stub server, by their proposed fixtures: the requests with the common fields, the arguments refused +// without a request, each answer, the old core's refusal, the `async` forms; the banner events through +// the new core's queue. What a method makes of an answer field by field is in the package tests. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class StoriesPredictLoyaltySlidersTests: CoreScenarioTestCase { + + private static let fixtures = ["stories", "predict", "loyalty", "sliders"] + + /// The cases of every fixture of these namespaces, with the file's own case for the query's lists. + private func cases() throws -> [(item: ContractCase, raw: [String: Any])] { + try Self.fixtures.flatMap { name in + try ContractFixtures.cases(name, from: .proposed).map { (ContractCase($0), $0) } + } + } + + // MARK: - Calls + + /// The method of `call` with its arguments, through `completion`; what it got. The completion comes on + /// the main thread. + private func run(_ call: ContractCase.Call, on sdk: PersonalizationSDK, file: StaticString = #filePath, line: UInt = #line) -> Result? { + let done = expectation(description: call.name) + let outcome = Locked?>(nil) + func finish(_ result: Result) { + XCTAssertTrue(Thread.isMainThread, "\(call.name): completion on the main thread", file: file, line: line) + outcome.current = result.map { $0 as Any } + done.fulfill() + } + let args = call.args + let text = { (key: String) in args[key] as? String } + switch call.name { + case "stories.get": + sdk.stories.get(code: text("code") ?? "") { finish($0) } + case "predict.getProbabilityToPurchase": + sdk.predict.getProbabilityToPurchase { finish($0) } + case "loyalty.join": + let gender = text("gender").map { $0 == "male" ? Gender.male : Gender.female } + sdk.loyalty.join( + phone: text("phone") ?? "", firstName: text("firstName"), lastName: text("lastName"), + gender: gender, birthday: text("birthday") + ) { finish($0) } + case "loyalty.getStatus": + sdk.loyalty.getStatus(phone: text("phone") ?? "") { finish($0) } + case "loyalty.getPromotions": + sdk.loyalty.getPromotions( + locationId: text("locationId"), promoCodes: args["promoCodes"] as? [String], + chargeBonuses: args["chargeBonuses"] as? Bool, currentTime: text("currentTime") + ) { finish($0) } + case "sliders.get": + sdk.sliders.get(code: text("code") ?? "", tags: args["tags"] as? [String], locationId: text("locationId")) { finish($0) } + case "tracking.bannerView": + sdk.tracking.bannerView(bannerId: text("bannerId") ?? "", code: text("code") ?? "") { finish($0) } + case "tracking.bannerClick": + sdk.tracking.bannerClick(bannerId: text("bannerId") ?? "", code: text("code") ?? "") { finish($0) } + default: + XCTFail("\(call.name): a method the test does not know", file: file, line: line) + return nil + } + wait(for: [done], timeout: 5) + return outcome.current + } + + private func error(of result: Result?) -> Rees46.SdkError? { + if case .failure(let error)? = result { return error } + return nil + } + + /// Every request of these namespaces the stub saw for `shop`. + private func sent(_ shop: String) -> [StubRequest] { + StubURLProtocol.requests.filter { request in + (request.query["shop_id"] ?? request.body["shop_id"] as? String) == shop + && ["/stories/", "/api/v3/cdp/", "/predict/", "/loyalty/", "/slider", "/track/slider"].contains { request.path.hasPrefix($0) } + } + } + + // MARK: - The fixtures + + func test_each_method_sends_the_fixtures_request_with_the_common_fields() throws { + let shop = newShop() + let sdk = makeV2(shop) + // The events of the banners go through the queue: their own test is below. + let cases = try cases().filter { $0.item.request != nil && $0.item.call?.namespace != "tracking" } + XCTAssertEqual(cases.count, 9) + for (item, raw) in cases { + let call = try XCTUnwrap(item.call, item.name) + let expected = try XCTUnwrap(item.request) + let path = "/" + expected.path + let before = requests(path, shop).count + _ = run(call, on: sdk) + XCTAssertEqual(requests(path, shop).count, before + 1, "\(item.name): one request") + let request = try XCTUnwrap(requests(path, shop).last, item.name) + XCTAssertEqual(request.method, expected.method, item.name) + XCTAssertEqual(request.timeout, NetworkClient.defaultTimeout, "\(item.name): the general timeout") + let rawQuery = (raw["request"] as? [String: Any])?["query"] as? [String: Any] ?? [:] + let items = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems ?? [] + for (key, value) in rawQuery { + if let list = value as? [String] { + XCTAssertEqual(items.filter { $0.name == key }.map(\.value), list, "\(item.name): \(key), a list of Rails") + } else { + XCTAssertEqual(request.query[key], "\(value)", "\(item.name): \(key)") + } + } + for (key, value) in expected.body { + XCTAssertTrue((request.body[key] as AnyObject?)?.isEqual(value) ?? false, "\(item.name): \(key) = \(String(describing: request.body[key]))") + } + // What the core adds: in the query of a GET, in the body of a POST. + let common: [String: String?] = request.method == "GET" + ? ["shop_id": request.query["shop_id"], "did": request.query["did"], "sid": request.query["sid"], + "seance": request.query["seance"], "stream": request.query["stream"], "segment": request.query["segment"]] + : ["shop_id": request.body["shop_id"] as? String, "did": request.body["did"] as? String, + "sid": request.body["sid"] as? String, "seance": request.body["seance"] as? String, + "stream": request.body["stream"] as? String, "segment": request.body["segment"] as? String] + XCTAssertEqual(common["shop_id"], shop, item.name) + XCTAssertEqual(common["did"], "d", item.name) + XCTAssertEqual(common["sid"], sdk.sessionId, item.name) + XCTAssertEqual(common["seance"], sdk.sessionId, "\(item.name): seance, which loyalty's promotions read") + XCTAssertEqual(common["stream"], "ios", item.name) + XCTAssertEqual(common["segment"], sdk.segment, item.name) + // The customer is the device id: no contact, and never the shop's secret. `loyalty.join` sends + // the phone of the member it makes. + for field in ["email", "external_id", "loyalty_id", "telegram_id", "shop_secret"] { + XCTAssertNil(request.query[field], "\(item.name): no \(field)") + XCTAssertNil(request.body[field], "\(item.name): no \(field)") + } + XCTAssertNil(request.query["phone"], "\(item.name): no phone") + if call.name == "predict.getProbabilityToPurchase" { + XCTAssertEqual(request.url?.host, Rees46Config.defaultAppDomain, "\(item.name): on the host of API v3") + } + } + sdk.release() + } + + func test_an_argument_the_contract_refuses_ends_with_invalid_argument_and_sends_nothing() throws { + let shop = newShop() + let sdk = makeV2(shop) + let cases = try cases().filter { $0.item.expectedError != nil && $0.item.response == nil } + XCTAssertEqual(cases.count, 14) + for (item, _) in cases { + let call = try XCTUnwrap(item.call, item.name) + let result = run(call, on: sdk) + guard case .invalidArgument? = error(of: result) else { + XCTFail("\(item.name): \(String(describing: result))") + continue + } + XCTAssertTrue(waitForLog(shop, "invalid_argument"), item.name) + XCTAssertTrue(logged(shop, "invalid_argument").contains { $0.context["call"] == call.name }, item.name) + } + XCTAssertTrue(sent(shop).isEmpty, "\(sent(shop).map(\.path))") + XCTAssertTrue(files(sdk.storage).isEmpty, "no event queued") + sdk.release() + } + + func test_each_answer_of_the_fixtures_ends_as_they_say_without_a_repeat() throws { + let shop = newShop() + let sdk = makeV2(shop) + let cases = try cases().filter { $0.item.response != nil } + XCTAssertFalse(cases.isEmpty) + for (item, _) in cases { + let call = try XCTUnwrap(item.call, item.name) + let response = try XCTUnwrap(item.response) + let path = try XCTUnwrap(Self.path(of: call), item.name) + answer(path, response.status.map { StubReply($0, json: String(decoding: response.body, as: UTF8.self)) } ?? StubReply.noAnswer) + let before = requests(path, shop).count + let result = run(call, on: sdk) + XCTAssertEqual(requests(path, shop).count, before + 1, "\(item.name): one request, not repeated") + switch result { + case .success?: + XCTAssertNil(item.expectedError, item.name) + case .failure(let error)?: + XCTAssertTrue(item.expectedError?.matches(error) == true, "\(item.name): \(error)") + case nil: + XCTFail("\(item.name): no outcome") + } + } + XCTAssertEqual(sdk.state, .ready, "an error of one request does not move the state") + sdk.release() + } + + /// The stub's path of a call with an answer in the fixtures. + private static func path(of call: ContractCase.Call) -> String? { + switch call.name { + case "stories.get": return "/stories/\(call.args["code"] as? String ?? "")" + case "predict.getProbabilityToPurchase": return "/api/v3/cdp/users/probability-to-purchase" + case "loyalty.join": return "/loyalty/members/join" + case "loyalty.getStatus": return "/loyalty/members/status" + case "loyalty.getPromotions": return "/loyalty/promos/for-client" + case "sliders.get": return "/slider" + default: return nil + } + } + + // MARK: - The new core only + + func test_on_the_old_core_every_method_is_not_initialized_sends_nothing_and_logs_core_flag_mismatch() throws { + let shop = newShop() + let sdk = makeLegacy(shop) + let calls = try cases().compactMap { $0.item.request != nil ? $0.item.call : nil } + let names = Set(calls.map(\.name)) + XCTAssertEqual(names.count, 8, "\(names)") + for call in calls { + XCTAssertEqual(error(of: run(call, on: sdk)), .notInitialized, call.name) + } + XCTAssertTrue(sent(shop).isEmpty, "\(sent(shop).map(\.path))") + XCTAssertTrue(waitForLog(shop, "core_flag_mismatch")) + let mismatches = logged(shop, "core_flag_mismatch") + XCTAssertEqual(Set(mismatches.compactMap { $0.context["call"] }), names) + XCTAssertTrue(mismatches.allSatisfy { $0.level == .warning && $0.message.contains("Rees46.initializeBridge") }) + XCTAssertTrue(heard.filter { $0.shopId == shop }.allSatisfy(LogContract.allows)) + sdk.release() + } + + func test_another_conformer_of_the_protocol_is_not_initialized() { + let fake = FakeSDK(shopId: "fake-\(UUID().uuidString)") + let view = ContractCase.Call(namespace: "tracking", method: "bannerView", args: ["bannerId": "12", "code": "main"]) + XCTAssertEqual(error(of: run(view, on: fake)), .notInitialized) + let slider = ContractCase.Call(namespace: "sliders", method: "get", args: ["code": "main"]) + XCTAssertEqual(error(of: run(slider, on: fake)), .notInitialized) + XCTAssertTrue(waitForLog(nil, "not_implemented")) + XCTAssertTrue(logged(nil, "not_implemented").contains { $0.context["call"] == "tracking.bannerView" }) + } + + // MARK: - The events of the banners + + func test_banner_events_complete_once_queued_and_go_with_the_device_and_the_session() throws { + let shop = newShop() + let sdk = makeV2(shop) + answer("/track/slider", StubReply(204, json: "")) + let events = try cases().filter { $0.item.call?.namespace == "tracking" && $0.item.request != nil } + XCTAssertEqual(events.count, 2) + network.isOnline = false + for (item, _) in events { + let result = run(try XCTUnwrap(item.call), on: sdk) + guard case .success? = result else { return XCTFail("\(item.name): \(String(describing: result))") } + } + XCTAssertEqual(files(sdk.storage).count, 2, "accepted: on disk, not sent") + XCTAssertTrue(requests("/track/slider", shop).isEmpty) + + network.isOnline = true + XCTAssertTrue(eventually { self.requests("/track/slider", shop).count == 2 }) + let sent = requests("/track/slider", shop) + for ((item, _), request) in zip(events, sent) { + XCTAssertEqual(request.method, "POST") + for (key, value) in item.request?.body ?? [:] { + XCTAssertTrue((request.body[key] as AnyObject?)?.isEqual(value) ?? false, "\(item.name): \(key) = \(String(describing: request.body[key]))") + } + XCTAssertTrue(request.body["banner_id"] is NSNumber, "\(item.name): banner_id is a number") + XCTAssertNil(request.body["recommended_by"], "\(item.name): the address does not read it") + XCTAssertNil(request.body["source"], item.name) + XCTAssertEqual(request.body["did"] as? String, "d") + XCTAssertEqual(request.body["sid"] as? String, sdk.sessionId) + XCTAssertEqual(request.body["shop_id"] as? String, shop) + } + XCTAssertTrue(queueIdle(sdk)) + XCTAssertTrue(files(sdk.storage).isEmpty, "204: sent") + sdk.release() + } + + func test_a_banner_event_of_a_refused_shop_is_shop_blocked_and_after_release_not_initialized() { + let view = ContractCase.Call(namespace: "tracking", method: "bannerView", args: ["bannerId": "12", "code": "main"]) + let refusedShop = newShop() + answer("/init", StubReply(402, json: #"{"status":"error","message":"Restricted Mode"}"#)) + let refused = makeV2(refusedShop, settled: false) + XCTAssertTrue(eventually { refused.state == .refused }) + XCTAssertEqual(error(of: run(view, on: refused)), .shopBlocked) + refused.release() + + answer("/init") + let shop = newShop() + let sdk = makeV2(shop) + sdk.release() + XCTAssertEqual(error(of: run(view, on: sdk)), .notInitialized) + XCTAssertTrue(requests("/track/slider", shop).isEmpty) + XCTAssertTrue(requests("/track/slider", refusedShop).isEmpty) + } + + // MARK: - async + + func test_the_async_forms_return_the_value_and_throw_the_error() throws { + let shop = newShop() + let sdk = makeV2(shop) + answer("/stories/abc", StubReply(json: #"{"id":35,"stories":[{"id":39,"slides":[]}]}"#)) + answer("/api/v3/cdp/users/probability-to-purchase", StubReply(json: #"{"status":"success","payload":{"probability":0.42,"client_id":null}}"#)) + answer("/loyalty/members/join", StubReply(json: #"{"status":"success","payload":{"identifier":"79991234567"}}"#)) + answer("/loyalty/members/status", StubReply(json: #"{"status":"success","payload":{"member":false,"level":null}}"#)) + answer("/loyalty/promos/for-client", StubReply(json: #"{"status":"success","payload":{"promotions":[{"id":3,"name":"P"}]}}"#)) + answer("/slider", StubReply(404, json: #"{"status":"error","message":"Slider not found"}"#)) + let done = expectation(description: "async") + let outcome = Locked<[String]>([]) + _Concurrency.Task { + var seen: [String] = [] + do { + let block = try await sdk.stories.get(code: "abc") + seen.append("stories \(block.stories.map(\.id))") + let probability = try await sdk.predict.getProbabilityToPurchase() + seen.append("predict \(probability.probability) \(probability.clientId ?? "none")") + let member = try await sdk.loyalty.join(phone: "+79991234567") + seen.append("join \(member.identifier)") + let status = try await sdk.loyalty.getStatus(phone: "+79991234567") + seen.append("status \(status.isMember)") + let promotions = try await sdk.loyalty.getPromotions() + seen.append("promotions \(promotions.map(\.id))") + try await sdk.tracking.bannerView(bannerId: "12", code: "main") + try await sdk.tracking.bannerClick(bannerId: "12", code: "main") + seen.append("banners") + _ = try await sdk.sliders.get(code: "nope") + } catch let error as Rees46.SdkError { + seen.append("\(error)") + } catch { + seen.append("not an SdkError: \(error)") + } + do { + try await sdk.tracking.bannerView(bannerId: "", code: "main") + } catch let error as Rees46.SdkError { + if case .invalidArgument = error { seen.append("invalidArgument") } + } catch { + seen.append("not an SdkError: \(error)") + } + outcome.current = seen + done.fulfill() + } + wait(for: [done], timeout: 10) + XCTAssertEqual(outcome.current, [ + "stories [\"39\"]", + "predict 0.42 none", + "join 79991234567", + "status false", + "promotions [3]", + "banners", + "\(Rees46.SdkError.http(code: 404, serverCode: nil))", + "invalidArgument", + ]) + sdk.release() + } +} diff --git a/DemoApp/Rees46DemoTests/StubServer.swift b/DemoApp/Rees46DemoTests/StubServer.swift index 6882e2b2..46da0303 100644 --- a/DemoApp/Rees46DemoTests/StubServer.swift +++ b/DemoApp/Rees46DemoTests/StubServer.swift @@ -338,6 +338,7 @@ enum StubSDK { environment: CoreEnvironment? = nil, shopStorage: ShopStorage? = nil, deviceStore: DeviceStore? = nil, + appDomain: String = Rees46Config.defaultAppDomain, completion: ((SdkError?) -> Void)? = nil ) -> SimplePersonalizationSDK { // The core a stub SDK asks for is the one it gets: the process's flag is the test's to set. @@ -352,6 +353,7 @@ enum StubSDK { enableAutoPopupPresentation: false, needReInitialization: needReInitialization, coreV2: coreV2, + appDomain: appDomain, deviceId: deviceId, environment: environment, userIdentity: identity, diff --git a/DemoApp/Rees46DemoTests/TrackingBackCompatTests.swift b/DemoApp/Rees46DemoTests/TrackingBackCompatTests.swift index 168b2ac0..2a799f36 100644 --- a/DemoApp/Rees46DemoTests/TrackingBackCompatTests.swift +++ b/DemoApp/Rees46DemoTests/TrackingBackCompatTests.swift @@ -1,5 +1,5 @@ import XCTest -@testable import REES46 +@_spi(Bridge) @testable import REES46 /// Guards the upgrade path: everything the `tracking` namespace touched has to keep working for /// code written against the previous release — conformers of `PersonalizationSDK`, the old diff --git a/DemoApp/Rees46DemoTests/TrackingNamespaceTests.swift b/DemoApp/Rees46DemoTests/TrackingNamespaceTests.swift index 39c30959..4f75e8fa 100644 --- a/DemoApp/Rees46DemoTests/TrackingNamespaceTests.swift +++ b/DemoApp/Rees46DemoTests/TrackingNamespaceTests.swift @@ -1,5 +1,5 @@ import XCTest -@testable import REES46 +@_spi(Bridge) @testable import REES46 /// Covers the `tracking` namespace: that every method maps onto the event the API expects, and /// that the two fields added with the namespace (cart price, search results) reach the wire. diff --git a/REES46/Classes/Cart/CartAPI.swift b/REES46/Classes/Cart/CartAPI.swift new file mode 100644 index 00000000..67e2659a --- /dev/null +++ b/REES46/Classes/Cart/CartAPI.swift @@ -0,0 +1,54 @@ +// +// CartAPI.swift +// REES46 +// +// The `cart` namespace of the contract (`sdk/contract/cart.md`). +// + +import Foundation + +/** + The customer's cart as the server keeps it: the server puts it together from the cart events of + `tracking` (`addToCart`, `syncCart`, `removeFromCart`). For showing a cart filled on another device or + on the site, or checking it against the app's own. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + */ +@_spi(Bridge) +public protocol CartAPI { + + /** + What the cart holds (`GET products/cart`): one `CartItem` per product, with its `id` and + `quantity`; an empty cart is an empty list. The server finds the cart by the device id alone. + + `completion` is called once, on the main thread, with the list or the error: `notInitialized` on + the old core or after `release()`, `shopBlocked`, `network`, `timeout`, `http(code:serverCode:)` — + `404` for a device the server does not know —, `decoding` for an answer in neither shape of the + API, `cancelled` for a call `release()` ended. Nothing is repeated: the app decides. + */ + func get(completion: @escaping (Result<[CartItem], Rees46.SdkError>) -> Void) + + /// `get(completion:)` for `async` code: throws the `Rees46.SdkError`; cancelling the task ends the + /// call as `cancelled`. + func get() async throws -> [CartItem] +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The customer's cart on the server (`CartAPI`): on the new core only. + public var cart: CartAPI { + CartAPIImpl(requests: NamespaceRequests(self)) + } +} + +@_spi(Bridge) +extension CartItem { + + /// The product's id (`uniqid` of the answer): the name `cart.get` gives `productId`. + public var id: String { + productId + } +} diff --git a/REES46/Classes/Cart/CartAPIImpl.swift b/REES46/Classes/Cart/CartAPIImpl.swift new file mode 100644 index 00000000..a393c41a --- /dev/null +++ b/REES46/Classes/Cart/CartAPIImpl.swift @@ -0,0 +1,57 @@ +// +// CartAPIImpl.swift +// REES46 +// + +import Foundation + +struct CartAPIImpl: CartAPI { + + let requests: NamespaceRequests + + func get(completion: @escaping (Result<[CartItem], Rees46.SdkError>) -> Void) { + requests.call("cart.get", completion: completion) { Self.cartRequest } + } + + func get() async throws -> [CartItem] { + try await requests.value("cart.get") { Self.cartRequest } + } + + /// `GET products/cart` with nothing but the common fields the core adds: the API finds the cart by the + /// device id. An answer without a body is an empty cart. + static var cartRequest: ApiRequest<[CartItem]> { + .get("products/cart", answer: CartAnswer.self, whenEmpty: []) { $0.items } + } +} + +/// The answer of `GET products/cart` in either of its shapes (`sdk/contract/cart.md`), as Android reads it: +/// today's `{"status": "success", "data": {"items": [...]}}`, else the documented +/// `{"status": "success", "payload": {"cart_items": [...]}}`, so the server's move to the second one +/// breaks nothing. Without a list in either place it is not a cart (`decoding`). +struct CartAnswer: Decodable { + + let items: [CartItem] + + init(from decoder: Decoder) throws { + let root = try decoder.container(keyedBy: AnswerKey.self) + let lines = (try? root.nestedContainer(keyedBy: AnswerKey.self, forKey: "data"))?.lenientList(Line.self, "items") + ?? (try? root.nestedContainer(keyedBy: AnswerKey.self, forKey: "payload"))?.lenientList(Line.self, "cart_items") + guard let lines = lines else { + throw DecodingError.dataCorrupted(DecodingError.Context( + codingPath: decoder.codingPath, + debugDescription: "neither data.items nor payload.cart_items is a list" + )) + } + items = lines.compactMap(\.item) + } + + /// One line: a product without an id is left out, one without a quantity is one of it. + private struct Line: Decodable { + let item: CartItem? + + init(from decoder: Decoder) throws { + let line = try decoder.container(keyedBy: AnswerKey.self) + item = line.lenientString("uniqid").map { CartItem(productId: $0, quantity: line.lenientInt("quantity") ?? 1) } + } + } +} diff --git a/REES46/Classes/Collections/CollectionsAPI.swift b/REES46/Classes/Collections/CollectionsAPI.swift new file mode 100644 index 00000000..e0ec99db --- /dev/null +++ b/REES46/Classes/Collections/CollectionsAPI.swift @@ -0,0 +1,82 @@ +// +// CollectionsAPI.swift +// REES46 +// +// The `collections` namespace of the contract (`sdk/contract/collections.md`). +// + +import Foundation + +/** + The shop's product collections: sets of products it makes by rules in its account. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + */ +@_spi(Bridge) +public protocol CollectionsAPI { + + /** + The products of a collection (`GET collection/{collectionId}`), for the customer of the device. + + `completion` is called once, on the main thread, with the collection or the error: `notInitialized` + on the old core or after `release()`, `shopBlocked`, `invalidArgument` for an empty `collectionId`, + `network`, `timeout`, `http(code:serverCode:)` — `400` for a collection that does not exist or is + not active —, `decoding` for an answer without products, `cancelled` for a call `release()` ended. + Nothing is repeated: the app decides. + */ + func get(collectionId: String, completion: @escaping (Result) -> Void) + + /// `get(collectionId:completion:)` for `async` code: throws the `Rees46.SdkError`; cancelling the task + /// ends the call as `cancelled`. + func get(collectionId: String) async throws -> Rees46.CollectionResponse +} + +@_spi(Bridge) +extension Rees46 { + + /// The products of a collection (`collections.get`). + public struct CollectionResponse: Equatable { + public let products: [Product] + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The shop's product collections (`CollectionsAPI`): on the new core only. + public var collections: CollectionsAPI { + CollectionsAPIImpl(requests: NamespaceRequests(self)) + } +} + +struct CollectionsAPIImpl: CollectionsAPI { + + let requests: NamespaceRequests + + func get(collectionId: String, completion: @escaping (Result) -> Void) { + requests.call("collections.get", completion: completion) { try Self.collectionRequest(collectionId: collectionId) } + } + + func get(collectionId: String) async throws -> Rees46.CollectionResponse { + try await requests.value("collections.get") { try Self.collectionRequest(collectionId: collectionId) } + } + + /// `GET collection/{id}`, the id encoded in the path, without the contacts of the customer: the + /// server finds the customer by the device id. + static func collectionRequest(collectionId: String) throws -> ApiRequest { + let id = try CatalogQuery.identifier(collectionId, "collectionId") + return ApiRequest(method: .get, path: "collection/\(CatalogQuery.pathSegment(id))") { body in + try Readable.read(body) + } + } +} + +extension Rees46.CollectionResponse: AnswerReadable { + + /// Without a list of products it is not a collection (`decoding`). + init(answer: KeyedDecodingContainer) throws { + products = try answer.requiredModels(Rees46.Product.self, "products") + } +} diff --git a/REES46/Classes/Core/Core.swift b/REES46/Classes/Core/Core.swift index 9efde07c..f0fc933b 100644 --- a/REES46/Classes/Core/Core.swift +++ b/REES46/Classes/Core/Core.swift @@ -40,6 +40,12 @@ struct CoreRequest { /// event of a push carries none (`EventQueue.sessionlessPaths`): it renews no session and asks no /// `/init`, the one it is sent once as when the disk refused it included. var needsSession = true + /// Query fields that repeat, the way Rails reads a list: `promo_codes[]` with `A` and `B` goes as + /// `promo_codes[]=A&promo_codes[]=B`. Only the new core sends them: the namespaces' methods run on it. + var queryLists: [String: [String]] = [:] + /// The host of this request alone, without a scheme — the host of API v3, `Rees46Config.appDomain`; + /// `nil` is the API host, `apiDomain`. Both cores send it there. + var host: String? /// `/init`: its own timeout, and in `CoreV2` the only request that may wait for the network. var isInit: Bool { path == "init" } diff --git a/REES46/Classes/Core/CoreV2.swift b/REES46/Classes/Core/CoreV2.swift index 916443d0..8f7d1ffe 100644 --- a/REES46/Classes/Core/CoreV2.swift +++ b/REES46/Classes/Core/CoreV2.swift @@ -49,20 +49,50 @@ final class CoreV2: Core { /// the session: it fails at once, as any request does offline. One that needs no session — an event /// of a push — neither renews nor waits for it. func send(_ request: CoreRequest, completion: @escaping (CoreResponse) -> Void) { + let callbacks = self.callbacks + switch flight(of: request) { + case .settled(let response): + callbacks.async { completion(Self.legacyResponse(response, for: request)) } + case .pending(let fly): + _Concurrency.Task { + let response = await fly() + callbacks.async { completion(Self.legacyResponse(response, for: request)) } + } + } + } + + /// `send` for the methods of the namespaces (`NamespaceRequests`): the same path, answered with the + /// new core's result, in the caller's task — cancelling the task cancels the request, also while it + /// waits for the instance to be usable, and it ends as `cancelled`. + func response(to request: CoreRequest) async -> NetworkClient.Response { + switch flight(of: request) { + case .settled(let response): + return response + case .pending(let fly): + return await fly() + } + } + + /// A request's way out: settled at once, or the work that waits for the instance and sends it. + private enum Flight { + case settled(NetworkClient.Response) + case pending(() async -> NetworkClient.Response) + } + + /// What `send` and `response(to:)` do with `request`: the checks and the session's renewal at the + /// call, the wait and the request in the work it hands back. + private func flight(of request: CoreRequest) -> Flight { lock.lock() let isReleased = released lock.unlock() - let callbacks = self.callbacks // A call after `release()` is `notInitialized`; the ones in flight end as `cancelled`. guard !isReleased else { - callbacks.async { completion(Self.legacyResponse(.failure(.notInitialized), for: request)) } - return + return .settled(.failure(.notInitialized)) } // A refused shop sends nothing, its own `/init` of the funnel (`sendIDFARequest`) included: only // the machine's `/init` of the next launch asks again. if request.isInit, machine.isRefused { - callbacks.async { completion(Self.legacyResponse(.failure(.shopBlocked), for: request)) } - return + return .settled(.failure(.shopBlocked)) } let client = self.client let machine = self.machine @@ -72,22 +102,24 @@ final class CoreV2: Core { if needsSession, !session.isAlive { machine.renewSession() } - var clientRequest = NetworkClient.Request( + let clientRequest = NetworkClient.Request( method: request.method, path: request.path, query: request.query, body: request.body, timeout: request.timeout, - waitsForNetwork: request.isInit && request.waitsForNetwork + waitsForNetwork: request.isInit && request.waitsForNetwork, + queryLists: request.queryLists, + host: request.host ) let wait = request.isInit ? nil : (request.timeout ?? NetworkClient.defaultTimeout) - _Concurrency.Task { + return .pending { + var clientRequest = clientRequest if let wait = wait, let refusal = await machine.awaitUsable(timeout: wait, needsSession: needsSession) { if refusal == .cancelled { logger.requestCancelled(request.method.rawValue, request.path) } - callbacks.async { completion(Self.legacyResponse(.failure(refusal), for: request)) } - return + return .failure(refusal) } if needsSession { Self.stampSession(session.sid, on: &clientRequest) @@ -96,13 +128,11 @@ final class CoreV2: Core { // The customer it was made for, checked and taken together after the wait. guard let taken = identity() else { logger.requestCancelled(request.method.rawValue, request.path) - callbacks.async { completion(Self.legacyResponse(.failure(.cancelled), for: request)) } - return + return .failure(.cancelled) } clientRequest.identity = taken } - let response = await client.send(clientRequest) - callbacks.async { completion(Self.legacyResponse(response, for: request)) } + return await client.send(clientRequest) } } diff --git a/REES46/Classes/Core/InitMachine.swift b/REES46/Classes/Core/InitMachine.swift index 935bb65e..a6658151 100644 --- a/REES46/Classes/Core/InitMachine.swift +++ b/REES46/Classes/Core/InitMachine.swift @@ -405,28 +405,38 @@ final class InitMachine { /// Waits until calls may go out, at most `timeout`: `nil` once they may; `shopBlocked` when the /// shop refused; `timeout` when the instance did not get there in time; `notInitialized` after - /// `release()`, and `cancelled` for a call `release()` ended while it waited. With `needsSession`, a - /// call to a `ready` instance whose session's window ran out waits for the `/init` on its way — the - /// one of the launch, say —, so it goes with the new `sid`. + /// `release()`, and `cancelled` for a call `release()` ended while it waited, or whose task was + /// cancelled. With `needsSession`, a call to a `ready` instance whose session's window ran out waits + /// for the `/init` on its way — the one of the launch, say —, so it goes with the new `sid`. func awaitUsable(timeout: TimeInterval, needsSession: Bool = false) async -> Rees46.SdkError? { - await withCheckedContinuation { (continuation: CheckedContinuation) in - lock.lock() - switch gateLocked(needsSession: needsSession) { - case .pass: - lock.unlock() - continuation.resume(returning: nil) - case .fail(let error): - lock.unlock() - continuation.resume(returning: error) - case .wait: - let id = UUID() - let waiter = Waiter(continuation, needsSession: needsSession) - waiters[id] = waiter - waiter.timeout = environment.scheduler.schedule(after: timeout) { [weak self] in - self?.expire(id) + let id = UUID() + return await withTaskCancellationHandler { + await withCheckedContinuation { (continuation: CheckedContinuation) in + lock.lock() + switch gateLocked(needsSession: needsSession) { + case .pass: + lock.unlock() + continuation.resume(returning: nil) + case .fail(let error): + lock.unlock() + continuation.resume(returning: error) + case .wait: + // Cancelled before it waits — `abandon` found nothing to end —, the call does not wait. + guard !_Concurrency.Task.isCancelled else { + lock.unlock() + continuation.resume(returning: .cancelled) + return + } + let waiter = Waiter(continuation, needsSession: needsSession) + waiters[id] = waiter + waiter.timeout = environment.scheduler.schedule(after: timeout) { [weak self] in + self?.expire(id) + } + lock.unlock() } - lock.unlock() } + } onCancel: { [weak self] in + self?.abandon(id) } } @@ -469,6 +479,15 @@ final class InitMachine { waiter?.continuation.resume(returning: .timeout) } + /// A call whose task was cancelled while it waited ends as `cancelled`. + private func abandon(_ id: UUID) { + lock.lock() + let waiter = waiters.removeValue(forKey: id) + lock.unlock() + waiter?.timeout?.cancel() + waiter?.continuation.resume(returning: .cancelled) + } + /// Lets through or fails every waiting call the state now decides. Under `lock`. private func settleWaitersLocked() { for (id, waiter) in waiters { diff --git a/REES46/Classes/Core/LegacyCore.swift b/REES46/Classes/Core/LegacyCore.swift index 00f0a3c3..3d7d5dca 100644 --- a/REES46/Classes/Core/LegacyCore.swift +++ b/REES46/Classes/Core/LegacyCore.swift @@ -75,7 +75,7 @@ final class LegacyCore: Core { private func get(_ request: CoreRequest, completion: @escaping (CoreResponse) -> Void) { let path = request.path - var url = URLComponents(string: baseURL + path) + var url = URLComponents(string: base(of: request) + path) var queryItems = request.query.map { URLQueryItem(name: $0.key, value: $0.value) } queryItems.append(URLQueryItem(name: "stream", value: stream)) url?.queryItems = queryItems @@ -114,7 +114,7 @@ final class LegacyCore: Core { private func post(_ request: CoreRequest, completion: @escaping (CoreResponse) -> Void) { let path = request.path - guard let url = URL(string: baseURL + path) else { + guard let url = URL(string: base(of: request) + path) else { logger.error(LogCode.requestBuildFailed, "\(SdkLogger.requestLine("POST", path)) could not be built", ["method": "POST", "path": path]) completion(CoreResponse(status: nil, body: Data(), result: .failure(.invalidResponse), error: .invalidArgument("the path \(path) is not a URL path"))) return @@ -173,6 +173,11 @@ final class LegacyCore: Core { // MARK: - Helpers + /// The URL `request`'s path goes under: the API host, or the request's own (`CoreRequest.host`). + private func base(of request: CoreRequest) -> String { + request.host.map { "https://\($0)/" } ?? baseURL + } + /// A request with the call's own timeout. The session is shared: a call that swapped in a session /// with its own timeout changed it for every call in flight on the session queue. It neither sends /// nor stores cookies, whatever the session — the app may have set one of its own (`urlSession`). diff --git a/REES46/Classes/Core/Network/NetworkClient.swift b/REES46/Classes/Core/Network/NetworkClient.swift index 1e9b7360..5a056cdb 100644 --- a/REES46/Classes/Core/Network/NetworkClient.swift +++ b/REES46/Classes/Core/Network/NetworkClient.swift @@ -30,6 +30,11 @@ actor NetworkClient { /// it — an event of the queue — instead of the ones stored when the request is built: a /// `deleteUserCredentials()` in between does not move it to the next customer's did. var identity: CommonFields.Identity? + /// Query fields that repeat (`CoreRequest.queryLists`): after the others. + var queryLists: [String: [String]] = [:] + /// The host of this request alone, without a scheme: the host of API v3 (`appDomain`). `nil` is + /// the client's, the API host. + var host: String? } struct Response { @@ -294,6 +299,7 @@ actor NetworkClient { fields = fields.with(identity) } var urlRequest: URLRequest + let baseURL = request.host.map { "https://\($0)/" } ?? self.baseURL switch request.method { case .get: let query = fields.apply(to: request.query, path: request.path) @@ -301,6 +307,9 @@ actor NetworkClient { return .failure(.invalidArgument("the path \(request.path) is not a URL path")) } components.queryItems = query.keys.sorted().map { URLQueryItem(name: $0, value: query[$0]) } + + request.queryLists.keys.sorted().flatMap { name in + (request.queryLists[name] ?? []).map { URLQueryItem(name: name, value: $0) } + } // URLComponents leaves "+" as it is, and the server reads it as a space: a phone number // "+7…" would lose its plus. components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") diff --git a/REES46/Classes/Core/Requests/ApiArguments.swift b/REES46/Classes/Core/Requests/ApiArguments.swift new file mode 100644 index 00000000..aea2f46f --- /dev/null +++ b/REES46/Classes/Core/Requests/ApiArguments.swift @@ -0,0 +1,52 @@ +// +// ApiArguments.swift +// REES46 +// +// The text arguments of the namespaces' methods (`sdk..`) as the contract reads them +// (`sdk/contract/README.md`): a required one may not be blank, an optional blank one is not sent. +// + +import Foundation + +enum ApiArguments { + + /// Empty or only whitespace: a required text the contract refuses as `invalidArgument`. + static func isBlank(_ text: String) -> Bool { + text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + /// An optional text as it is sent: `nil`, empty and blank are none. + static func given(_ text: String?) -> String? { + text.flatMap { isBlank($0) ? nil : $0 } + } + + /// An existing day of the calendar as `YYYY-MM-DD`, of ASCII digits: `2026-02-30` is none. A birthday + /// `loyalty/members/join` cannot read erases the date it has. + static func isCalendarDate(_ text: String) -> Bool { + calendarYear(text) != nil + } + + /// A birthday `profile/set` takes: an existing day `YYYY-MM-DD` of the years 1000 to 2999. The server + /// ignores any other in silence. + static func isBirthday(_ text: String) -> Bool { + calendarYear(text).map { (1000...2999).contains($0) } ?? false + } + + /// The year of `text` when it is an existing day of the calendar as `YYYY-MM-DD`; `nil` otherwise. + private static func calendarYear(_ text: String) -> Int? { + let parts = text.split(separator: "-", omittingEmptySubsequences: false) + guard parts.count == 3, parts[0].count == 4, parts[1].count == 2, parts[2].count == 2, + parts.allSatisfy({ $0.allSatisfy { $0.isASCII && $0.isNumber } }), + let year = Int(parts[0]), let month = Int(parts[1]), let day = Int(parts[2]) + else { return nil } + let days: Int + switch month { + case 1, 3, 5, 7, 8, 10, 12: days = 31 + case 4, 6, 9, 11: days = 30 + case 2: days = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ? 29 : 28 + default: days = 0 + } + guard days > 0, (1...days).contains(day) else { return nil } + return year + } +} diff --git a/REES46/Classes/Core/Requests/ApiRequest.swift b/REES46/Classes/Core/Requests/ApiRequest.swift new file mode 100644 index 00000000..28e5b64b --- /dev/null +++ b/REES46/Classes/Core/Requests/ApiRequest.swift @@ -0,0 +1,65 @@ +// +// ApiRequest.swift +// REES46 +// +// One request of a namespace's method (`sdk..`): what it sends and how the answer +// becomes the method's value. `NamespaceRequests` sends it through the new core. +// + +import Foundation + +struct ApiRequest { + + let method: CoreRequest.Method + /// The path under the API host, without a leading slash: `products/cart`. + let path: String + /// The query of a `GET`, without the common fields: the core adds them (`CommonFields`). + var query: [String: String] = [:] + /// The JSON body of a `POST`, without the common fields. + var body: [String: Any] = [:] + /// Query fields that repeat, as Rails reads a list: `promo_codes[]=A&promo_codes[]=B`. + var queryLists: [String: [String]] = [:] + /// The read timeout of this request alone; `nil` is the default one (`sdk/core/network.md`). + var timeout: TimeInterval? + /// The host it goes to: the API's, or API v3's for the methods the contract puts there. + var host: ApiHost = .api + /// The method's value of a `2xx` answer's body — empty when the answer had none; throws when the + /// body is not one (`decoding`). + let decode: (Data) throws -> Value + + /// The request as the core sends it. + var coreRequest: CoreRequest { + CoreRequest(method: method, path: path, query: query, body: body, timeout: timeout, queryLists: queryLists) + } +} + +/// The host of a namespace's request (`sdk/core/network.md`, "Хосты"): the namespace's file of the +/// contract names the methods that do not go to the API host. +enum ApiHost: Equatable { + /// `Rees46Config.apiDomain`: the API. + case api + /// `Rees46Config.appDomain`: API v3, on the host of the shop's account. + case app +} + +extension ApiRequest { + + /// A `GET` whose answer reads as `Answer` (`LenientDecoding`), made into the value by `value`. An + /// answer without a body is `whenEmpty` — a `2xx` without one is a success with an empty result + /// (`sdk/core/network.md`) —, or `decoding` for a method that has no empty value. + static func get( + _ path: String, + query: [String: String] = [:], + timeout: TimeInterval? = nil, + answer: Answer.Type, + whenEmpty: Value? = nil, + value: @escaping (Answer) -> Value + ) -> ApiRequest { + ApiRequest(method: .get, path: path, query: query, timeout: timeout) { body in + if body.isEmpty, let empty = whenEmpty { + return empty + } + return value(try JSONDecoder().decode(Answer.self, from: body)) + } + } +} diff --git a/REES46/Classes/Core/Requests/LenientDecoding.swift b/REES46/Classes/Core/Requests/LenientDecoding.swift new file mode 100644 index 00000000..83ab0655 --- /dev/null +++ b/REES46/Classes/Core/Requests/LenientDecoding.swift @@ -0,0 +1,189 @@ +// +// LenientDecoding.swift +// REES46 +// +// How the answers of the namespaces' methods are read with `Codable` (`sdk/contract/README.md`, +// "Ответы"): a field that is missing, `null` or of a type that does not fit is empty, not a failure; a +// number may come as a string and a string as a number; an unknown value of an enumeration is empty; +// an element of a list that does not read is left out; fields the SDK does not know are ignored. +// `decoding` is only for an answer that does not read into the method's model at all. +// +// The answers are read into internal types (`Decodable` here), and the method's public model is made +// from them: a public model that is `Decodable` would hand its decoding to the app as API. +// + +import Foundation + +/// One JSON scalar, whatever its type. +private enum LenientScalar: Decodable { + case bool(Bool) + case int(Int) + case double(Double) + case string(String) + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + // A JSON boolean reads only as `Bool`, a number never does: the order keeps `1` a number. + if let value = try? container.decode(Bool.self) { + self = .bool(value) + } else if let value = try? container.decode(Int.self) { + self = .int(value) + } else if let value = try? container.decode(Double.self) { + self = .double(value) + } else if let value = try? container.decode(String.self) { + self = .string(value) + } else { + throw DecodingError.typeMismatch( + LenientScalar.self, + DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "not a scalar") + ) + } + } + + /// A string: a number as its digits — an integral one without a fraction —; an empty or blank string + /// is none. + var string: String? { + switch self { + case .string(let value): + return value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : value + case .int(let value): + return String(value) + case .double(let value): + guard value.isFinite else { return nil } + return Self.integral(value).map(String.init) ?? String(value) + case .bool: + return nil + } + } + + /// An integer: a number without a fraction, or a string of one. + var int: Int? { + switch self { + case .int(let value): + return value + case .double(let value): + return Self.integral(value) + case .string(let value): + let text = value.trimmingCharacters(in: .whitespaces) + return Int(text) ?? Double(text).flatMap(Self.integral) + case .bool: + return nil + } + } + + /// A finite number, or a string of one. + var double: Double? { + let value: Double? + switch self { + case .int(let int): + value = Double(int) + case .double(let double): + value = double + case .string(let text): + value = Double(text.trimmingCharacters(in: .whitespaces)) + case .bool: + value = nil + } + return value.flatMap { $0.isFinite ? $0 : nil } + } + + /// A boolean: `true`/`false`, `1`/`0`, or a string of one of them. + var bool: Bool? { + switch self { + case .bool(let value): + return value + case .int(let value): + return value == 1 ? true : value == 0 ? false : nil + case .double(let value): + return value == 1 ? true : value == 0 ? false : nil + case .string(let value): + switch value.trimmingCharacters(in: .whitespaces).lowercased() { + case "true", "1": return true + case "false", "0": return false + default: return nil + } + } + } + + /// `value` as an `Int` when it has no fraction and fits one. + private static func integral(_ value: Double) -> Int? { + guard value.isFinite, value.rounded() == value, abs(value) < 9.0e15 else { return nil } + return Int(value) + } +} + +/// Whatever an element of a list is: it reads, or the list leaves it out. +private struct Lossy: Decodable { + let value: Element? + + init(from decoder: Decoder) throws { + value = try? Element(from: decoder) + } +} + +extension KeyedDecodingContainer { + + /// The string at `key`; a number is its digits. Missing, `null`, empty, blank or not a scalar: `nil`. + func lenientString(_ key: Key) -> String? { + scalar(key)?.string + } + + /// The integer at `key`, from a number without a fraction or a string of one; otherwise `nil`. + func lenientInt(_ key: Key) -> Int? { + scalar(key)?.int + } + + /// The number at `key`, from a number or a string of one; otherwise `nil`. + func lenientDouble(_ key: Key) -> Double? { + scalar(key)?.double + } + + /// The boolean at `key`, from `true`/`false`, `1`/`0` or a string of them; otherwise `nil`. + func lenientBool(_ key: Key) -> Bool? { + scalar(key)?.bool + } + + /// The value of an enumeration at `key`; a value the SDK does not know — the server added one — is + /// `nil`, not a failure. + func lenientEnum(_ type: Value.Type, _ key: Key) -> Value? where Value.RawValue == String { + lenientString(key).flatMap(Value.init(rawValue:)) + } + + /// The object at `key`; `nil` when it is missing, `null` or does not read as `Value`. + func lenient(_ type: Value.Type, _ key: Key) -> Value? { + (try? decodeIfPresent(Lossy.self, forKey: key))?.value + } + + /// The list at `key` without the elements that do not read; `nil` when it is missing, `null` or not + /// a list. + func lenientList(_ type: Element.Type, _ key: Key) -> [Element]? { + guard let list = try? decodeIfPresent([Lossy].self, forKey: key) else { return nil } + return list.compactMap(\.value) + } + + private func scalar(_ key: Key) -> LenientScalar? { + try? decodeIfPresent(LenientScalar.self, forKey: key) + } +} + +/// A coding key of any name: what an answer's own keys are read with. +struct AnswerKey: CodingKey, ExpressibleByStringLiteral { + let stringValue: String + let intValue: Int? = nil + + init(_ name: String) { + stringValue = name + } + + init(stringLiteral name: String) { + stringValue = name + } + + init?(stringValue: String) { + self.stringValue = stringValue + } + + init?(intValue: Int) { + return nil + } +} diff --git a/REES46/Classes/Core/Requests/NamespaceRequests.swift b/REES46/Classes/Core/Requests/NamespaceRequests.swift new file mode 100644 index 00000000..c7d98a86 --- /dev/null +++ b/REES46/Classes/Core/Requests/NamespaceRequests.swift @@ -0,0 +1,134 @@ +// +// NamespaceRequests.swift +// REES46 +// +// The one way the methods of the namespaces (`sdk..`, all but `tracking`) reach the +// API: a request of the new core with its value or a `Rees46.SdkError` (`sdk/core/errors.md`), and the +// pair the contract gives every method (`sdk/contract/README.md`, "Результат и ошибки") — a +// `completion` called once on the main thread, and an `async throws` form. +// + +import Foundation + +// `_Concurrency.Task`: the module has a `Task` class of its own (the stories image loader). + +/// The namespaces' requests of one instance. +/// +/// The namespaces run on the new core only, the bridges' (`Rees46.initializeBridge`). On an instance of +/// the old core every method ends as `notInitialized`, sends nothing and logs `core_flag_mismatch`, as on +/// Android; on a conformer of `PersonalizationSDK` other than the SDK's own it ends the same way and logs +/// `not_implemented`. On the new core a request waits for the instance to be usable, at most its timeout, +/// and goes with the current device id and session; nothing repeats it (`sdk/core/network.md`). +/// `release()` ends the calls on their way as `cancelled`, later ones as `notInitialized`. +struct NamespaceRequests { + + private weak var instance: SimplePersonalizationSDK? + /// Whether it was made for the SDK's own instance: once that is gone, a call is `notInitialized`. + private let isTheSdks: Bool + + init(_ sdk: PersonalizationSDK) { + instance = sdk as? SimplePersonalizationSDK + isTheSdks = instance != nil + } + + /// The value of the method `name` (`cart.get`, what the log calls it) or its error. `make` builds the + /// request once the instance takes the call; it throws `Rees46.SdkError.invalidArgument` for an + /// argument the contract refuses, and then nothing is sent. Cancelling the task cancels the call. + func result(_ name: String, _ make: () throws -> ApiRequest) async -> Result { + // `usesCoreV2` is what makes the core a `CoreV2` (`makeCore`). + guard let instance = Self.onTheNewCore(instance, isTheSdks: isTheSdks, call: name), + let core = instance.core as? CoreV2 else { + return .failure(.notInitialized) + } + let request: ApiRequest + do { + request = try make() + } catch { + let refusal = error as? Rees46.SdkError ?? .invalidArgument(String(describing: error)) + instance.logger.warning(LogCode.invalidArgument, "\(name): \(refusal.message)", ["call": name]) + return .failure(refusal) + } + var coreRequest = request.coreRequest + if request.host == .app { + coreRequest.host = instance.config.appDomain + } + let response = await core.response(to: coreRequest) + return Self.value(of: response, for: request, call: name, logger: instance.logger) + } + + /// `instance` when the method `name` may run on it: the SDK's own, on the new core. Otherwise `nil` + /// — the method ends as `notInitialized` — and the log says why: `not_implemented` for a conformer of + /// `owner` other than the SDK's own (`isTheSdks` `false`), `core_flag_mismatch` on the old core; + /// nothing for the SDK's instance that is gone. + static func onTheNewCore( + _ instance: SimplePersonalizationSDK?, + isTheSdks: Bool, + call name: String, + owner: String = "PersonalizationSDK" + ) -> SimplePersonalizationSDK? { + guard let instance = instance else { + if !isTheSdks { + SdkLogger.process.error(LogCode.notImplemented, "\(name) is not implemented by this \(owner)", ["call": name]) + } + return nil + } + guard instance.usesCoreV2 else { + instance.logger.warning( + LogCode.coreFlagMismatch, + "\(name) runs on the new core only: start the shop with Rees46.initializeBridge", + ["call": name] + ) + return nil + } + return instance + } + + /// `result` for a method's `completion`: called exactly once, on the main thread. + func call( + _ name: String, + completion: @escaping (Result) -> Void, + _ make: @escaping () throws -> ApiRequest + ) { + _Concurrency.Task { + let result = await self.result(name, make) + DispatchQueue.main.async { completion(result) } + } + } + + /// `result` for a method's `async` form: the value, or the `Rees46.SdkError` thrown. Cancelling the + /// caller's task ends the call as `cancelled`, also while it waits for the instance. + func value(_ name: String, _ make: () throws -> ApiRequest) async throws -> Value { + try await result(name, make).get() + } + + /// The method's value of what the core got. Any `2xx` is a success, but one whose body says + /// `{"status": "error"}`: that is `decoding`, as is a body that does not read as the method's model. + /// The log has the call, the method and the path, never the body: an error's text may repeat what + /// the request carried. + static func value( + of response: NetworkClient.Response, + for request: ApiRequest, + call name: String, + logger: SdkLogger + ) -> Result { + let json: Any + switch response.result { + case .failure(let error): + return .failure(error) + case .success(let value): + json = value + } + let line = SdkLogger.requestLine(request.method.rawValue, request.path) + let context = ["call": name, "method": request.method.rawValue, "path": request.path] + if let object = json as? [String: Any], object["status"] as? String == "error" { + logger.warning(LogCode.decodingFailed, "the answer to \(line) is an error with a 2xx status", context) + return .failure(.decoding) + } + do { + return .success(try request.decode(response.body)) + } catch { + logger.warning(LogCode.decodingFailed, "the answer to \(line) does not read as \(name)'s result", context) + return .failure(.decoding) + } + } +} diff --git a/REES46/Classes/Loyalty/LoyaltyAPI.swift b/REES46/Classes/Loyalty/LoyaltyAPI.swift new file mode 100644 index 00000000..0f4c4a37 --- /dev/null +++ b/REES46/Classes/Loyalty/LoyaltyAPI.swift @@ -0,0 +1,182 @@ +// +// LoyaltyAPI.swift +// REES46 +// +// The `loyalty` namespace of the contract (`sdk/contract/loyalty.md`). +// + +import Foundation + +/** + The loyalty program from the customer's side: join it, read one's status, get the promotions that fit. + The rest of the program — bonuses, certificates, checkout, promo codes — is the shop's server's: it + needs the shop's secret, which the SDK never sends. + + Without the secret the server takes `join` and `getStatus` only from a shop with "loyalty methods from + the front" turned on in its account (off by default); otherwise they end as `http(403)`. Whether they + stay so is open (questions 17 and 18 of `sdk/questions.md`). `getPromotions` needs no such setting. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + + Every `completion` is called once, on the main thread, with the value or the error: `invalidArgument` + for an argument the method refuses, nothing sent; `notInitialized` on the old core or after + `release()`, `shopBlocked`, `network`, `timeout`, `http(code:serverCode:)` — `404` when the shop has + no loyalty program, `402` when the service is off or not paid, `403` when the method needs the secret, + `400` for data the server refuses —, `decoding` for an answer that is not the method's, `cancelled` + for a call `release()` ended. Nothing is repeated: the app decides. The `async` forms throw the + `Rees46.SdkError`; cancelling the task ends the call as `cancelled`. + */ +@_spi(Bridge) +public protocol LoyaltyAPI { + + /** + Joins the customer to the program (`POST loyalty/members/join`) by their `phone`, which becomes + the member's identifier for `getStatus`. A phone already registered is a success with the same + identifier; the server then updates the name, gender and birthday it has. The server finds or makes + the customer by the phone, not by the device. + + `invalidArgument` for an empty `phone` or a `birthday` that is not an existing date `YYYY-MM-DD`: + a birthday the server cannot read erases the one it has. An empty name is not sent. + */ + func join( + phone: String, + firstName: String?, + lastName: String?, + gender: Gender?, + birthday: String?, + completion: @escaping (Result) -> Void + ) + + /// `join(phone:firstName:lastName:gender:birthday:completion:)` for `async` code. + func join(phone: String, firstName: String?, lastName: String?, gender: Gender?, birthday: String?) async throws -> LoyaltyMember + + /** + Whether the customer with `phone` is a member, and on which level (`GET loyalty/members/status`). + Not a member is a success with `isMember` false; the base level is a member without a `level`. The + phone goes as it is: the server keeps its digits. `invalidArgument` for an empty `phone`. + */ + func getStatus(phone: String, completion: @escaping (Result) -> Void) + + /// `getStatus(phone:completion:)` for `async` code. + func getStatus(phone: String) async throws -> LoyaltyStatus + + /** + The active promotions that fit the customer of this device and their cart + (`GET loyalty/promos/for-client`); none is an empty list. + + `locationId` is the shop's location — a city, a store —, `promoCodes` the customer's codes, + `chargeBonuses` whether bonuses are charged (the server takes `false` without it), `currentTime` + the local time at the store as `HH:MM`, for the promotions of some hours (the server takes its + own time in the shop's time zone without it). `invalidArgument` for a `currentTime` that is not + `HH:MM` or an empty code in `promoCodes`. An empty `locationId` or list is not sent. + */ + func getPromotions( + locationId: String?, + promoCodes: [String]?, + chargeBonuses: Bool?, + currentTime: String?, + completion: @escaping (Result<[LoyaltyPromotion], Rees46.SdkError>) -> Void + ) + + /// `getPromotions(locationId:promoCodes:chargeBonuses:currentTime:completion:)` for `async` code. + func getPromotions(locationId: String?, promoCodes: [String]?, chargeBonuses: Bool?, currentTime: String?) async throws -> [LoyaltyPromotion] +} + +/// The default arguments of `LoyaltyAPI`: a requirement of a protocol cannot have them. +@_spi(Bridge) +extension LoyaltyAPI { + + public func join( + phone: String, + firstName: String? = nil, + lastName: String? = nil, + gender: Gender? = nil, + birthday: String? = nil, + completion: @escaping (Result) -> Void + ) { + join(phone: phone, firstName: firstName, lastName: lastName, gender: gender, birthday: birthday, completion: completion) + } + + public func join( + phone: String, + firstName: String? = nil, + lastName: String? = nil, + gender: Gender? = nil, + birthday: String? = nil + ) async throws -> LoyaltyMember { + try await join(phone: phone, firstName: firstName, lastName: lastName, gender: gender, birthday: birthday) + } + + public func getPromotions( + locationId: String? = nil, + promoCodes: [String]? = nil, + chargeBonuses: Bool? = nil, + currentTime: String? = nil, + completion: @escaping (Result<[LoyaltyPromotion], Rees46.SdkError>) -> Void + ) { + getPromotions(locationId: locationId, promoCodes: promoCodes, chargeBonuses: chargeBonuses, currentTime: currentTime, completion: completion) + } + + public func getPromotions( + locationId: String? = nil, + promoCodes: [String]? = nil, + chargeBonuses: Bool? = nil, + currentTime: String? = nil + ) async throws -> [LoyaltyPromotion] { + try await getPromotions(locationId: locationId, promoCodes: promoCodes, chargeBonuses: chargeBonuses, currentTime: currentTime) + } +} + +/// A member of the loyalty program. +@_spi(Bridge) +public struct LoyaltyMember { + /// The member's identifier: the phone's digits, `7XXXXXXXXXX`. + public let identifier: String +} + +/// Whether the customer is a member, and their level. +@_spi(Bridge) +public struct LoyaltyStatus { + public let isMember: Bool + /// `nil` on the base level and for one who is not a member. `code` is always set. + public let level: LoyaltyLevel? +} + +/// A promotion of the loyalty program; `id` is 64-bit, as the server's ids of promotions. +@_spi(Bridge) +public struct LoyaltyPromotion { + public let id: Int + public let name: String + public let description: String? + /// `YYYY-MM-DD`. + public let startDate: String? + /// `YYYY-MM-DD`. + public let finishDate: String? + /// Where the promotion holds; `nil` is everywhere. + public let stream: String? + /// The text of the badge. + public let badgeLabel: String? + /// The colour of the badge, `#RRGGBB`. + public let badgeColor: String? + /// `nil` for a type the SDK does not know. + public let rewardType: LoyaltyRewardType? +} + +/// What a promotion gives. +@_spi(Bridge) +public enum LoyaltyRewardType: String { + case discount = "discount" + case bonusesEarn = "bonuses_earn" + case bonusesUsage = "bonuses_usage" +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The loyalty program from the customer's side (`LoyaltyAPI`): on the new core only. + public var loyalty: LoyaltyAPI { + LoyaltyAPIImpl(requests: NamespaceRequests(self)) + } +} diff --git a/REES46/Classes/Loyalty/LoyaltyAPIImpl.swift b/REES46/Classes/Loyalty/LoyaltyAPIImpl.swift new file mode 100644 index 00000000..83b39208 --- /dev/null +++ b/REES46/Classes/Loyalty/LoyaltyAPIImpl.swift @@ -0,0 +1,219 @@ +// +// LoyaltyAPIImpl.swift +// REES46 +// + +import Foundation + +struct LoyaltyAPIImpl: LoyaltyAPI { + + let requests: NamespaceRequests + + func join( + phone: String, + firstName: String?, + lastName: String?, + gender: Gender?, + birthday: String?, + completion: @escaping (Result) -> Void + ) { + requests.call("loyalty.join", completion: completion) { + try Self.joinRequest(phone: phone, firstName: firstName, lastName: lastName, gender: gender, birthday: birthday) + } + } + + func join(phone: String, firstName: String?, lastName: String?, gender: Gender?, birthday: String?) async throws -> LoyaltyMember { + try await requests.value("loyalty.join") { + try Self.joinRequest(phone: phone, firstName: firstName, lastName: lastName, gender: gender, birthday: birthday) + } + } + + func getStatus(phone: String, completion: @escaping (Result) -> Void) { + requests.call("loyalty.getStatus", completion: completion) { try Self.statusRequest(phone: phone) } + } + + func getStatus(phone: String) async throws -> LoyaltyStatus { + try await requests.value("loyalty.getStatus") { try Self.statusRequest(phone: phone) } + } + + func getPromotions( + locationId: String?, + promoCodes: [String]?, + chargeBonuses: Bool?, + currentTime: String?, + completion: @escaping (Result<[LoyaltyPromotion], Rees46.SdkError>) -> Void + ) { + requests.call("loyalty.getPromotions", completion: completion) { + try Self.promotionsRequest(locationId: locationId, promoCodes: promoCodes, chargeBonuses: chargeBonuses, currentTime: currentTime) + } + } + + func getPromotions(locationId: String?, promoCodes: [String]?, chargeBonuses: Bool?, currentTime: String?) async throws -> [LoyaltyPromotion] { + try await requests.value("loyalty.getPromotions") { + try Self.promotionsRequest(locationId: locationId, promoCodes: promoCodes, chargeBonuses: chargeBonuses, currentTime: currentTime) + } + } + + // MARK: - Requests + + /// `POST loyalty/members/join` with the member's fields; the core adds the common ones, the device id + /// among them, which this address does not read. No email: the server reads it only with the secret. + static func joinRequest( + phone: String, + firstName: String?, + lastName: String?, + gender: Gender?, + birthday: String? + ) throws -> ApiRequest { + guard !ApiArguments.isBlank(phone) else { + throw Rees46.SdkError.invalidArgument("the phone must not be empty") + } + // A birthday the server cannot read erases the one it has: only an existing date goes. + if let birthday = birthday, !ApiArguments.isCalendarDate(birthday) { + throw Rees46.SdkError.invalidArgument("the birthday must be an existing date as YYYY-MM-DD") + } + var body: [String: Any] = ["phone": phone] + body["first_name"] = ApiArguments.given(firstName) + body["last_name"] = ApiArguments.given(lastName) + body["gender"] = gender.map { $0 == .male ? "m" : "f" } + body["birthday"] = birthday + return ApiRequest(method: .post, path: "loyalty/members/join", body: body) { data in + try JSONDecoder().decode(LoyaltyMemberAnswer.self, from: data).member + } + } + + /// `GET loyalty/members/status` for the member `phone`, sent as it is: the server keeps its digits. + static func statusRequest(phone: String) throws -> ApiRequest { + guard !ApiArguments.isBlank(phone) else { + throw Rees46.SdkError.invalidArgument("the phone must not be empty") + } + return .get("loyalty/members/status", query: ["identifier": phone], answer: LoyaltyStatusAnswer.self) { $0.status } + } + + /// `GET loyalty/promos/for-client` for the customer of the device id. The codes go as a list of + /// Rails — `promo_codes[]=A&promo_codes[]=B` —: the server drops a string of them. No contacts: by a + /// contact the server would give another customer's promotions. An answer without a body is none. + static func promotionsRequest( + locationId: String?, + promoCodes: [String]?, + chargeBonuses: Bool?, + currentTime: String? + ) throws -> ApiRequest<[LoyaltyPromotion]> { + if let time = currentTime, !isTime(time) { + throw Rees46.SdkError.invalidArgument("the current time must be HH:MM") + } + if promoCodes?.contains(where: ApiArguments.isBlank) == true { + throw Rees46.SdkError.invalidArgument("a promo code must not be empty") + } + var query: [String: String] = [:] + query["location_id"] = ApiArguments.given(locationId) + query["charge_bonuses"] = chargeBonuses.map { $0 ? "true" : "false" } + query["current_time"] = currentTime + var request = ApiRequest<[LoyaltyPromotion]>.get( + "loyalty/promos/for-client", query: query, answer: LoyaltyPromotionsAnswer.self, whenEmpty: [] + ) { $0.promotions } + if let codes = promoCodes, !codes.isEmpty { + request.queryLists = ["promo_codes[]": codes] + } + return request + } + + // MARK: - Arguments + + /// `HH:MM` of a day: `00:00` to `23:59`. + static func isTime(_ text: String) -> Bool { + text.range(of: #"^([01][0-9]|2[0-3]):[0-5][0-9]$"#, options: .regularExpression) != nil + } +} + +// MARK: - The answers + +/// `{"status": "success", "payload": {"message": …, "identifier": "7…"}}`, for a new member and for one +/// already registered. Without an identifier it is not a member (`decoding`). +struct LoyaltyMemberAnswer: Decodable { + + let member: LoyaltyMember + + init(from decoder: Decoder) throws { + let root = try decoder.container(keyedBy: AnswerKey.self) + let payload = try? root.nestedContainer(keyedBy: AnswerKey.self, forKey: "payload") + guard let identifier = payload?.lenientString("identifier") else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "no payload.identifier")) + } + member = LoyaltyMember(identifier: identifier) + } +} + +/// `{"status": "success", "payload": {"member": true, "level": {"code", "name", "expiration_date"}}}`. +/// A level whose `code` is `null` — the base level, or no member — is none. Without `payload.member` it +/// is not a status (`decoding`). +struct LoyaltyStatusAnswer: Decodable { + + let status: LoyaltyStatus + + init(from decoder: Decoder) throws { + let root = try decoder.container(keyedBy: AnswerKey.self) + let payload = try? root.nestedContainer(keyedBy: AnswerKey.self, forKey: "payload") + guard let isMember = payload?.lenientBool("member") else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "no payload.member")) + } + let level = try? payload?.nestedContainer(keyedBy: AnswerKey.self, forKey: "level") + status = LoyaltyStatus( + isMember: isMember, + level: level.flatMap { level in + level.lenientString("code").map { + LoyaltyLevel(code: $0, name: level.lenientString("name"), expirationDate: level.lenientString("expiration_date")) + } + } + ) + } +} + +/// `{"status": "success", "payload": {"promotions": [...]}}`. A promotion without an id is left out, one +/// of an unknown reward type has none. Without the list it is not an answer of promotions (`decoding`). +struct LoyaltyPromotionsAnswer: Decodable { + + let promotions: [LoyaltyPromotion] + + init(from decoder: Decoder) throws { + let root = try decoder.container(keyedBy: AnswerKey.self) + let payload = try? root.nestedContainer(keyedBy: AnswerKey.self, forKey: "payload") + guard let list = payload?.lenientList(PromotionAnswer.self, "promotions") else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "no payload.promotions")) + } + promotions = list.map(\.promotion) + } + + private struct PromotionAnswer: Decodable { + let promotion: LoyaltyPromotion + + init(from decoder: Decoder) throws { + let item = try decoder.container(keyedBy: AnswerKey.self) + guard let id = item.lenientInt("id") else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "no id")) + } + promotion = LoyaltyPromotion( + id: id, + name: item.lenientString("name") ?? "", + description: item.lenientString("description"), + startDate: item.lenientString("start_date"), + finishDate: item.lenientString("finish_date"), + stream: item.lenientString("stream"), + badgeLabel: item.lenientString("badge_label"), + badgeColor: item.lenientString("badge_color"), + rewardType: item.lenientEnum(LoyaltyRewardType.self, "reward_type") + ) + } + } +} + +extension LoyaltyLevel { + + /// A level of `loyalty.getStatus`, whose `code` is always set. + init(code: String, name: String?, expirationDate: String?) { + self.init(json: [:]) + self.code = code + self.name = name + self.expirationDate = expirationDate + } +} diff --git a/REES46/Classes/Model/CartItem.swift b/REES46/Classes/Model/CartItem.swift index 33aab709..b0b6fc7b 100644 --- a/REES46/Classes/Model/CartItem.swift +++ b/REES46/Classes/Model/CartItem.swift @@ -1,8 +1,11 @@ import Foundation +/// A product in the cart: what the cart events of `tracking` send, and a line of the server's cart +/// (`cart.get`, bridges only). public struct CartItem { var productId: String - var quantity: Int = 1 + /// How many of the product. + @_spi(Bridge) public internal(set) var quantity: Int = 1 var price: Double? public init(productId: String, quantity: Int = 1, price: Double? = nil) { diff --git a/REES46/Classes/Model/ProbabilityToPurchaseResponse.swift b/REES46/Classes/Model/ProbabilityToPurchaseResponse.swift index 53707067..e593a13d 100644 --- a/REES46/Classes/Model/ProbabilityToPurchaseResponse.swift +++ b/REES46/Classes/Model/ProbabilityToPurchaseResponse.swift @@ -1,26 +1,15 @@ import Foundation +/// The forecast of `getProbabilityToPurchase(params:completion:)`. public struct ProbabilityToPurchaseResponse { + /// From 0 to 1. public let probability: Double + /// The customer the server found by the device id; empty when it found none. public let clientId: String - init?(json: [String: Any]) { - guard let probVal = json["probability"] else { return nil } - let probability: Double - if let d = probVal as? Double { - probability = d - } else if let n = probVal as? NSNumber { - probability = n.doubleValue - } else { - return nil - } - if let cid = json["client_id"] as? String { - self.clientId = cid - } else if let cidNum = json["client_id"] as? NSNumber { - self.clientId = cidNum.stringValue - } else { - return nil - } - self.probability = probability + /// The old model of the forecast `predict.getProbabilityToPurchase` reads. + init(_ forecast: PurchaseProbability) { + probability = forecast.probability + clientId = forecast.clientId ?? "" } } diff --git a/REES46/Classes/Model/PurchasePredictParams.swift b/REES46/Classes/Model/PurchasePredictParams.swift index 552c61d2..80aa5e1a 100644 --- a/REES46/Classes/Model/PurchasePredictParams.swift +++ b/REES46/Classes/Model/PurchasePredictParams.swift @@ -1,6 +1,7 @@ import Foundation -/// Optional query parameters for `getProbabilityToPurchase`. `shop_id`, `did`, session and `stream` are set by the SDK. +/// The contacts `getProbabilityToPurchase` once sent. They are no longer sent: the server finds the customer by +/// the device id, which wins over any contact. `shop_id`, `did`, session and `stream` are set by the SDK. public struct PurchasePredictParams { public var email: String? public var phone: String? diff --git a/REES46/Classes/Model/Stories.swift b/REES46/Classes/Model/Stories.swift index bd6254d8..f75ac6f9 100644 --- a/REES46/Classes/Model/Stories.swift +++ b/REES46/Classes/Model/Stories.swift @@ -6,7 +6,7 @@ public class StoryContent { var id: String let ids: Int let settings: StoriesSettings - let stories: [Story] + let stories: [LegacyStory] public init(json: [String: Any], shopId: String = "") { self.id = json["id"] as? String ?? "-1" @@ -14,7 +14,7 @@ public class StoryContent { let _settings = json["settings"] as? [String: Any] ?? [:] self.settings = StoriesSettings(json: _settings) let _stories = json["stories"] as? [[String: Any]] ?? [] - self.stories = _stories.map({ Story(json: $0, shopId: shopId) }) + self.stories = _stories.map({ LegacyStory(json: $0, shopId: shopId) }) if let ids = json["id"] as? Int { self.id = String(ids) @@ -47,8 +47,9 @@ public class StoriesSettings { } -// MARK: - Story -class Story { +// MARK: - LegacyStory +/// A story of the old stories view (`StoriesView`). The name `Story` is the model of `stories.get`. +class LegacyStory { var id: String let ids: Int let avatar: String diff --git a/REES46/Classes/Notifications/API/NotificationsAPI.swift b/REES46/Classes/Notifications/API/NotificationsAPI.swift new file mode 100644 index 00000000..c8bdff2d --- /dev/null +++ b/REES46/Classes/Notifications/API/NotificationsAPI.swift @@ -0,0 +1,141 @@ +// +// NotificationsAPI.swift +// REES46 +// +// The `notifications` namespace of the contract (`sdk/contract/notifications.md`): the push token and +// the events of pushes, over the push machinery of the new core (`sdk/core/push.md`). +// + +import Foundation + +/** + Mobile pushes of one shop: the events of a push the app or the bridge parses itself, the device's push + token, and the shop's push callbacks. A push the SDK should parse goes to `Rees46.handlePush`, which + finds its shop and sends the event for it. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized`, sends nothing and sets nothing; `getPushToken` gives `nil`. + */ +@_spi(Bridge) +public protocol NotificationsAPI { + + /** + The push came to the app (`POST track/delivered`), for an app that parses its pushes itself. + `code` is the push's `id`, `type` its `type` — `bulk`, `chain`, `transactional` or `digest` —, both + required and not blank. + + The event goes through the shop's queue, as `tracking` events go, with the shop and the device id; + an event of one message goes once per process — a repeat, or one `Rees46.handlePush` sent before, + sends nothing and succeeds. No push callback is called: the app knows of the event. + + `completion` is called once, on the main thread: success once the queue took the event — it does + not wait for the network, and no network error comes —, or `invalidArgument` for a blank `code` or + `type`, `notInitialized` on the old core or after `release()`, `shopBlocked`. + */ + func trackDelivered(code: String, type: String, completion: @escaping (Result) -> Void) + + /// The notification was shown to the user (`POST track/opened`), as `trackDelivered(code:type:completion:)`. + func trackOpened(code: String, type: String, completion: @escaping (Result) -> Void) + + /// The user tapped the notification (`POST track/clicked`), as `trackDelivered(code:type:completion:)`. + /// The push also becomes the source of the shop's `/push` events for 48 hours, as + /// `tracking.setSource` would make it, when its `type` is a `TrackingSourceType`. + func trackClicked(code: String, type: String, completion: @escaping (Result) -> Void) + + /// The notification was dismissed without a tap (`POST track/closed`), as + /// `trackDelivered(code:type:completion:)`. + func trackClosed(code: String, type: String, completion: @escaping (Result) -> Void) + + /// `trackDelivered(code:type:completion:)` for `async` code: throws the `Rees46.SdkError`; a task + /// cancelled before the call sends nothing and throws `cancelled`. + func trackDelivered(code: String, type: String) async throws + + /// `trackOpened(code:type:completion:)` for `async` code, as `trackDelivered(code:type:)`. + func trackOpened(code: String, type: String) async throws + + /// `trackClicked(code:type:completion:)` for `async` code, as `trackDelivered(code:type:)`. + func trackClicked(code: String, type: String) async throws + + /// `trackClosed(code:type:completion:)` for `async` code, as `trackDelivered(code:type:)`. + func trackClosed(code: String, type: String) async throws + + /** + The push token the SDK keeps, from its storage, without the network: the device's token of + `provider`, or — `nil` — the one of the provider whose token this shop sent last, and while it sent + none, the last token the SDK got from APNs or FCM or was given. `nil` when there is none: on iOS + `hms` never has one. The token is the device's: every shop of the app sends the same one. + */ + func getPushToken(provider: Rees46.PushProvider?) -> Rees46.PushToken? + + /** + The push token the app or the bridge got itself (`POST mobile_push_tokens`): `apns` goes as + `platform=ios`, `fcm` as `platform=ios_firebase`. It becomes the device's token and goes to this + shop by the rules of the token the SDK gets itself (`sdk/core/push.md`): a new token at once, the + same one at most once a week, never without a device id — until `/init` brings one it waits. + + `completion` is called once, on the main thread: success once the server took the token — also + when it went within the week, and nothing goes —, or `invalidArgument` for an empty token or `hms`, + which iOS does not have, `notInitialized` on the old core or after `release()`, `shopBlocked`, + `network`, `timeout`, `http(code:serverCode:)` — `400` for a token the server refuses, `403` or `404` + with an empty body for a shop it does not serve —, `decoding` for a `2xx` whose body says + `{"status": "error"}`. + */ + func setPushToken(_ token: String, provider: Rees46.PushProvider, completion: @escaping (Result) -> Void) + + /// `setPushToken(_:provider:completion:)` for `async` code: throws the `Rees46.SdkError`. Cancelling + /// the task ends the wait as `cancelled`; the SDK keeps the token and sends it as it would. + func setPushToken(_ token: String, provider: Rees46.PushProvider) async throws + + /** + The shop's own push callbacks: they win over `Rees46.setPushCallbacks`, one by one, for the pushes + of this shop the SDK sees — its `NotificationService` and `Rees46.handlePush` — and the tokens it + gets; on the main thread. A new call replaces them; `PushCallbacks()` without fields removes them. + The `track…` methods call none of them. + */ + func setCallbacks(_ callbacks: Rees46.PushCallbacks) +} + +@_spi(Bridge) +extension NotificationsAPI { + + /// `trackDelivered(code:type:completion:)` without a completion. + public func trackDelivered(code: String, type: String) { + trackDelivered(code: code, type: type, completion: { _ in }) + } + + /// `trackOpened(code:type:completion:)` without a completion. + public func trackOpened(code: String, type: String) { + trackOpened(code: code, type: type, completion: { _ in }) + } + + /// `trackClicked(code:type:completion:)` without a completion. + public func trackClicked(code: String, type: String) { + trackClicked(code: code, type: type, completion: { _ in }) + } + + /// `trackClosed(code:type:completion:)` without a completion. + public func trackClosed(code: String, type: String) { + trackClosed(code: code, type: type, completion: { _ in }) + } + + /// `getPushToken(provider:)` of the last token the SDK got or was given. + public func getPushToken() -> Rees46.PushToken? { + getPushToken(provider: nil) + } + + /// `setPushToken(_:provider:completion:)` without a completion. + public func setPushToken(_ token: String, provider: Rees46.PushProvider) { + setPushToken(token, provider: provider, completion: { _ in }) + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The shop's push token, events of pushes and push callbacks (`NotificationsAPI`): on the new core + /// only. + public var notifications: NotificationsAPI { + NotificationsAPIImpl(self) + } +} diff --git a/REES46/Classes/Notifications/API/NotificationsAPIImpl.swift b/REES46/Classes/Notifications/API/NotificationsAPIImpl.swift new file mode 100644 index 00000000..eb856644 --- /dev/null +++ b/REES46/Classes/Notifications/API/NotificationsAPIImpl.swift @@ -0,0 +1,243 @@ +// +// NotificationsAPIImpl.swift +// REES46 +// + +import Foundation + +// `_Concurrency.Task`: the module has a `Task` class of its own (the stories image loader). + +/// The `notifications` namespace of one instance, over its push machinery: the queue of the new core +/// for the events, the device's token and its week for `setPushToken`, the instance's callbacks. +/// +/// As the other namespaces (`NamespaceRequests`): on an instance of the old core every method ends as +/// `notInitialized`, sends nothing and logs `core_flag_mismatch`; on a conformer of `PersonalizationSDK` +/// other than the SDK's own it ends the same way and logs `not_implemented`. +struct NotificationsAPIImpl: NotificationsAPI { + + private weak var instance: SimplePersonalizationSDK? + /// Whether it was made for the SDK's own instance: once that is gone, a call is `notInitialized`. + private let isTheSdks: Bool + + init(_ sdk: PersonalizationSDK) { + instance = sdk as? SimplePersonalizationSDK + isTheSdks = instance != nil + } + + // MARK: - Events + + func trackDelivered(code: String, type: String, completion: @escaping (Result) -> Void) { + track(.delivered, code: code, type: type, completion: completion) + } + + func trackOpened(code: String, type: String, completion: @escaping (Result) -> Void) { + track(.opened, code: code, type: type, completion: completion) + } + + func trackClicked(code: String, type: String, completion: @escaping (Result) -> Void) { + track(.clicked, code: code, type: type, completion: completion) + } + + func trackClosed(code: String, type: String, completion: @escaping (Result) -> Void) { + track(.closed, code: code, type: type, completion: completion) + } + + func trackDelivered(code: String, type: String) async throws { + try await Self.awaiting { trackDelivered(code: code, type: type, completion: $0) } + } + + func trackOpened(code: String, type: String) async throws { + try await Self.awaiting { trackOpened(code: code, type: type, completion: $0) } + } + + func trackClicked(code: String, type: String) async throws { + try await Self.awaiting { trackClicked(code: code, type: type, completion: $0) } + } + + func trackClosed(code: String, type: String) async throws { + try await Self.awaiting { trackClosed(code: code, type: type, completion: $0) } + } + + /// `event` of the message `code` through the instance's queue, once per message in the process. + private func track(_ event: Rees46.PushEvent, code: String, type: String, completion: @escaping (Result) -> Void) { + let name = Self.callName(of: event) + let finish = Self.onMain(completion) + guard let instance = onTheNewCore(name) else { + finish(.failure(.notInitialized)) + return + } + if let refusal = Self.refusal(code: code, type: type) { + instance.logger.warning(LogCode.invalidArgument, "\(name): \(refusal.message)", ["call": name]) + finish(.failure(refusal)) + return + } + instance.queuePushEvent(event, type: type, code: code) { error in + finish(error.map { .failure($0) } ?? .success(())) + } + } + + /// The name of `event`'s method, as the log calls it: `notifications.trackDelivered`. + static func callName(of event: Rees46.PushEvent) -> String { + "notifications.track" + event.rawValue.prefix(1).uppercased() + event.rawValue.dropFirst() + } + + /// Why the event of `code` and `type` is not sent: either is blank (`sdk/contract/notifications.md`). + static func refusal(code: String, type: String) -> Rees46.SdkError? { + if ApiArguments.isBlank(code) { + return .invalidArgument("the code of the push must not be empty") + } + if ApiArguments.isBlank(type) { + return .invalidArgument("the type of the push must not be empty") + } + return nil + } + + // MARK: - The token + + func getPushToken(provider: Rees46.PushProvider?) -> Rees46.PushToken? { + guard let instance = onTheNewCore("notifications.getPushToken"), !instance.isReleased else { return nil } + if let provider = provider { + return Self.token(of: provider, on: instance) + } + // The provider whose token this shop sent last; without one, the device's last token. + let lastSent = Rees46.PushProvider.allCases + .compactMap { provider in + provider.iosPlatform.flatMap(instance.storage.pushTokenSent(platform:)).map { (provider, $0.at) } + } + .max { $0.1 < $1.1 } + return lastSent.flatMap { Self.token(of: $0.0, on: instance) } ?? instance.deviceStore.deviceToken + } + + /// The device's token of `provider`, or the one the shop of `instance` sent. + private static func token(of provider: Rees46.PushProvider, on instance: SimplePersonalizationSDK) -> Rees46.PushToken? { + if let token = instance.deviceStore.deviceToken(provider) { + return token + } + return provider.iosPlatform + .flatMap(instance.storage.pushTokenSent(platform:)) + .map { Rees46.PushToken(token: $0.token, provider: provider) } + } + + func setPushToken(_ token: String, provider: Rees46.PushProvider, completion: @escaping (Result) -> Void) { + let name = "notifications.setPushToken" + guard let instance = onTheNewCore(name) else { + Self.onMain(completion)(.failure(.notInitialized)) + return + } + if let refusal = Self.refusal(token: token, provider: provider) { + instance.logger.warning(LogCode.invalidArgument, "\(name): \(refusal.message)", ["call": name]) + Self.onMain(completion)(.failure(refusal)) + return + } + // The bridges' way of a token they got: its whole error, on the main thread. + instance.setPushToken(Rees46.PushToken(token: token, provider: provider), completion: completion) + } + + func setPushToken(_ token: String, provider: Rees46.PushProvider) async throws { + try await Self.awaiting(endsOnCancel: true) { setPushToken(token, provider: provider, completion: $0) } + } + + /// Why `token` of `provider` is not taken: it is empty, or the provider is not one of iOS. + static func refusal(token: String, provider: Rees46.PushProvider) -> Rees46.SdkError? { + if token.isEmpty { + return .invalidArgument("the push token must not be empty") + } + if provider.iosPlatform == nil { + return .invalidArgument("\(provider.rawValue) is not a provider of iOS") + } + return nil + } + + // MARK: - Callbacks + + func setCallbacks(_ callbacks: Rees46.PushCallbacks) { + onTheNewCore("notifications.setCallbacks")?.setPushCallbacks(callbacks) + } + + // MARK: - The instance + + /// The instance, when the method `name` may run on it: the SDK's own, on the new core. + private func onTheNewCore(_ name: String) -> SimplePersonalizationSDK? { + NamespaceRequests.onTheNewCore(instance, isTheSdks: isTheSdks, call: name) + } + + // MARK: - completion and async + + /// `completion`, called once, on the main thread. + static func onMain(_ completion: @escaping (Result) -> Void) -> (Result) -> Void { + let once = Once() + return { result in + guard once.take() else { return } + DispatchQueue.main.async { completion(result) } + } + } + + /// The `async` form of a method with `completion` (`start`): returns or throws its result. A task + /// cancelled before the call throws `cancelled` and does not start it. `endsOnCancel`: cancelling the + /// task while the call goes on ends the wait as `cancelled` too — for a call that may wait long, as + /// a token waits for the device id; the call itself goes on. + static func awaiting( + endsOnCancel: Bool = false, + _ start: (@escaping (Result) -> Void) -> Void + ) async throws { + guard !_Concurrency.Task.isCancelled else { + throw Rees46.SdkError.cancelled + } + let outcome = Outcome() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + outcome.wait(continuation) + start { outcome.finish($0) } + } + } onCancel: { + if endsOnCancel { + outcome.finish(.failure(.cancelled)) + } + } + } + + /// The first result of a call and who waits for it: the waiting `async` call resumes once, with + /// the first of the result and the cancellation. + private final class Outcome { + private let lock = NSLock() + private var result: Result? + private var continuation: CheckedContinuation? + + func wait(_ continuation: CheckedContinuation) { + lock.lock() + guard let result = result else { + self.continuation = continuation + lock.unlock() + return + } + lock.unlock() + continuation.resume(with: result) + } + + func finish(_ result: Result) { + lock.lock() + guard self.result == nil else { + lock.unlock() + return + } + self.result = result + let waiting = continuation + continuation = nil + lock.unlock() + waiting?.resume(with: result) + } + } + + /// `true` the first time only. + private final class Once { + private let lock = NSLock() + private var taken = false + + func take() -> Bool { + lock.lock(); defer { lock.unlock() } + guard !taken else { return false } + taken = true + return true + } + } +} diff --git a/REES46/Classes/Predict/PredictAPI.swift b/REES46/Classes/Predict/PredictAPI.swift new file mode 100644 index 00000000..0c5170ac --- /dev/null +++ b/REES46/Classes/Predict/PredictAPI.swift @@ -0,0 +1,60 @@ +// +// PredictAPI.swift +// REES46 +// +// The `predict` namespace of the contract (`sdk/contract/predict.md`). +// + +import Foundation + +/** + Forecasts of the customer's behaviour. One for now: how likely the customer of this device is to buy, + from the products they viewed, their cart and favorites of the last days. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + */ +@_spi(Bridge) +public protocol PredictAPI { + + /** + The probability that the customer of this device buys (`GET api/v3/cdp/users/probability-to-purchase` + on `Rees46Config.appDomain`). The customer is the device id: the method takes no contacts, and it + waits for the instance to have one. A customer the server does not know, or one without events, is a + success with probability 0. + + `completion` is called once, on the main thread, with the forecast or the error: `notInitialized` + on the old core or after `release()`, `shopBlocked`, `network`, `timeout`, `http(code:serverCode:)` + — `400` without a device id, `402` for a shop that does not pay or has no `cdp` service, `403` for an + inactive or restricted one, `404` for an unknown one —, `decoding` for an answer without a numeric + `probability`, `cancelled` for a call `release()` ended. Nothing is repeated: the app decides. + + The SDKs up to 3.39.0 asked `predict/probability-to-purchase` on the API host, which answers `503`: + the service is no longer deployed there (question 42 of `sdk/questions.md`). The root method + `getProbabilityToPurchase(params:completion:)` now asks the same path as this one, on either core. + */ + func getProbabilityToPurchase(completion: @escaping (Result) -> Void) + + /// `getProbabilityToPurchase(completion:)` for `async` code: throws the `Rees46.SdkError`; cancelling + /// the task ends the call as `cancelled`. + func getProbabilityToPurchase() async throws -> PurchaseProbability +} + +/// How likely the customer is to buy. +@_spi(Bridge) +public struct PurchaseProbability { + /// From 0 to 1, to two decimal places. + public let probability: Double + /// The customer the server found by the device id; `nil` when it found none. + public let clientId: String? +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// Forecasts of the customer's behaviour (`PredictAPI`): on the new core only. + public var predict: PredictAPI { + PredictAPIImpl(requests: NamespaceRequests(self)) + } +} diff --git a/REES46/Classes/Predict/PredictAPIImpl.swift b/REES46/Classes/Predict/PredictAPIImpl.swift new file mode 100644 index 00000000..2c42ccda --- /dev/null +++ b/REES46/Classes/Predict/PredictAPIImpl.swift @@ -0,0 +1,61 @@ +// +// PredictAPIImpl.swift +// REES46 +// + +import Foundation + +struct PredictAPIImpl: PredictAPI { + + let requests: NamespaceRequests + + func getProbabilityToPurchase(completion: @escaping (Result) -> Void) { + requests.call("predict.getProbabilityToPurchase", completion: completion) { Self.probabilityRequest } + } + + func getProbabilityToPurchase() async throws -> PurchaseProbability { + try await requests.value("predict.getProbabilityToPurchase") { Self.probabilityRequest } + } + + /// `GET api/v3/cdp/users/probability-to-purchase` on `appDomain`, with nothing but the common fields: + /// the server finds the customer by the device id, which wins over any contact (question 44 of + /// `sdk/questions.md`), so none is sent. The API host's `predict/probability-to-purchase` answers + /// `503`: its service is no longer deployed there (question 42). The general read timeout, not the 15 + /// seconds of the old method. + static var probabilityRequest: ApiRequest { + var request = ApiRequest.get(probabilityPath, answer: ProbabilityAnswer.self) { $0.value } + request.host = .app + return request + } + + /// The path of the forecast on the host of API v3. + static let probabilityPath = "api/v3/cdp/users/probability-to-purchase" +} + +/// `{"status": "success", "payload": {"probability": 0.42, "client_id": 12345}}`: a `client_id` that is +/// `null` or missing is no customer, a success. Without a numeric `payload.probability` it is not a +/// forecast (`decoding`). +struct ProbabilityAnswer: Decodable { + + let value: PurchaseProbability + + init(from decoder: Decoder) throws { + let root = try decoder.container(keyedBy: AnswerKey.self) + let payload = try? root.nestedContainer(keyedBy: AnswerKey.self, forKey: "payload") + guard let probability = payload?.lenientDouble("probability") else { + throw DecodingError.dataCorrupted(DecodingError.Context( + codingPath: decoder.codingPath, + debugDescription: "no numeric payload.probability" + )) + } + value = PurchaseProbability(probability: probability, clientId: payload?.lenientString("client_id")) + } + + /// The forecast in an answer the old methods got as JSON; `nil` when it is none. + static func forecast(in json: Any) -> PurchaseProbability? { + guard JSONSerialization.isValidJSONObject(json), let data = try? JSONSerialization.data(withJSONObject: json) else { + return nil + } + return (try? JSONDecoder().decode(ProbabilityAnswer.self, from: data))?.value + } +} diff --git a/REES46/Classes/Products/CatalogQuery.swift b/REES46/Classes/Products/CatalogQuery.swift new file mode 100644 index 00000000..e6c10a75 --- /dev/null +++ b/REES46/Classes/Products/CatalogQuery.swift @@ -0,0 +1,106 @@ +// +// CatalogQuery.swift +// REES46 +// +// The query of a catalog's request (`sdk/contract/products.md`, "ProductsListRequest"), built and +// checked before anything is sent: a refused argument throws `Rees46.SdkError.invalidArgument`. +// + +import Foundation + +/// The fields of one request's query: what is `nil` or empty is not sent. +struct CatalogQuery { + + private(set) var fields: [String: String] = [:] + + init(_ fields: [String: String] = [:]) { + self.fields = fields + } + + /// `value`, when there is one. + mutating func set(_ name: String, _ value: String?) { + guard let value = value else { return } + fields[name] = value + } + + /// A list as one value joined by `,` without spaces: the server splits on `,` and keeps the + /// spaces. An empty list is none. + mutating func set(_ name: String, list: [String]?) { + guard let list = list, !list.isEmpty else { return } + fields[name] = list.joined(separator: ",") + } + + /// A number without a needless fraction: `100`, not `100.0`. + mutating func set(_ name: String, number: Double?) { + set(name, number.map(Self.number)) + } + + mutating func set(_ name: String, int: Int?) { + set(name, int.map(String.init)) + } + + /// The free filters as the JSON text the API reads, keys sorted; none for an empty map. + mutating func set(_ name: String, filters: [String: [String]]?) throws { + guard let filters = filters, !filters.isEmpty else { return } + guard let data = SafeJSON.data(filters, options: [.sortedKeys, .withoutEscapingSlashes]), + let text = String(data: data, encoding: .utf8) + else { + throw Rees46.SdkError.invalidArgument("\(name) are not valid JSON") + } + fields[name] = text + } + + // MARK: - Values + + /// `value` without a needless fraction. + static func number(_ value: Double) -> String { + if value.rounded() == value, abs(value) < 1e15 { + return String(Int64(value)) + } + return String(value) + } + + /// `value` as one segment of a path: everything but the unreserved characters of a URL is + /// percent-encoded, `/` included. + static func pathSegment(_ value: String) -> String { + value.addingPercentEncoding(withAllowedCharacters: unreserved) ?? value + } + + private static let unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") + + // MARK: - Checks + + /// A required identifier: `invalidArgument` when it is empty or blank. + static func identifier(_ value: String, _ name: String) throws -> String { + guard !ApiArguments.isBlank(value) else { + throw Rees46.SdkError.invalidArgument("\(name) is empty") + } + return value + } + + /// A count that starts at 1: `limit`, `page`. + static func positive(_ value: Int?, _ name: String) throws { + if let value = value, value < 1 { + throw Rees46.SdkError.invalidArgument("\(name) must be at least 1") + } + } + + /// A price range: finite, not negative, the lowest not above the highest. + static func prices(_ min: Double?, _ max: Double?) throws { + for (name, value) in [("priceMin", min), ("priceMax", max)] { + if let value = value, !value.isFinite || value < 0 { + throw Rees46.SdkError.invalidArgument("\(name) must be a number not below 0") + } + } + if let min = min, let max = max, min > max { + throw Rees46.SdkError.invalidArgument("priceMin is above priceMax") + } + } + + /// The sorting of a listing: `relevance` is the search's. + static func listingSort(_ sortBy: Rees46.SortBy?) throws { + if sortBy == .relevance { + throw Rees46.SdkError.invalidArgument("sortBy relevance is for search.full only") + } + } +} diff --git a/REES46/Classes/Products/ProductAnswers.swift b/REES46/Classes/Products/ProductAnswers.swift new file mode 100644 index 00000000..4fda99a6 --- /dev/null +++ b/REES46/Classes/Products/ProductAnswers.swift @@ -0,0 +1,518 @@ +// +// ProductAnswers.swift +// REES46 +// +// How the catalog's answers become its models, by the rules of `LenientDecoding`: a model reads itself +// from the answer's object (`AnswerReadable`) and stays out of `Decodable`, which would hand its +// decoding to the app as API. +// + +import Foundation + +/// A model the namespaces read from an object of an answer. It throws when the object is not one of +/// it — a product without an id —: an element of a list is then left out, a whole answer is `decoding`. +protocol AnswerReadable { + init(answer: KeyedDecodingContainer) throws +} + +/// `Value` read from an answer, as a `Decodable`. +struct Readable: Decodable { + let value: Value + + init(from decoder: Decoder) throws { + value = try Value(answer: decoder.container(keyedBy: AnswerKey.self)) + } + + /// The method's value of a whole answer: `body` is an object of `Value`, or `decoding`. + static func read(_ body: Data) throws -> Value { + try JSONDecoder().decode(Readable.self, from: body).value + } + + /// The method's value of an answer that is a list of `Value` at its top, without the elements that + /// are not one; an answer that is not a list is `decoding`. + static func readList(_ body: Data) throws -> [Value] { + try JSONDecoder().decode([Element].self, from: body).compactMap(\.value) + } + + /// An element of a list at the top of an answer: `nil` when it is not a `Value`. + private struct Element: Decodable { + let value: Value? + + init(from decoder: Decoder) throws { + value = try? Value(answer: decoder.container(keyedBy: AnswerKey.self)) + } + } +} + +/// One element of a list of strings: a string, or a number as its digits. Anything else, and an empty +/// or blank string, is left out. +private struct AnswerString: Decodable { + let value: String + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let text = try? container.decode(String.self) { + guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "an empty string") + } + value = text + } else if let number = try? container.decode(Int.self) { + value = String(number) + } else if let number = try? container.decode(Double.self), number.isFinite { + value = CatalogQuery.number(number) + } else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "not a string") + } + } +} + +extension KeyedDecodingContainer { + + /// The string at `key`, or the error that makes the object not a model. + func requiredString(_ key: Key) throws -> String { + guard let value = lenientString(key) else { + throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "no \(key.stringValue)")) + } + return value + } + + /// The string at `key` for a field a model cannot do without: an empty one is a value here, a missing + /// one, `null` or one that is not a scalar the error that makes the object not a model. + func requiredText(_ key: Key) throws -> String { + if let value = lenientString(key) ?? (try? decodeIfPresent(String.self, forKey: key)) { + return value + } + throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "no \(key.stringValue)")) + } + + /// The number at `key` for a field a model cannot do without. + func requiredDouble(_ key: Key) throws -> Double { + guard let value = lenientDouble(key) else { + throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "no \(key.stringValue)")) + } + return value + } + + /// The integer at `key` for a field a model cannot do without. + func requiredInt(_ key: Key) throws -> Int { + guard let value = lenientInt(key) else { + throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "no \(key.stringValue)")) + } + return value + } + + /// The model at `key`; `nil` when it is missing or not one. + func model(_ type: Value.Type, _ key: Key) -> Value? { + lenient(Readable.self, key)?.value + } + + /// The models of the list at `key`, without the elements that are not one; `nil` when it is missing + /// or not a list. + func models(_ type: Value.Type, _ key: Key) -> [Value]? { + lenientList(Readable.self, key)?.map(\.value) + } + + /// The models of the list at `key`, or the error that makes the answer not one of the method: the + /// main list of an answer. + func requiredModels(_ type: Value.Type, _ key: Key) throws -> [Value] { + guard let list = models(type, key) else { + throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: codingPath, debugDescription: "no list \(key.stringValue)")) + } + return list + } + + /// The strings of the list at `key`, numbers as their digits; `nil` when it is missing or not a list. + func lenientStrings(_ key: Key) -> [String]? { + lenientList(AnswerString.self, key)?.map(\.value) + } + + /// The object at `key` as a map of names to strings, numbers as their digits; `nil` when it is + /// missing or not an object. + func lenientStringMap(_ key: Key) -> [String: String]? { + lenientMap(key) { $0.lenientString($1) } + } + + /// The object at `key` as a map of names to integers; `nil` when it is missing or not an object. + func lenientIntMap(_ key: Key) -> [String: Int]? { + lenientMap(key) { $0.lenientInt($1) } + } + + /// The object at `key` as a map of names to models; `nil` when it is missing or not an object. + func modelMap(_ type: Value.Type, _ key: Key) -> [String: Value]? { + lenientMap(key) { $0.model(type, $1) } + } + + /// The object at `key`, each of its values read by `value`; a value it cannot read is left out. An + /// empty list is an empty object: the server writes an empty object so (PHP). + private func lenientMap( + _ key: Key, + _ value: (KeyedDecodingContainer, AnswerKey) -> Value? + ) -> [String: Value]? { + guard let object = try? nestedContainer(keyedBy: AnswerKey.self, forKey: key) else { + let list = try? nestedUnkeyedContainer(forKey: key) + return list?.count == 0 ? [:] : nil + } + var map: [String: Value] = [:] + for name in object.allKeys { + map[name.stringValue] = value(object, name) + } + return map + } +} + +// MARK: - Products + +extension Rees46.Product: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + try self.init(answer: answer, preferringUniqid: false) + } + + /// `preferringUniqid`: the card's answer (`products/get`), where `uniqid` is the shop's id. + /// `paramOrder`: the names of `params` in the answer's order, when it is an object (`productParams`). + init(answer: KeyedDecodingContainer, preferringUniqid: Bool, paramOrder: [String] = []) throws { + id = try (preferringUniqid ? answer.lenientString("uniqid") : nil) ?? answer.requiredString("id") + groupId = answer.lenientString("group_id") + name = try answer.requiredText("name") + brand = answer.lenientString("brand") + model = answer.lenientString("model") + description = answer.lenientString("description") + barcode = answer.lenientString("barcode") + url = try answer.requiredText("url") + deeplinkAndroid = answer.lenientString("deeplink_android") + deeplinkIos = answer.lenientString("deeplink_ios") + imageUrl = answer.lenientString("image_url") + picture = answer.lenientString("picture") + resizedImages = answer.lenientStringMap("image_url_resized") + price = try answer.requiredDouble("price") + priceFormatted = answer.lenientString("price_formatted") + priceFull = answer.lenientDouble("price_full") + priceFullFormatted = answer.lenientString("price_full_formatted") + // No old price is 0 in the answer. + oldPrice = answer.lenientDouble("oldprice").flatMap { $0 > 0 ? $0 : nil } + oldPriceFormatted = answer.lenientString("oldprice_formatted") + oldPriceFull = answer.lenientDouble("oldprice_full").flatMap { $0 > 0 ? $0 : nil } + oldPriceFullFormatted = answer.lenientString("oldprice_full_formatted") + currency = try answer.requiredText("currency") + // `discount` is a flag in the card, a number elsewhere: a flag reads as no integer. + discountPercent = answer.lenientInt("discount_percent") ?? answer.lenientInt("discount") + discountFormatted = answer.lenientString("discount_formatted") + salesRate = answer.lenientInt("sales_rate") + relativeSalesRate = answer.lenientDouble("relative_sales_rate") + rating = answer.lenientInt("rating") + isNew = answer.lenientBool("is_new") ?? false + stockQuantity = answer.lenientInt("stock_quantity") + categoryIds = answer.lenientStrings("category_ids") + categories = answer.models(Rees46.ProductCategory.self, "categories") + params = answer.models(Rees46.ProductParam.self, "params") ?? answer.productParams("params", order: paramOrder) + locationIds = answer.lenientStrings("location_ids") + } +} + +extension Rees46.ProductCategory: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + id = try answer.requiredString("id") + name = answer.lenientString("name") + url = answer.lenientString("url") + parentId = answer.lenientString("parent_id") ?? answer.lenientString("parent") + level = answer.lenientInt("level") + count = answer.lenientInt("count") + alias = answer.lenientString("alias") + } +} + +extension Rees46.ProductParam: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + key = try answer.requiredString("key") + values = answer.lenientStrings("values") ?? [] + } +} + +extension KeyedDecodingContainer where Key == AnswerKey { + + /// The parameters at `key` when they are an object, as the card's answer (`products/get`) writes them + /// — name → `{"searchable": true, "value": [...]}` —, where the other answers have a list of + /// `{"key", "values"}`. In the order of `order`, the answer's own, which the decoder does not keep; + /// by name for one `order` does not have. `nil` when `key` is not an object. + func productParams(_ key: Key, order: [String]) -> [Rees46.ProductParam]? { + guard let object = try? nestedContainer(keyedBy: AnswerKey.self, forKey: key) else { return nil } + var rank: [String: Int] = [:] + for (position, name) in order.enumerated() where rank[name] == nil { + rank[name] = position + } + let names = object.allKeys.map(\.stringValue).sorted { + (rank[$0] ?? Int.max, $0) < (rank[$1] ?? Int.max, $1) + } + return names.map { name in + let field = AnswerKey(name) + let entry = try? object.nestedContainer(keyedBy: AnswerKey.self, forKey: field) + let values = entry?.lenientStrings("value") + ?? entry?.lenientString("value").map { [$0] } + ?? object.lenientStrings(field) + ?? object.lenientString(field).map { [$0] } + return Rees46.ProductParam(key: name, values: values ?? []) + } + } +} + +/// The order of the keys of an object in an answer, which `JSONDecoder` does not keep: the order the shop +/// gave the parameters of a product in the card's answer (`products/get`). +struct AnswerKeyOrder { + + private let bytes: [UInt8] + private var index = 0 + + /// The keys of the object at `key` of the object at the top of `data`, in the answer's order; `nil` + /// when the answer is not an object of JSON or `key` is not an object in it. + static func keys(ofObjectAt key: String, in data: Data) -> [String]? { + var scanner = AnswerKeyOrder(bytes: [UInt8](data)) + guard scanner.consume("{"), !scanner.consume("}") else { return nil } + repeat { + guard let name = scanner.member() else { return nil } + if name == key { + return scanner.objectKeys() + } + guard scanner.skipValue() else { return nil } + } while scanner.consume(",") + return nil + } + + /// The keys of the object at the index, in their order; the index after it. + private mutating func objectKeys() -> [String]? { + guard consume("{") else { return nil } + var keys: [String] = [] + if consume("}") { + return keys + } + repeat { + guard let name = member(), skipValue() else { return nil } + keys.append(name) + } while consume(",") + return consume("}") ? keys : nil + } + + /// The key of a member and its colon. + private mutating func member() -> String? { + guard let name = string(), consume(":") else { return nil } + return name + } + + /// Moves past the value at the index; `false` when there is none. + private mutating func skipValue() -> Bool { + skipSpace() + guard index < bytes.count else { return false } + switch bytes[index] { + case UInt8(ascii: "\""): + return string() != nil + case UInt8(ascii: "{"), UInt8(ascii: "["): + var depth = 0 + while index < bytes.count { + switch bytes[index] { + case UInt8(ascii: "\""): + guard string() != nil else { return false } + continue + case UInt8(ascii: "{"), UInt8(ascii: "["): + depth += 1 + case UInt8(ascii: "}"), UInt8(ascii: "]"): + depth -= 1 + if depth == 0 { + index += 1 + return true + } + default: + break + } + index += 1 + } + return false + default: + let start = index + while index < bytes.count, !Self.ends.contains(bytes[index]) { + index += 1 + } + return index > start + } + } + + /// What ends a number, `true`, `false` or `null`. + private static let ends = Set(",}] \t\r\n".utf8) + + /// The string at the index, its escapes read; the index after its closing quote. + private mutating func string() -> String? { + skipSpace() + guard index < bytes.count, bytes[index] == UInt8(ascii: "\"") else { return nil } + let start = index + var escaped = false + index += 1 + while index < bytes.count { + switch bytes[index] { + case UInt8(ascii: "\\"): + escaped = true + index += 2 + case UInt8(ascii: "\""): + index += 1 + let token = Data(bytes[start.. Bool { + skipSpace() + guard index < bytes.count, bytes[index] == UInt8(ascii: character) else { return false } + index += 1 + return true + } + + private mutating func skipSpace() { + while index < bytes.count, Self.space.contains(bytes[index]) { + index += 1 + } + } + + private static let space = Set(" \t\r\n".utf8) +} + +extension Rees46.Location: AnswerReadable { + + /// A location without an id or a name is left out. + init(answer: KeyedDecodingContainer) throws { + id = try answer.requiredString("id") + name = try answer.requiredText("name") + type = answer.lenientString("type") + } +} + +extension Rees46.Brand: AnswerReadable { + + /// A brand without a name or a count is left out. + init(answer: KeyedDecodingContainer) throws { + name = try answer.requiredText("name") + count = try answer.requiredInt("count") + } +} + +extension Rees46.SearchFilter: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + count = answer.lenientInt("count") + priority = answer.lenientInt("priority") + values = answer.lenientIntMap("values") + let ranges = try? answer.nestedContainer(keyedBy: AnswerKey.self, forKey: "ranges") + min = ranges?.lenientDouble("min") + max = ranges?.lenientDouble("max") + } +} + +extension Rees46.IndustrialFilters: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + colors = answer.models(Rees46.ColorFilter.self, "colors") + fashionSizes = answer.models(Rees46.SizeFilter.self, "fashion_sizes") + } +} + +extension Rees46.ColorFilter: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + color = try answer.requiredText("color") + count = try answer.requiredInt("count") + } +} + +extension Rees46.SizeFilter: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + size = try answer.requiredText("size") + count = try answer.requiredInt("count") + } +} + +extension Rees46.PriceRange: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + guard let min = answer.lenientDouble("min"), let max = answer.lenientDouble("max") else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: answer.codingPath, debugDescription: "no min or max")) + } + self.min = min + self.max = max + } +} + +extension Rees46.PriceInterval: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + from = answer.lenientDouble("from") ?? 0 + to = answer.lenientDouble("to") + count = answer.lenientInt("count") + } +} + +extension Rees46.ProductsListResponse: AnswerReadable { + + /// Without a list of products it is not a listing (`decoding`). + init(answer: KeyedDecodingContainer) throws { + products = try answer.requiredModels(Rees46.Product.self, "products") + productsTotal = answer.lenientInt("products_total") + categories = answer.models(Rees46.ProductCategory.self, "categories") + brands = answer.models(Rees46.Brand.self, "brands") + locations = answer.models(Rees46.Location.self, "locations") + filters = answer.modelMap(Rees46.SearchFilter.self, "filters") + industrialFilters = answer.model(Rees46.IndustrialFilters.self, "industrial_filters") + priceRange = answer.model(Rees46.PriceRange.self, "price_range") + priceRanges = answer.models(Rees46.PriceInterval.self, "price_ranges") + priceMedian = answer.lenientDouble("price_median") + } +} + +extension Rees46.CategoryResponse { + + /// The listing of the category: the same answer without what a category has not. + init(_ list: Rees46.ProductsListResponse) { + productsTotal = list.productsTotal + products = list.products + categories = list.categories + brands = list.brands + filters = list.filters + priceRange = list.priceRange + priceRanges = list.priceRanges + priceMedian = list.priceMedian + } +} + +extension ProductCountersResponse: AnswerReadable { + + /// The released model, read leniently: a counter the answer does not have is 0, as the old + /// `getProductCounters` reads it. + init(answer: KeyedDecodingContainer) throws { + daily = answer.model(ProductCounter.self, "daily") + now = answer.model(ProductCounter.self, "now") + triggers = answer.model(ProductCounterTriggers.self, "triggers") + } +} + +extension ProductCounter: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + view = answer.lenientInt("view") ?? 0 + cart = answer.lenientInt("cart") ?? 0 + purchase = answer.lenientInt("purchase") ?? 0 + } +} + +extension ProductCounterTriggers: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + backInStock = answer.lenientInt("back_in_stock") ?? 0 + priceDrop = answer.lenientInt("price_drop") ?? 0 + } +} diff --git a/REES46/Classes/Products/ProductModels.swift b/REES46/Classes/Products/ProductModels.swift new file mode 100644 index 00000000..16f909e1 --- /dev/null +++ b/REES46/Classes/Products/ProductModels.swift @@ -0,0 +1,296 @@ +// +// ProductModels.swift +// REES46 +// +// The catalog's models of the contract (`sdk/contract/products.md`): the product of every answer, its +// categories and parameters, the facets of a listing and the requests of `products`. `collections`, +// `recommendations` and `search` use them too. +// +// Nested in the facade, as `Rees46.SdkError` is: the released top-level `Product`, `Category`, +// `ProductsListResponse` and the rest stay as the old methods return them. A field the answer does not +// have is `nil`, never an empty string or 0, unless the model says otherwise. +// + +import Foundation + +@_spi(Bridge) +extension Rees46 { + + /// A product in every answer of the catalog: the card, a listing, a category, a collection, + /// recommendations, search. + /// + /// `id`, `name`, `url`, `price` and `currency` are always there: a product without one of them is left + /// out of its answer. The other fields are `nil` when the answer does not have them, and so is an + /// empty text. + public struct Product: Equatable { + /// `id`; `uniqid` in the answer of `products.getInfo` when it has one: the shop's own id. + public let id: String + /// `group_id`: the group of the product's variants. The server gives a product without a group + /// a value of its own, `__`. + public let groupId: String? + public let name: String + public let brand: String? + public let model: String? + public let description: String? + public let barcode: String? + public let url: String + public let deeplinkAndroid: String? + public let deeplinkIos: String? + /// `image_url`: the original image. + public let imageUrl: String? + /// `picture`: the image at the answer's size. + public let picture: String? + /// `image_url_resized`: the image by size, `"120"` … `"520"` and `"original"`. + public let resizedImages: [String: String]? + public let price: Double + public let priceFormatted: String? + /// `price_full`: the price with its fraction. + public let priceFull: Double? + public let priceFullFormatted: String? + /// `oldprice`; `nil` when the product has none — the server's 0 too. + public let oldPrice: Double? + public let oldPriceFormatted: String? + /// `oldprice_full`; `nil` when the product has none — the server's 0 too. + public let oldPriceFull: Double? + public let oldPriceFullFormatted: String? + public let currency: String + /// `discount_percent`, else `discount` when it is a number: in the card it is a flag. + public let discountPercent: Int? + public let discountFormatted: String? + public let salesRate: Int? + public let relativeSalesRate: Double? + /// The server sends it only when it is not 0. + public let rating: Int? + /// The server sends `is_new` only when it is true: missing is `false`. + public let isNew: Bool + public let stockQuantity: Int? + public let categoryIds: [String]? + public let categories: [ProductCategory]? + public let params: [ProductParam]? + /// `location_ids`, with `RecommendationRequest.withLocations`: where the product is in stock, or + /// `["global"]`. + public let locationIds: [String]? + } + + /// A category of a product, and a category of the facets of a listing or a search. + public struct ProductCategory: Equatable { + public let id: String + public let name: String? + public let url: String? + /// `parent_id`; `parent` in the facets. + public let parentId: String? + /// The depth from the root; only in a product's categories. + public let level: Int? + /// How many products were found in it; only in the facets. + public let count: Int? + /// Only in the facets. + public let alias: String? + } + + /// A parameter of a product from the shop's feed: its key and values, numbers as strings. + public struct ProductParam: Equatable { + public let key: String + public let values: [String] + } + + /// A location of the shop: a store, a city. + public struct Location: Equatable { + public let id: String + public let name: String + public let type: String? + } + + /// A brand in the facets, with how many products were found of it. + public struct Brand: Equatable { + public let name: String + public let count: Int + } + + /// A facet: one parameter of the products in a sidebar of filters. A list facet has `values`, a + /// numeric one `min` and `max`. + public struct SearchFilter: Equatable { + /// How many products have the parameter. + public let count: Int? + /// The order of the facets. + public let priority: Int? + /// Value → how many products have it. + public let values: [String: Int]? + /// `ranges.min`. + public let min: Double? + /// `ranges.max`. + public let max: Double? + } + + /// The facets of colors and sizes; only in search. + public struct IndustrialFilters: Equatable { + public let colors: [ColorFilter]? + public let fashionSizes: [SizeFilter]? + } + + public struct ColorFilter: Equatable { + public let color: String + public let count: Int + } + + public struct SizeFilter: Equatable { + public let size: String + public let count: Int + } + + /// The lowest and highest price of the products found. + public struct PriceRange: Equatable { + public let min: Double + public let max: Double + } + + /// One interval of prices with how many products are in it. + public struct PriceInterval: Equatable { + /// 0 when the answer has none. + public let from: Double + /// `nil`: no upper bound. + public let to: Double? + public let count: Int? + } + + /// The products of the catalog by filters (`products.getList`). + public struct ProductsListResponse: Equatable { + public let productsTotal: Int? + public let products: [Product] + public let categories: [ProductCategory]? + public let brands: [Brand]? + public let locations: [Location]? + /// The name of a parameter → its facet. + public let filters: [String: SearchFilter]? + /// Only search has it: `/products` does not send it. + public let industrialFilters: IndustrialFilters? + public let priceRange: PriceRange? + public let priceRanges: [PriceInterval]? + public let priceMedian: Double? + } + + /// The products of a category with its facets (`products.getCategory`). + public struct CategoryResponse: Equatable { + public let productsTotal: Int? + public let products: [Product] + public let categories: [ProductCategory]? + public let brands: [Brand]? + /// The name of a parameter → its facet. + public let filters: [String: SearchFilter]? + public let priceRange: PriceRange? + public let priceRanges: [PriceInterval]? + public let priceMedian: Double? + } + + /// What a listing is sorted by. An open set: a key the server adds goes as it is, with no new + /// version of the SDK. + public struct SortBy: RawRepresentable, Hashable { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public static let price = SortBy(rawValue: "price") + public static let discount = SortBy(rawValue: "discount") + public static let salesRate = SortBy(rawValue: "sales_rate") + public static let date = SortBy(rawValue: "date") + public static let priceMargin = SortBy(rawValue: "price_margin") + /// The server applies it only together with another key, which the contract does not send yet. + public static let rating = SortBy(rawValue: "rating") + /// Only `search.full`: a listing refuses it (`invalidArgument`). + public static let relevance = SortBy(rawValue: "relevance") + } + + /// The direction of the sorting; the server sorts in descending order without one. + public enum SortDirection: String { + case asc + case desc + } + + /// The filters, sorting and page of `products.getList`; without any, the first page of the whole + /// catalog. + /// + /// Lists go as one value joined by `,`, an empty one as none. `limit` and `page` start at 1, a price + /// is not negative and `priceMin` not above `priceMax`: otherwise the call is `invalidArgument` and + /// sends nothing. The server drops the fraction of a price. + public struct ProductsListRequest: Equatable { + public var categoryIds: [String]? + public var brands: [String]? + /// For marketplaces. + public var merchants: [String]? + /// Products in stock in these locations. + public var locations: [String]? + public var priceMin: Double? + public var priceMax: Double? + /// A parameter of the products → its values; sent as JSON. + public var filters: [String: [String]]? + /// Not `relevance`. + public var sortBy: SortBy? + public var sortDir: SortDirection? + public var limit: Int? + public var page: Int? + + public init( + categoryIds: [String]? = nil, + brands: [String]? = nil, + merchants: [String]? = nil, + locations: [String]? = nil, + priceMin: Double? = nil, + priceMax: Double? = nil, + filters: [String: [String]]? = nil, + sortBy: SortBy? = nil, + sortDir: SortDirection? = nil, + limit: Int? = nil, + page: Int? = nil + ) { + self.categoryIds = categoryIds + self.brands = brands + self.merchants = merchants + self.locations = locations + self.priceMin = priceMin + self.priceMax = priceMax + self.filters = filters + self.sortBy = sortBy + self.sortDir = sortDir + self.limit = limit + self.page = page + } + } + + /// The filters, sorting and page of `products.getCategory`, by the rules of `ProductsListRequest`. + public struct CategoryRequest: Equatable { + public var brands: [String]? + public var locations: [String]? + /// A parameter of the products → its values; sent as JSON. + public var filters: [String: [String]]? + public var priceMin: Double? + public var priceMax: Double? + /// Not `relevance`. + public var sortBy: SortBy? + public var sortDir: SortDirection? + public var limit: Int? + public var page: Int? + + public init( + brands: [String]? = nil, + locations: [String]? = nil, + filters: [String: [String]]? = nil, + priceMin: Double? = nil, + priceMax: Double? = nil, + sortBy: SortBy? = nil, + sortDir: SortDirection? = nil, + limit: Int? = nil, + page: Int? = nil + ) { + self.brands = brands + self.locations = locations + self.filters = filters + self.priceMin = priceMin + self.priceMax = priceMax + self.sortBy = sortBy + self.sortDir = sortDir + self.limit = limit + self.page = page + } + } +} diff --git a/REES46/Classes/Products/ProductsAPI.swift b/REES46/Classes/Products/ProductsAPI.swift new file mode 100644 index 00000000..fd8cb60d --- /dev/null +++ b/REES46/Classes/Products/ProductsAPI.swift @@ -0,0 +1,88 @@ +// +// ProductsAPI.swift +// REES46 +// +// The `products` namespace of the contract (`sdk/contract/products.md`). +// + +import Foundation + +/** + The shop's products: a product's card, the catalog by filters, the counters of a product and the page of + a category. Each method is one request; the answer comes as the contract's models (`Rees46.Product` and + the rest). + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + + Every `completion` is called once, on the main thread, with the value or the error: `notInitialized` on + the old core or after `release()`, `shopBlocked`, `invalidArgument` for an argument refused before + anything is sent, `network`, `timeout`, `http(code:serverCode:)`, `decoding`, `cancelled` for a call + `release()` ended. The `async` forms throw the same `Rees46.SdkError`, and cancelling the task ends the + call as `cancelled`. Nothing is repeated: the app decides. + */ +@_spi(Bridge) +public protocol ProductsAPI { + + /// The card of a product (`GET products/get`): `nil` for an id the server does not know — it + /// answers that with an empty object. `itemId` is the shop's id of the product, not empty. + func getInfo(itemId: String, completion: @escaping (Result) -> Void) + + func getInfo(itemId: String) async throws -> Rees46.Product? + + /// The catalog by filters, sorted and by pages (`GET products`): a listing without a query. + func getList(_ request: Rees46.ProductsListRequest, completion: @escaping (Result) -> Void) + + func getList(_ request: Rees46.ProductsListRequest) async throws -> Rees46.ProductsListResponse + + /// How many times a product was viewed, put into a cart and bought today and in the last 30 minutes, + /// and how many subscriptions to its price and stock it has (`GET products/counters`). + func getCounters(itemId: String, completion: @escaping (Result) -> Void) + + func getCounters(itemId: String) async throws -> ProductCountersResponse + + /// The page of a category: its products, facets, prices and sorting. The listing of `getList` with + /// the category as its only `categoryIds`, which the server answers as it answers `category/{id}`. + func getCategory( + categoryId: String, + request: Rees46.CategoryRequest, + completion: @escaping (Result) -> Void + ) + + func getCategory(categoryId: String, request: Rees46.CategoryRequest) async throws -> Rees46.CategoryResponse +} + +/// The requests by default: protocol requirements cannot carry them. +@_spi(Bridge) +extension ProductsAPI { + + /// The first page of the whole catalog. + public func getList(completion: @escaping (Result) -> Void) { + getList(Rees46.ProductsListRequest(), completion: completion) + } + + /// The first page of the whole catalog. + public func getList() async throws -> Rees46.ProductsListResponse { + try await getList(Rees46.ProductsListRequest()) + } + + /// The first page of the category. + public func getCategory(categoryId: String, completion: @escaping (Result) -> Void) { + getCategory(categoryId: categoryId, request: Rees46.CategoryRequest(), completion: completion) + } + + /// The first page of the category. + public func getCategory(categoryId: String) async throws -> Rees46.CategoryResponse { + try await getCategory(categoryId: categoryId, request: Rees46.CategoryRequest()) + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The shop's products (`ProductsAPI`): on the new core only. + public var products: ProductsAPI { + ProductsAPIImpl(requests: NamespaceRequests(self)) + } +} diff --git a/REES46/Classes/Products/ProductsAPIImpl.swift b/REES46/Classes/Products/ProductsAPIImpl.swift new file mode 100644 index 00000000..12f5b736 --- /dev/null +++ b/REES46/Classes/Products/ProductsAPIImpl.swift @@ -0,0 +1,136 @@ +// +// ProductsAPIImpl.swift +// REES46 +// + +import Foundation + +struct ProductsAPIImpl: ProductsAPI { + + let requests: NamespaceRequests + + func getInfo(itemId: String, completion: @escaping (Result) -> Void) { + requests.call("products.getInfo", completion: completion) { try Self.infoRequest(itemId: itemId) } + } + + func getInfo(itemId: String) async throws -> Rees46.Product? { + try await requests.value("products.getInfo") { try Self.infoRequest(itemId: itemId) } + } + + func getList(_ request: Rees46.ProductsListRequest, completion: @escaping (Result) -> Void) { + requests.call("products.getList", completion: completion) { try Self.listRequest(request) } + } + + func getList(_ request: Rees46.ProductsListRequest) async throws -> Rees46.ProductsListResponse { + try await requests.value("products.getList") { try Self.listRequest(request) } + } + + func getCounters(itemId: String, completion: @escaping (Result) -> Void) { + requests.call("products.getCounters", completion: completion) { try Self.countersRequest(itemId: itemId) } + } + + func getCounters(itemId: String) async throws -> ProductCountersResponse { + try await requests.value("products.getCounters") { try Self.countersRequest(itemId: itemId) } + } + + func getCategory( + categoryId: String, + request: Rees46.CategoryRequest, + completion: @escaping (Result) -> Void + ) { + requests.call("products.getCategory", completion: completion) { try Self.categoryRequest(categoryId: categoryId, request) } + } + + func getCategory(categoryId: String, request: Rees46.CategoryRequest) async throws -> Rees46.CategoryResponse { + try await requests.value("products.getCategory") { try Self.categoryRequest(categoryId: categoryId, request) } + } + + // MARK: - Requests + + /// `GET products/get?item_id=`. The server answers an id it does not know with `{}`: no product. An + /// answer with something else but neither `uniqid` nor `id` is `decoding`. + static func infoRequest(itemId: String) throws -> ApiRequest { + let id = try CatalogQuery.identifier(itemId, "itemId") + return ApiRequest(method: .get, path: "products/get", query: ["item_id": id]) { body in + guard !body.isEmpty else { return nil } + return try ProductCard.read(body) + } + } + + /// `GET products` with the request's filters; `extended` is not sent, the server always gives the + /// products whole. + static func listRequest(_ request: Rees46.ProductsListRequest) throws -> ApiRequest { + try CatalogQuery.positive(request.limit, "limit") + try CatalogQuery.positive(request.page, "page") + try CatalogQuery.prices(request.priceMin, request.priceMax) + try CatalogQuery.listingSort(request.sortBy) + var query = CatalogQuery() + query.set("categories", list: request.categoryIds) + query.set("brands", list: request.brands) + query.set("merchants", list: request.merchants) + query.set("locations", list: request.locations) + query.set("price_min", number: request.priceMin) + query.set("price_max", number: request.priceMax) + try query.set("filters", filters: request.filters) + query.set("sort_by", request.sortBy?.rawValue) + query.set("sort_dir", request.sortDir?.rawValue) + query.set("limit", int: request.limit) + query.set("page", int: request.page) + return ApiRequest(method: .get, path: "products", query: query.fields) { body in + try Readable.read(body) + } + } + + /// `GET products/counters?item=`. An answer without a body or without a counter has none of it. + static func countersRequest(itemId: String) throws -> ApiRequest { + let id = try CatalogQuery.identifier(itemId, "itemId") + return ApiRequest(method: .get, path: "products/counters", query: ["item": id]) { body in + try Readable.read(body.isEmpty ? Data("{}".utf8) : body) + } + } + + /// The listing of `listRequest` with the category alone in `categories`: `GET category/{id}` is + /// that same listing on the server, and it is to be removed there (question В31). + static func categoryRequest(categoryId: String, _ request: Rees46.CategoryRequest) throws -> ApiRequest { + let id = try CatalogQuery.identifier(categoryId, "categoryId") + let list = try listRequest(Rees46.ProductsListRequest( + categoryIds: [id], + brands: request.brands, + locations: request.locations, + priceMin: request.priceMin, + priceMax: request.priceMax, + filters: request.filters, + sortBy: request.sortBy, + sortDir: request.sortDir, + limit: request.limit, + page: request.page + )) + return ApiRequest(method: list.method, path: list.path, query: list.query) { body in + Rees46.CategoryResponse(try list.decode(body)) + } + } +} + +/// The answer of `products/get`: the product itself, its id `uniqid`; `{}` is no product. Its `params` is +/// an object of name → values, read in the answer's order (`AnswerKeyOrder`). +private struct ProductCard: Decodable { + let product: Rees46.Product? + + init(from decoder: Decoder) throws { + let answer = try decoder.container(keyedBy: AnswerKey.self) + let order = Self.paramOrder.flatMap { decoder.userInfo[$0] as? [String] } ?? [] + product = answer.allKeys.isEmpty ? nil : try Rees46.Product(answer: answer, preferringUniqid: true, paramOrder: order) + } + + /// The product of `body`, or `decoding`. + static func read(_ body: Data) throws -> Rees46.Product? { + let decoder = JSONDecoder() + if let key = paramOrder { + decoder.userInfo[key] = AnswerKeyOrder.keys(ofObjectAt: "params", in: body) ?? [] + } + return try decoder.decode(ProductCard.self, from: body).product + } + + /// Where `read` hands the decoder the names of `params` in the answer's order. + private static let paramOrder = CodingUserInfoKey(rawValue: "REES46.ProductCard.paramOrder") +} diff --git a/REES46/Classes/Profile/ClientBody.swift b/REES46/Classes/Profile/ClientBody.swift new file mode 100644 index 00000000..0929b75b --- /dev/null +++ b/REES46/Classes/Profile/ClientBody.swift @@ -0,0 +1,105 @@ +// +// ClientBody.swift +// REES46 +// +// The JSON body of a request of the client's namespaces — `profile`, `subscriptions`, `segments` —, +// built and checked before anything is sent: a refused argument throws +// `Rees46.SdkError.invalidArgument`. +// + +import Foundation + +/// The fields of one body: what is `nil` is not sent. +struct ClientBody { + + private(set) var fields: [String: Any] = [:] + + init(_ fields: [String: Any] = [:]) { + self.fields = fields + } + + mutating func set(_ name: String, _ value: Any?) { + guard let value = value else { return } + fields[name] = value + } + + /// A contact or an identifier of the customer: none is not sent, an empty or blank one is refused. + mutating func identifier(_ name: String, _ value: String?, _ argument: String) throws { + guard let value = value else { return } + guard !ApiArguments.isBlank(value) else { + throw Rees46.SdkError.invalidArgument("\(argument) is empty") + } + fields[name] = value + } + + /// The shop's own properties of a profile, each at the top level of the body. A key is of + /// `[a-z0-9_]` and none of the request's own fields or the SDK's; a value is a string, a number, a + /// boolean, `NSNull` or `nil`, or a list or map of them. + mutating func customProperties(_ properties: [String: Any]?) throws { + guard let properties = properties else { return } + for key in properties.keys.sorted() { + guard !key.isEmpty, key.unicodeScalars.allSatisfy(Self.keyCharacters.contains) else { + throw Rees46.SdkError.invalidArgument("the custom property \(key) is not of [a-z0-9_]") + } + guard !Self.reservedKeys.contains(key) else { + throw Rees46.SdkError.invalidArgument("the custom property \(key) is a field of the request") + } + guard let value = properties[key].flatMap(Self.json) else { + throw Rees46.SdkError.invalidArgument("the custom property \(key) is not a JSON value") + } + fields[key] = value + } + } + + // MARK: - Values + + /// `value` as a birthday `profile/set` takes — an existing day `YYYY-MM-DD` of the years 1000 to + /// 2999 (`ApiArguments.isBirthday`) —, or `invalidArgument`: the server would ignore it in silence. + static func birthday(_ value: String, _ name: String) throws -> String { + guard ApiArguments.isBirthday(value) else { + throw Rees46.SdkError.invalidArgument("\(name) is not a date YYYY-MM-DD of the years 1000 to 2999") + } + return value + } + + /// `value` as JSON — `nil` and an empty optional become `NSNull` —; `nil` when it is not JSON: a + /// `Date`, an object, a number that is not finite. + static func json(_ value: Any) -> Any? { + switch value { + case let text as String: + return text + case is NSNull: + return NSNull() + case let list as [Any]: + let items = list.map(json) + return items.contains { $0 == nil } ? nil : items.compactMap { $0 } + case let map as [String: Any]: + var object: [String: Any] = [:] + for (key, item) in map { + guard let converted = json(item) else { return nil } + object[key] = converted + } + return object + case let number as NSNumber: + return number.doubleValue.isFinite ? number : nil + default: + let mirror = Mirror(reflecting: value) + guard mirror.displayStyle == .optional else { return nil } + return mirror.children.first.map { json($0.value) } ?? NSNull() + } + } + + /// The fields as one text, the same for the same fields: what popups v3 tell a change by. + static func signature(_ fields: [String: Any]) -> String { + SafeJSON.data(fields, options: [.sortedKeys]).flatMap { String(data: $0, encoding: .utf8) } ?? String(describing: fields) + } + + private static let keyCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz0123456789_") + + /// The fields of `ProfileUpdateRequest` and the ones the SDK adds to every request. + private static let reservedKeys: Set = [ + "email", "phone", "id", "external_id", "loyalty_id", "telegram_id", "fb_id", "vk_id", "first_name", "last_name", + "gender", "birthday", "age", "location", "kids", "auto", + "shop_id", "did", "sid", "seance", "segment", "stream" + ] +} diff --git a/REES46/Classes/Profile/ProfileAPI.swift b/REES46/Classes/Profile/ProfileAPI.swift new file mode 100644 index 00000000..7499ea2a --- /dev/null +++ b/REES46/Classes/Profile/ProfileAPI.swift @@ -0,0 +1,183 @@ +// +// ProfileAPI.swift +// REES46 +// +// The `profile` namespace of the contract (`sdk/contract/profile.md`). +// + +import Foundation + +/** + The customer's profile in the CDP: reading it, writing its properties, and the products of the last + order. The server finds the customer by the device id; the SDK sends no secret of the shop, so reading + gives only the profile's fields that are not sensitive. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + + Every `completion` is called once, on the main thread, with the value or the error: `notInitialized` on + the old core or after `release()`, `shopBlocked`, `invalidArgument` for an argument refused before + anything is sent, `network`, `timeout`, `http(code:serverCode:)`, `decoding`, `cancelled` for a call + `release()` ended. The `async` forms throw the same `Rees46.SdkError`, and cancelling the task ends the + call as `cancelled`. Nothing is repeated: the app decides. + */ +@_spi(Bridge) +public protocol ProfileAPI { + + /// The customer's profile (`GET profile`): what the server gives without the shop's secret — no + /// name, email or phone. A device the server does not know is `http(404)`. + func get(completion: @escaping (Result) -> Void) + + func get() async throws -> Rees46.Profile + + /** + Writes the properties of the profile (`POST profile/set`): only the fields given change. An empty + text erases `externalId`, `telegramId`, `birthday`, `fbId` and `vkId`, and leaves `location`, + `firstName` and `lastName` empty; `age` 0 erases the age. The server does not erase `email`, + `phone` or `loyaltyId` with an empty text, so an empty one is refused. `gender` has no empty value: + `set` cannot erase it. + + An identifier of another customer — `email`, `phone`, `externalId`, `loyaltyId`, `telegramId` — + moves the device to that customer's profile: a sign-in, or another user on the same device. Call it + on sign-in, when the city changes, and on every launch with the current identifier and city. + + Refused before anything is sent (`invalidArgument`): a request without a field, an empty `email`, + `phone` or `loyaltyId`, a `birthday` — a kid's too — that is not an existing day `YYYY-MM-DD` of + the years 1000 to 2999 (the server would ignore it in silence; an empty one erases it, but not a + kid's), a negative `age`, a key of + `customProperties` not of `[a-z0-9_]` or one of the request's own or the SDK's fields, a value of + it that is not a string, a number, a boolean, `NSNull`, or a list or map of them. The server checks + the email and the phone. + */ + func set(_ request: Rees46.ProfileUpdateRequest, completion: @escaping (Result) -> Void) + + func set(_ request: Rees46.ProfileUpdateRequest) async throws + + /// The products of the customer's last order (`GET orders/last_for_user`); no order is an empty + /// list. A device the server does not know is `http(400)`. + func getLastOrder(completion: @escaping (Result<[Rees46.Product], Rees46.SdkError>) -> Void) + + func getLastOrder() async throws -> [Rees46.Product] +} + +@_spi(Bridge) +extension Rees46 { + + /// The customer's profile as the server gives it without the shop's secret. Which fields it has + /// depends on the shop's settings; a field the answer does not have is `nil`. + public struct Profile { + /// The server's own id of the customer, not `externalId`. + public let id: String? + public let hasEmail: Bool? + /// When the shop first got the email: `YYYY-MM-DD HH:MM:SS`, without a time zone. + public let emailRegisteredAt: String? + public let gender: Gender? + /// The gender the server worked out. + public let computedGender: Gender? + public let boughtSomething: Bool? + /// The shop's own properties of the profile, as the answer has them: strings, numbers, booleans, + /// `NSNull`, lists and maps of them. + public let customProperties: [String: Any]? + } + + /// The properties `profile.set` writes: only the ones given change, `nil` is not sent. + public struct ProfileUpdateRequest { + public var email: String? + public var phone: String? + /// The customer's id in the shop's system; sent as both `id` and `external_id`. + public var externalId: String? + /// The id in an external loyalty program. + public var loyaltyId: String? + public var telegramId: String? + public var fbId: String? + public var vkId: String? + public var firstName: String? + public var lastName: String? + public var gender: Gender? + /// `YYYY-MM-DD` of the years 1000 to 2999: a date, not a moment, so no time zone moves it a day. + /// An empty one erases it. + public var birthday: String? + /// From 0; 0 erases the age. + public var age: Int? + /// The city: an id of a location of the shop's feed. + public var location: String? + public var kids: [ProfileKid]? + /// Sent as `auto`. + public var cars: [ProfileCar]? + /// The properties the shop made in its account, each sent at the top level of the request. A + /// date goes as a string `YYYY-MM-DD`. + public var customProperties: [String: Any]? + + public init( + email: String? = nil, + phone: String? = nil, + externalId: String? = nil, + loyaltyId: String? = nil, + telegramId: String? = nil, + fbId: String? = nil, + vkId: String? = nil, + firstName: String? = nil, + lastName: String? = nil, + gender: Gender? = nil, + birthday: String? = nil, + age: Int? = nil, + location: String? = nil, + kids: [ProfileKid]? = nil, + cars: [ProfileCar]? = nil, + customProperties: [String: Any]? = nil + ) { + self.email = email + self.phone = phone + self.externalId = externalId + self.loyaltyId = loyaltyId + self.telegramId = telegramId + self.fbId = fbId + self.vkId = vkId + self.firstName = firstName + self.lastName = lastName + self.gender = gender + self.birthday = birthday + self.age = age + self.location = location + self.kids = kids + self.cars = cars + self.customProperties = customProperties + } + } + + /// A kid of the customer. + public struct ProfileKid: Equatable { + public var gender: Gender? + /// `YYYY-MM-DD`. + public var birthday: String? + + public init(gender: Gender? = nil, birthday: String? = nil) { + self.gender = gender + self.birthday = birthday + } + } + + /// A car of the customer. + public struct ProfileCar: Equatable { + public var brand: String? + public var model: String? + /// The API's documentation calls it the VIN. + public var vds: String? + + public init(brand: String? = nil, model: String? = nil, vds: String? = nil) { + self.brand = brand + self.model = model + self.vds = vds + } + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The customer's profile (`ProfileAPI`): on the new core only. + public var profile: ProfileAPI { + ProfileAPIImpl(requests: NamespaceRequests(self), popups: self as? SimplePersonalizationSDK) + } +} diff --git a/REES46/Classes/Profile/ProfileAPIImpl.swift b/REES46/Classes/Profile/ProfileAPIImpl.swift new file mode 100644 index 00000000..c9fddf20 --- /dev/null +++ b/REES46/Classes/Profile/ProfileAPIImpl.swift @@ -0,0 +1,180 @@ +// +// ProfileAPIImpl.swift +// REES46 +// + +import Foundation + +struct ProfileAPIImpl: ProfileAPI { + + let requests: NamespaceRequests + /// The instance whose popups v3 hear that the profile changed. + weak var popups: SimplePersonalizationSDK? + + func get(completion: @escaping (Result) -> Void) { + requests.call("profile.get", completion: completion) { Self.profileRequest } + } + + func get() async throws -> Rees46.Profile { + try await requests.value("profile.get") { Self.profileRequest } + } + + func set(_ request: Rees46.ProfileUpdateRequest, completion: @escaping (Result) -> Void) { + requests.call("profile.set", completion: completion) { try changing(Self.setRequest(request)) } + } + + func set(_ request: Rees46.ProfileUpdateRequest) async throws { + try await requests.value("profile.set") { try changing(Self.setRequest(request)) } + } + + func getLastOrder(completion: @escaping (Result<[Rees46.Product], Rees46.SdkError>) -> Void) { + requests.call("profile.getLastOrder", completion: completion) { Self.lastOrderRequest } + } + + func getLastOrder() async throws -> [Rees46.Product] { + try await requests.value("profile.getLastOrder") { Self.lastOrderRequest } + } + + /// `request` once it is on its way: popups v3 load their list anew for a profile new in the session, + /// as for the old `setProfileData`. + private func changing(_ request: ApiRequest) -> ApiRequest { + popups?.popupsV3.contextChanged("profile", signature: ClientBody.signature(request.body)) + return request + } + + // MARK: - Requests + + /// `GET profile`: the profile of the device's customer. An answer without a body has no field. + static var profileRequest: ApiRequest { + ApiRequest(method: .get, path: "profile") { body in + try Readable.read(body.isEmpty ? Data("{}".utf8) : body) + } + } + + /// `POST profile/set` with the fields the request gives, its custom properties at the top level. An + /// empty `externalId`, `telegramId` or `birthday` goes as `""`: the server erases them so. It does not + /// erase `email`, `phone` or `loyalty_id` so: an empty one is refused. Any other text goes as it is. + static func setRequest(_ request: Rees46.ProfileUpdateRequest) throws -> ApiRequest { + var body = ClientBody() + try body.identifier("email", request.email, "email") + try body.identifier("phone", request.phone, "phone") + body.set("id", request.externalId) + body.set("external_id", request.externalId) + try body.identifier("loyalty_id", request.loyaltyId, "loyaltyId") + body.set("telegram_id", request.telegramId) + body.set("fb_id", request.fbId) + body.set("vk_id", request.vkId) + body.set("first_name", request.firstName) + body.set("last_name", request.lastName) + body.set("gender", request.gender?.wire) + if let birthday = request.birthday { + body.set("birthday", birthday.isEmpty ? birthday : try ClientBody.birthday(birthday, "birthday")) + } + if let age = request.age { + guard age >= 0 else { throw Rees46.SdkError.invalidArgument("age is negative") } + body.set("age", age) + } + body.set("location", request.location) + if let kids = request.kids, !kids.isEmpty { + body.set("kids", try kids.map { kid -> [String: Any] in + var fields: [String: Any] = [:] + fields["gender"] = kid.gender?.wire + fields["birthday"] = try kid.birthday.map { try ClientBody.birthday($0, "the birthday of a kid") } + return fields + }) + } + if let cars = request.cars, !cars.isEmpty { + body.set("auto", cars.map { car -> [String: Any] in + var fields: [String: Any] = [:] + fields["brand"] = car.brand + fields["model"] = car.model + fields["vds"] = car.vds + return fields + }) + } + try body.customProperties(request.customProperties) + guard !body.fields.isEmpty else { + throw Rees46.SdkError.invalidArgument("the request sets no field of the profile") + } + return ApiRequest(method: .post, path: "profile/set", body: body.fields) { _ in () } + } + + /// `GET orders/last_for_user`: a list of products at the top of the answer; no order is an empty + /// one, and so is an answer without a body. An answer that is not a list is `decoding`. + static var lastOrderRequest: ApiRequest<[Rees46.Product]> { + ApiRequest(method: .get, path: "orders/last_for_user") { body in + guard !body.isEmpty else { return [] } + return try Readable.readList(body) + } + } +} + +extension Gender { + + /// The value on the wire: `m`, `f`. + var wire: String { + switch self { + case .male: return "m" + case .female: return "f" + } + } + + /// The value of an answer; one the SDK does not know is none. + init?(wire: String?) { + switch wire?.lowercased() { + case "m", "male": self = .male + case "f", "female": self = .female + default: return nil + } + } +} + +extension Rees46.Profile: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + id = answer.lenientString("id") + hasEmail = answer.lenientBool("has_email") + emailRegisteredAt = answer.lenientString("email_registered_at") + gender = Gender(wire: answer.lenientString("gender")) + computedGender = Gender(wire: answer.lenientString("computed_gender")) + boughtSomething = answer.lenientBool("bought_something") + customProperties = answer.lenient(AnyJSON.self, "custom_properties")?.value as? [String: Any] + } +} + +/// Any JSON value: a map, a list, a string, a number, a boolean or `NSNull`. +struct AnyJSON: Decodable { + let value: Any + + init(from decoder: Decoder) throws { + if let object = try? decoder.container(keyedBy: AnswerKey.self) { + var map: [String: Any] = [:] + for key in object.allKeys { + map[key.stringValue] = (try? object.decode(AnyJSON.self, forKey: key))?.value ?? NSNull() + } + value = map + return + } + if var list = try? decoder.unkeyedContainer() { + var items: [Any] = [] + while !list.isAtEnd { + guard let item = try? list.decode(AnyJSON.self) else { break } + items.append(item.value) + } + value = items + return + } + let single = try decoder.singleValueContainer() + if single.decodeNil() { + value = NSNull() + } else if let flag = try? single.decode(Bool.self) { + value = flag + } else if let number = try? single.decode(Int.self) { + value = number + } else if let number = try? single.decode(Double.self) { + value = number + } else { + value = try single.decode(String.self) + } + } +} diff --git a/REES46/Classes/Recommendations/RecommendationsAPI.swift b/REES46/Classes/Recommendations/RecommendationsAPI.swift new file mode 100644 index 00000000..6c087b01 --- /dev/null +++ b/REES46/Classes/Recommendations/RecommendationsAPI.swift @@ -0,0 +1,129 @@ +// +// RecommendationsAPI.swift +// REES46 +// +// The `recommendations` namespace of the contract (`sdk/contract/recommendations.md`). +// + +import Foundation + +/** + The shop's blocks of recommendations: similar products, bought together, popular and the rest, set up in + its account. A block gives its products for the customer and where they are: on a product's card, in a + category, on the search's page. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + */ +@_spi(Bridge) +public protocol RecommendationsAPI { + + /** + The products of the block `code` (`GET recommend/{code}`). + + With `extended`, the default, the products come whole; without it only their ids (`itemIds`). A + block on pause gives no products. For the views, carts and purchases to count for the block, send + them to `tracking` with the source `TrackingSource(type: .dynamic, code: code)`. + + `completion` is called once, on the main thread, with the block or the error: `notInitialized` on + the old core or after `release()`, `shopBlocked`, `invalidArgument` for an empty `code` or a + refused request, `network`, `timeout`, `http(code:serverCode:)` — `404` for a block the shop does not + have, `402` for a service not paid —, `decoding`, `cancelled` for a call `release()` ended. Nothing + is repeated: the app decides. + */ + func get( + code: String, + request: Rees46.RecommendationRequest, + completion: @escaping (Result) -> Void + ) + + /// `get(code:request:completion:)` for `async` code: throws the `Rees46.SdkError`; cancelling the task + /// ends the call as `cancelled`. + func get(code: String, request: Rees46.RecommendationRequest) async throws -> Rees46.RecommendationResponse +} + +/// The request by default: protocol requirements cannot carry it. +@_spi(Bridge) +extension RecommendationsAPI { + + /// The block's products, whole, without a context. + public func get(code: String, completion: @escaping (Result) -> Void) { + get(code: code, request: Rees46.RecommendationRequest(), completion: completion) + } + + /// The block's products, whole, without a context. + public func get(code: String) async throws -> Rees46.RecommendationResponse { + try await get(code: code, request: Rees46.RecommendationRequest()) + } +} + +@_spi(Bridge) +extension Rees46 { + + /// Where the customer is and what the block gives (`recommendations.get`). + /// + /// Lists go as one value joined by `,`, an empty one as none. `limit` starts at 1, and + /// `withLocations` needs `extended`: otherwise the call is `invalidArgument` and sends nothing. + public struct RecommendationRequest: Equatable { + /// The product on screen: a card, a cart. + public var itemId: String? + /// The category on screen. + public var categoryId: String? + /// The search query on screen, for a block on the search's page. + public var searchQuery: String? + public var excludedItemIds: [String]? + public var brands: [String]? + public var locations: [String]? + public var limit: Int? + /// The products whole; without it, only their ids (`RecommendationResponse.itemIds`). + public var extended: Bool + /// Each product's `locationIds`; only with `extended`. + public var withLocations: Bool + + public init( + itemId: String? = nil, + categoryId: String? = nil, + searchQuery: String? = nil, + excludedItemIds: [String]? = nil, + brands: [String]? = nil, + locations: [String]? = nil, + limit: Int? = nil, + extended: Bool = true, + withLocations: Bool = false + ) { + self.itemId = itemId + self.categoryId = categoryId + self.searchQuery = searchQuery + self.excludedItemIds = excludedItemIds + self.brands = brands + self.locations = locations + self.limit = limit + self.extended = extended + self.withLocations = withLocations + } + } + + /// The products of a block. + public struct RecommendationResponse: Equatable { + /// The block's id. + public let id: Int? + /// The block's title. + public let title: String? + /// The link of the title, when the block has one. + public let link: String? + /// The products, with `extended`; empty without it, and for a block on pause. + public let products: [Product] + /// The products' ids: of `products` with `extended`, the answer's list without it. + public let itemIds: [String] + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The shop's blocks of recommendations (`RecommendationsAPI`): on the new core only. + public var recommendations: RecommendationsAPI { + RecommendationsAPIImpl(requests: NamespaceRequests(self)) + } +} diff --git a/REES46/Classes/Recommendations/RecommendationsAPIImpl.swift b/REES46/Classes/Recommendations/RecommendationsAPIImpl.swift new file mode 100644 index 00000000..ef79dacf --- /dev/null +++ b/REES46/Classes/Recommendations/RecommendationsAPIImpl.swift @@ -0,0 +1,73 @@ +// +// RecommendationsAPIImpl.swift +// REES46 +// + +import Foundation + +struct RecommendationsAPIImpl: RecommendationsAPI { + + let requests: NamespaceRequests + + func get( + code: String, + request: Rees46.RecommendationRequest, + completion: @escaping (Result) -> Void + ) { + requests.call("recommendations.get", completion: completion) { try Self.blockRequest(code: code, request) } + } + + func get(code: String, request: Rees46.RecommendationRequest) async throws -> Rees46.RecommendationResponse { + try await requests.value("recommendations.get") { try Self.blockRequest(code: code, request) } + } + + /// `GET recommend/{code}`, the code encoded in the path. The product goes as `item_id` and the + /// category as `category`, the names the server prefers; `resize_image` is not sent, the server + /// does not read it. + static func blockRequest(code: String, _ request: Rees46.RecommendationRequest) throws -> ApiRequest { + let code = try CatalogQuery.identifier(code, "code") + try CatalogQuery.positive(request.limit, "limit") + if request.withLocations, !request.extended { + throw Rees46.SdkError.invalidArgument("withLocations needs extended") + } + var query = CatalogQuery() + query.set("item_id", request.itemId) + query.set("category", request.categoryId) + query.set("search_query", request.searchQuery) + query.set("exclude", list: request.excludedItemIds) + query.set("brands", list: request.brands) + query.set("locations", list: request.locations) + query.set("limit", int: request.limit) + query.set("extended", request.extended ? "true" : nil) + query.set("with_locations", request.withLocations ? "true" : nil) + return ApiRequest(method: .get, path: "recommend/\(CatalogQuery.pathSegment(code))", query: query.fields) { body in + // A block on pause may answer without a body too: no products. + try Readable.read(body.isEmpty ? Data(#"{"state": "paused"}"#.utf8) : body).response + } + } +} + +/// The answer of `recommend/{code}`: its `recommends` are whole products or their ids, whatever was asked. +/// A block on pause answers `{"state": "paused"}` without them: no products. Without a list of them and +/// not on pause it is not the block's answer (`decoding`). +private struct RecommendationAnswer: AnswerReadable { + let response: Rees46.RecommendationResponse + + init(answer: KeyedDecodingContainer) throws { + let products = answer.models(Rees46.Product.self, "recommends") + let ids = answer.lenientStrings("recommends") + let paused = answer.lenientString("state") == "paused" + guard products != nil || ids != nil || paused else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: answer.codingPath, debugDescription: "no list recommends")) + } + let whole = products ?? [] + response = Rees46.RecommendationResponse( + id: answer.lenientInt("id"), + title: answer.lenientString("title"), + link: answer.lenientString("link"), + products: whole, + // The products' ids, or the ids of the simple answer. + itemIds: whole.isEmpty ? (ids ?? []) : whole.map(\.id) + ) + } +} diff --git a/REES46/Classes/Reviews/ReviewsAPI.swift b/REES46/Classes/Reviews/ReviewsAPI.swift new file mode 100644 index 00000000..2e21afdd --- /dev/null +++ b/REES46/Classes/Reviews/ReviewsAPI.swift @@ -0,0 +1,227 @@ +// +// ReviewsAPI.swift +// REES46 +// +// The `reviews` namespace of the contract (`sdk/contract/reviews.md`). +// + +import Foundation + +/** + The customer's feedback: NPS, CSAT and CES scores with the dictionaries behind them, and the reviews of + products. The app asks for a score with its own interface and sends it with a `create…` method; the + question and the thanks for a score come from the dictionary. + + The polls go to API v3, on the host of the shop's account (`Rees46Config.appDomain`); the reviews of + products go to the API host (`apiDomain`). + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. The SDK's `review(rate:channel:category:orderId:comment:completion:)` + stays as it is for apps. + + Every `completion` is called once, on the main thread, with the value or the error: `notInitialized` on + the old core or after `release()`; `shopBlocked`; `invalidArgument` for an argument the method refuses, + and then nothing is sent; `network`, `timeout`; `http(code:serverCode:)` for an answer outside `2xx`; + `decoding` for an answer that is not the method's; `cancelled` for a call `release()` ended. A `402`, + `403` or `404` here does not change the state of the SDK. Nothing is repeated: the app decides. The + `async` form of each method throws the same `Rees46.SdkError`; cancelling the task ends the call as + `cancelled`. + */ +@_spi(Bridge) +public protocol ReviewsAPI { + + /** + An NPS score: how ready the customer is to recommend the shop (`POST api/v3/polls/nps/reviews` on + `appDomain`). The question and the thanks come from `NpsCategory`: 0–6 — `detractor…`, 7–8 — + `passive…`, 9–10 — `promoter…`. + + - Parameters: + - rate: from 0 to 10. + - channel: the code of the channel in the shop's account; not empty. + - category: the code of the category — what is scored; not empty. + - orderId: the order scored, if one is. Another customer's order is `http(404)`; an order the + server does not know it drops, and keeps the score without it. `nil` or empty is not sent. + - comment: `nil` or empty is not sent. A score sent again the same day without one keeps the + earlier comment if the score is the same, and clears it if the score changed. + - label: a mark that groups the reviews in the report; `nil` or empty is not sent. + + The same channel, category, order and label scored again the same day (in the shop's time zone) + makes no new review: the server updates the earlier one, and `PollReview.id` is its id. A score + with a comment — the answer to the question after the score — goes to the latest review of the + last 90 days with the same channel, category, order, label and score and no comment, if there is + one, rather than making another. `http(400)` + is a score the server refused, `http(404)` a shop, customer, channel or category it does not know, + `http(429)` more than 30 scores a minute from the device. + */ + func createNps( + rate: Int, channel: String, category: String, orderId: String?, comment: String?, label: String?, + completion: @escaping (Result) -> Void + ) + + /// `createNps(rate:channel:category:orderId:comment:label:completion:)` for `async` code. + func createNps( + rate: Int, channel: String, category: String, orderId: String?, comment: String?, label: String? + ) async throws -> PollReview + + /** + A CSAT score: whether the customer is pleased with one interaction — the delivery, the support, the + checkout (`POST api/v3/polls/csat/reviews` on `appDomain`). `rate` is from 1 to 5; `campaign` — the + code of the campaign, what is scored — not empty. The rest as in `createNps`. The question and the + thanks come from `CsatCampaign`: 1–2 — `dissatisfied…`, 3 — `neutral…`, 4–5 — `satisfied…`. + */ + func createCsat( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String?, + completion: @escaping (Result) -> Void + ) + + /// `createCsat(rate:channel:campaign:orderId:comment:label:completion:)` for `async` code. + func createCsat( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String? + ) async throws -> PollReview + + /** + A CES score: how much effort the task took the customer (`POST api/v3/polls/ces/reviews` on + `appDomain`). As `createCsat`, but `rate` is from 1 to 7. The question and the thanks come from + `CesCampaign`: 1–3 — `difficult…`, 4–5 — `neutral…`, 6–7 — `easy…`. + */ + func createCes( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String?, + completion: @escaping (Result) -> Void + ) + + /// `createCes(rate:channel:campaign:orderId:comment:label:completion:)` for `async` code. + func createCes( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String? + ) async throws -> PollReview + + /// The NPS categories of the shop's account (`GET api/v3/polls/nps/categories` on `appDomain`); none + /// is an empty list. + func getNpsCategories(completion: @escaping (Result<[NpsCategory], Rees46.SdkError>) -> Void) + + /// `getNpsCategories(completion:)` for `async` code. + func getNpsCategories() async throws -> [NpsCategory] + + /// The channels of the polls (`GET api/v3/polls/nps/channels` on `appDomain`): one list for NPS, CSAT + /// and CES, which the API gives on the path of NPS only. None is an empty list. + func getNpsChannels(completion: @escaping (Result<[PollChannel], Rees46.SdkError>) -> Void) + + /// `getNpsChannels(completion:)` for `async` code. + func getNpsChannels() async throws -> [PollChannel] + + /// The CSAT campaigns of the shop's account (`GET api/v3/polls/csat/campaigns` on `appDomain`); none + /// is an empty list. + func getCsatCampaigns(completion: @escaping (Result<[CsatCampaign], Rees46.SdkError>) -> Void) + + /// `getCsatCampaigns(completion:)` for `async` code. + func getCsatCampaigns() async throws -> [CsatCampaign] + + /// The CES campaigns of the shop's account (`GET api/v3/polls/ces/campaigns` on `appDomain`); none is + /// an empty list. + func getCesCampaigns(completion: @escaping (Result<[CesCampaign], Rees46.SdkError>) -> Void) + + /// `getCesCampaigns(completion:)` for `async` code. + func getCesCampaigns() async throws -> [CesCampaign] + + /** + The published reviews of a product and its rating, for the product's card (`GET reviews/product` on + `apiDomain`). The summary counts every published review; `limit` and `offset` page the list only, + newest first. Reviews on moderation and rejected ones are not here. + + - Parameters: + - itemId: the product; not empty. + - limit: from 1 to 100; `nil` is the server's 20. + - offset: not below 0; `nil` is 0. + + `http(403)` is a shop without the service of reviews, `http(404)` a product the server does not know. + */ + func getProductReviews( + itemId: String, limit: Int?, offset: Int?, + completion: @escaping (Result) -> Void + ) + + /// `getProductReviews(itemId:limit:offset:completion:)` for `async` code. + func getProductReviews(itemId: String, limit: Int?, offset: Int?) async throws -> ProductReviewsResponse + + /** + The reviews the customer of this device left in one order, whatever their moderation, say to show + a score next to a product in the history of orders (`GET reviews/client` on `apiDomain`). `orderId` + is not empty. No page; none is an empty list. + + `http(404)` is an order the server does not know or another customer's ("Order not found"), or a + customer it does not know ("User not found"): the method makes none. + */ + func getClientReviews(orderId: String, completion: @escaping (Result<[ClientReview], Rees46.SdkError>) -> Void) + + /// `getClientReviews(orderId:completion:)` for `async` code. + func getClientReviews(orderId: String) async throws -> [ClientReview] +} + +/// The calls without the arguments that may be left out. Each is another method than the protocol's, +/// with fewer arguments: a conformer that does not implement a requirement does not compile, instead of +/// calling itself here. +@_spi(Bridge) +extension ReviewsAPI { + + /// `createNps` without an order, a comment or a label. + public func createNps( + rate: Int, channel: String, category: String, + completion: @escaping (Result) -> Void + ) { + createNps(rate: rate, channel: channel, category: category, orderId: nil, comment: nil, label: nil, completion: completion) + } + + /// `createNps` without an order, a comment or a label, for `async` code. + public func createNps(rate: Int, channel: String, category: String) async throws -> PollReview { + try await createNps(rate: rate, channel: channel, category: category, orderId: nil, comment: nil, label: nil) + } + + /// `createCsat` without an order, a comment or a label. + public func createCsat( + rate: Int, channel: String, campaign: String, + completion: @escaping (Result) -> Void + ) { + createCsat(rate: rate, channel: channel, campaign: campaign, orderId: nil, comment: nil, label: nil, completion: completion) + } + + /// `createCsat` without an order, a comment or a label, for `async` code. + public func createCsat(rate: Int, channel: String, campaign: String) async throws -> PollReview { + try await createCsat(rate: rate, channel: channel, campaign: campaign, orderId: nil, comment: nil, label: nil) + } + + /// `createCes` without an order, a comment or a label. + public func createCes( + rate: Int, channel: String, campaign: String, + completion: @escaping (Result) -> Void + ) { + createCes(rate: rate, channel: channel, campaign: campaign, orderId: nil, comment: nil, label: nil, completion: completion) + } + + /// `createCes` without an order, a comment or a label, for `async` code. + public func createCes(rate: Int, channel: String, campaign: String) async throws -> PollReview { + try await createCes(rate: rate, channel: channel, campaign: campaign, orderId: nil, comment: nil, label: nil) + } + + /// `getProductReviews` with the server's page: the 20 newest. + public func getProductReviews( + itemId: String, + completion: @escaping (Result) -> Void + ) { + getProductReviews(itemId: itemId, limit: nil, offset: nil, completion: completion) + } + + /// `getProductReviews` with the server's page, for `async` code. + public func getProductReviews(itemId: String) async throws -> ProductReviewsResponse { + try await getProductReviews(itemId: itemId, limit: nil, offset: nil) + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The customer's feedback (`ReviewsAPI`): the polls on `appDomain`, the reviews of products on the + /// API host. On the new core only. + public var reviews: ReviewsAPI { + ReviewsAPIImpl(requests: NamespaceRequests(self)) + } +} diff --git a/REES46/Classes/Reviews/ReviewsAPIImpl.swift b/REES46/Classes/Reviews/ReviewsAPIImpl.swift new file mode 100644 index 00000000..3ad95a2c --- /dev/null +++ b/REES46/Classes/Reviews/ReviewsAPIImpl.swift @@ -0,0 +1,224 @@ +// +// ReviewsAPIImpl.swift +// REES46 +// + +import Foundation + +struct ReviewsAPIImpl: ReviewsAPI { + + let requests: NamespaceRequests + + // MARK: - Scores + + func createNps( + rate: Int, channel: String, category: String, orderId: String?, comment: String?, label: String?, + completion: @escaping (Result) -> Void + ) { + requests.call("reviews.createNps", completion: completion) { + try Self.scoreRequest(.nps, rate: rate, channel: channel, subject: category, orderId: orderId, comment: comment, label: label) + } + } + + func createNps( + rate: Int, channel: String, category: String, orderId: String?, comment: String?, label: String? + ) async throws -> PollReview { + try await requests.value("reviews.createNps") { + try Self.scoreRequest(.nps, rate: rate, channel: channel, subject: category, orderId: orderId, comment: comment, label: label) + } + } + + func createCsat( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String?, + completion: @escaping (Result) -> Void + ) { + requests.call("reviews.createCsat", completion: completion) { + try Self.scoreRequest(.csat, rate: rate, channel: channel, subject: campaign, orderId: orderId, comment: comment, label: label) + } + } + + func createCsat( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String? + ) async throws -> PollReview { + try await requests.value("reviews.createCsat") { + try Self.scoreRequest(.csat, rate: rate, channel: channel, subject: campaign, orderId: orderId, comment: comment, label: label) + } + } + + func createCes( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String?, + completion: @escaping (Result) -> Void + ) { + requests.call("reviews.createCes", completion: completion) { + try Self.scoreRequest(.ces, rate: rate, channel: channel, subject: campaign, orderId: orderId, comment: comment, label: label) + } + } + + func createCes( + rate: Int, channel: String, campaign: String, orderId: String?, comment: String?, label: String? + ) async throws -> PollReview { + try await requests.value("reviews.createCes") { + try Self.scoreRequest(.ces, rate: rate, channel: channel, subject: campaign, orderId: orderId, comment: comment, label: label) + } + } + + // MARK: - Dictionaries + + func getNpsCategories(completion: @escaping (Result<[NpsCategory], Rees46.SdkError>) -> Void) { + requests.call("reviews.getNpsCategories", completion: completion) { Self.npsCategoriesRequest } + } + + func getNpsCategories() async throws -> [NpsCategory] { + try await requests.value("reviews.getNpsCategories") { Self.npsCategoriesRequest } + } + + func getNpsChannels(completion: @escaping (Result<[PollChannel], Rees46.SdkError>) -> Void) { + requests.call("reviews.getNpsChannels", completion: completion) { Self.npsChannelsRequest } + } + + func getNpsChannels() async throws -> [PollChannel] { + try await requests.value("reviews.getNpsChannels") { Self.npsChannelsRequest } + } + + func getCsatCampaigns(completion: @escaping (Result<[CsatCampaign], Rees46.SdkError>) -> Void) { + requests.call("reviews.getCsatCampaigns", completion: completion) { Self.csatCampaignsRequest } + } + + func getCsatCampaigns() async throws -> [CsatCampaign] { + try await requests.value("reviews.getCsatCampaigns") { Self.csatCampaignsRequest } + } + + func getCesCampaigns(completion: @escaping (Result<[CesCampaign], Rees46.SdkError>) -> Void) { + requests.call("reviews.getCesCampaigns", completion: completion) { Self.cesCampaignsRequest } + } + + func getCesCampaigns() async throws -> [CesCampaign] { + try await requests.value("reviews.getCesCampaigns") { Self.cesCampaignsRequest } + } + + // MARK: - Reviews of products + + func getProductReviews( + itemId: String, limit: Int?, offset: Int?, + completion: @escaping (Result) -> Void + ) { + requests.call("reviews.getProductReviews", completion: completion) { + try Self.productReviewsRequest(itemId: itemId, limit: limit, offset: offset) + } + } + + func getProductReviews(itemId: String, limit: Int?, offset: Int?) async throws -> ProductReviewsResponse { + try await requests.value("reviews.getProductReviews") { + try Self.productReviewsRequest(itemId: itemId, limit: limit, offset: offset) + } + } + + func getClientReviews(orderId: String, completion: @escaping (Result<[ClientReview], Rees46.SdkError>) -> Void) { + requests.call("reviews.getClientReviews", completion: completion) { try Self.clientReviewsRequest(orderId: orderId) } + } + + func getClientReviews(orderId: String) async throws -> [ClientReview] { + try await requests.value("reviews.getClientReviews") { try Self.clientReviewsRequest(orderId: orderId) } + } +} + +// MARK: - Requests + +extension ReviewsAPIImpl { + + /// A poll of API v3 and its scale. + enum Poll: String { + case nps, csat, ces + + var scale: ClosedRange { + switch self { + case .nps: return 0...10 + case .csat: return 1...5 + case .ces: return 1...7 + } + } + + /// The field of what is scored: a category of NPS, a campaign of CSAT and CES. + var subject: String { + self == .nps ? "category" : "campaign" + } + } + + /// `POST api/v3/polls//reviews` on `appDomain`: the score, the channel and what is scored; the + /// order, the comment and the label only when they are given and not empty. A score off the poll's + /// scale or an empty channel or subject is `invalidArgument`, and nothing is sent. The answer is + /// `payload.review.id`; one without it — an empty body too — is `decoding`. + static func scoreRequest( + _ poll: Poll, rate: Int, channel: String, subject: String, orderId: String?, comment: String?, label: String? + ) throws -> ApiRequest { + guard poll.scale.contains(rate) else { + throw Rees46.SdkError.invalidArgument("rate must be from \(poll.scale.lowerBound) to \(poll.scale.upperBound)") + } + try required(channel, "channel") + try required(subject, poll.subject) + var body: [String: Any] = ["rate": rate, "channel": channel, poll.subject: subject] + for (key, value) in [("order_id", orderId), ("comment", comment), ("label", label)] { + if let value = ApiArguments.given(value) { + body[key] = value + } + } + return ApiRequest(method: .post, path: "api/v3/polls/\(poll.rawValue)/reviews", body: body, host: .app) { data in + try JSONDecoder().decode(PollReviewAnswer.self, from: data).review + } + } + + static var npsCategoriesRequest: ApiRequest<[NpsCategory]> { + dictionaryRequest("api/v3/polls/nps/categories", NpsCategoriesAnswer.self) { $0.items } + } + + static var npsChannelsRequest: ApiRequest<[PollChannel]> { + dictionaryRequest("api/v3/polls/nps/channels", PollChannelsAnswer.self) { $0.items } + } + + static var csatCampaignsRequest: ApiRequest<[CsatCampaign]> { + dictionaryRequest("api/v3/polls/csat/campaigns", CsatCampaignsAnswer.self) { $0.items } + } + + static var cesCampaignsRequest: ApiRequest<[CesCampaign]> { + dictionaryRequest("api/v3/polls/ces/campaigns", CesCampaignsAnswer.self) { $0.items } + } + + /// `GET reviews/product` on the API host: `product`, and `limit` and `offset` when they are given. An + /// answer without a body is a product without reviews. + static func productReviewsRequest(itemId: String, limit: Int?, offset: Int?) throws -> ApiRequest { + try required(itemId, "itemId") + var query = ["product": itemId] + if let limit = limit { + guard (1...100).contains(limit) else { throw Rees46.SdkError.invalidArgument("limit must be from 1 to 100") } + query["limit"] = String(limit) + } + if let offset = offset { + guard offset >= 0 else { throw Rees46.SdkError.invalidArgument("offset must not be negative") } + query["offset"] = String(offset) + } + let none = ProductReviewsResponse(summary: ProductRatingSummary(count: 0), reviews: []) + return .get("reviews/product", query: query, answer: ProductReviewsAnswer.self, whenEmpty: none) { $0.response } + } + + /// `GET reviews/client` on the API host: `order`. An answer without a body is no review. + static func clientReviewsRequest(orderId: String) throws -> ApiRequest<[ClientReview]> { + try required(orderId, "orderId") + return .get("reviews/client", query: ["order": orderId], answer: ClientReviewsAnswer.self, whenEmpty: []) { $0.items } + } + + /// A `GET` of a dictionary of the polls on `appDomain`; an answer without a body is an empty one. + private static func dictionaryRequest( + _ path: String, _ answer: Answer.Type, _ items: @escaping (Answer) -> [Item] + ) -> ApiRequest<[Item]> { + var request = ApiRequest<[Item]>.get(path, answer: answer, whenEmpty: [], value: items) + request.host = .app + return request + } + + /// Throws `invalidArgument` for an empty or blank `value` of the argument `name`. + private static func required(_ value: String, _ name: String) throws { + if ApiArguments.isBlank(value) { + throw Rees46.SdkError.invalidArgument("\(name) must not be empty") + } + } +} diff --git a/REES46/Classes/Reviews/ReviewsAnswers.swift b/REES46/Classes/Reviews/ReviewsAnswers.swift new file mode 100644 index 00000000..a5af7bdb --- /dev/null +++ b/REES46/Classes/Reviews/ReviewsAnswers.swift @@ -0,0 +1,249 @@ +// +// ReviewsAnswers.swift +// REES46 +// +// The answers of `reviews` as the API gives them (`sdk/contract/reviews.md`, "Модели"), read leniently +// (`LenientDecoding`) into the namespace's models. A field the model can do without is empty when it is +// missing or does not fit; an element of a list without a field the model needs is left out; an answer +// without the object or the list the method reads is not the method's answer (`decoding`). +// + +import Foundation + +/// `{"payload": {"review": {"id": …}}}` of a score: the id of the review kept. +struct PollReviewAnswer: Decodable { + + let review: PollReview + + init(from decoder: Decoder) throws { + let review = try decoder.payload().object("review") + self.review = PollReview(id: try review.requiredInt("id")) + } +} + +/// `{"payload": {"categories": [...]}}`. +struct NpsCategoriesAnswer: Decodable { + + let items: [NpsCategory] + + init(from decoder: Decoder) throws { + items = try decoder.payload().list(Line.self, "categories").map(\.value) + } + + private struct Line: Decodable { + let value: NpsCategory + + init(from decoder: Decoder) throws { + let line = try decoder.container(keyedBy: AnswerKey.self) + value = NpsCategory( + code: try line.requiredString("code"), + name: try line.requiredString("name"), + detractorQuestion: line.lenientString("detractor_question"), + passiveQuestion: line.lenientString("passive_question"), + promoterQuestion: line.lenientString("promoter_question"), + detractorSuccess: line.lenientString("detractor_success"), + passiveSuccess: line.lenientString("passive_success"), + promoterSuccess: line.lenientString("promoter_success"), + buttonLabel: line.lenientString("button_label") + ) + } + } +} + +/// `{"payload": {"channels": [...]}}`. +struct PollChannelsAnswer: Decodable { + + let items: [PollChannel] + + init(from decoder: Decoder) throws { + items = try decoder.payload().list(Line.self, "channels").map(\.value) + } + + private struct Line: Decodable { + let value: PollChannel + + init(from decoder: Decoder) throws { + let line = try decoder.container(keyedBy: AnswerKey.self) + value = PollChannel(code: try line.requiredString("code"), name: try line.requiredString("name")) + } + } +} + +/// `{"payload": {"campaigns": [...]}}` of CSAT. +struct CsatCampaignsAnswer: Decodable { + + let items: [CsatCampaign] + + init(from decoder: Decoder) throws { + items = try decoder.payload().list(Line.self, "campaigns").map(\.value) + } + + private struct Line: Decodable { + let value: CsatCampaign + + init(from decoder: Decoder) throws { + let line = try decoder.container(keyedBy: AnswerKey.self) + value = CsatCampaign( + code: try line.requiredString("code"), + name: try line.requiredString("name"), + dissatisfiedQuestion: line.lenientString("dissatisfied_question"), + neutralQuestion: line.lenientString("neutral_question"), + satisfiedQuestion: line.lenientString("satisfied_question"), + dissatisfiedSuccess: line.lenientString("dissatisfied_success"), + neutralSuccess: line.lenientString("neutral_success"), + satisfiedSuccess: line.lenientString("satisfied_success"), + buttonLabel: line.lenientString("button_label") + ) + } + } +} + +/// `{"payload": {"campaigns": [...]}}` of CES. +struct CesCampaignsAnswer: Decodable { + + let items: [CesCampaign] + + init(from decoder: Decoder) throws { + items = try decoder.payload().list(Line.self, "campaigns").map(\.value) + } + + private struct Line: Decodable { + let value: CesCampaign + + init(from decoder: Decoder) throws { + let line = try decoder.container(keyedBy: AnswerKey.self) + value = CesCampaign( + code: try line.requiredString("code"), + name: try line.requiredString("name"), + difficultQuestion: line.lenientString("difficult_question"), + neutralQuestion: line.lenientString("neutral_question"), + easyQuestion: line.lenientString("easy_question"), + difficultSuccess: line.lenientString("difficult_success"), + neutralSuccess: line.lenientString("neutral_success"), + easySuccess: line.lenientString("easy_success"), + buttonLabel: line.lenientString("button_label") + ) + } + } +} + +/// `{"payload": {"summary": {...}, "reviews": [...]}}` of `reviews/product`. +struct ProductReviewsAnswer: Decodable { + + let response: ProductReviewsResponse + + init(from decoder: Decoder) throws { + let payload = try decoder.payload() + let summary = try payload.object("summary") + var ratings: [Int: Int] = [:] + // `{"1": 0, …, "5": 3}`: a key that is not a score or a count that is not a number is left out. + if let counts = try? summary.nestedContainer(keyedBy: AnswerKey.self, forKey: "ratings") { + for key in counts.allKeys { + if let score = Int(key.stringValue.trimmingCharacters(in: .whitespaces)), let count = counts.lenientInt(key) { + ratings[score] = count + } + } + } + response = ProductReviewsResponse( + summary: ProductRatingSummary( + count: try summary.requiredInt("count"), + averageRating: summary.lenientDouble("average_rating"), + ratings: ratings + ), + reviews: try payload.list(Line.self, "reviews").map(\.value) + ) + } + + private struct Line: Decodable { + let value: ProductReview + + init(from decoder: Decoder) throws { + let line = try decoder.container(keyedBy: AnswerKey.self) + value = ProductReview( + id: try line.requiredInt("id"), + rating: try line.requiredInt("rating"), + comment: line.lenientString("comment"), + author: line.lenientString("author"), + createdAt: try line.requiredString("created_at") + ) + } + } +} + +/// `{"payload": {"reviews": [...]}}` of `reviews/client`. +struct ClientReviewsAnswer: Decodable { + + let items: [ClientReview] + + init(from decoder: Decoder) throws { + items = try decoder.payload().list(Line.self, "reviews").map(\.value) + } + + private struct Line: Decodable { + let value: ClientReview + + init(from decoder: Decoder) throws { + let line = try decoder.container(keyedBy: AnswerKey.self) + value = ClientReview( + id: try line.requiredInt("id"), + itemId: try line.requiredString("product"), + orderId: try line.requiredString("order"), + rating: try line.requiredInt("rating"), + comment: line.lenientString("comment"), + state: line.lenientEnum(ReviewState.self, "state"), + createdAt: try line.requiredString("created_at") + ) + } + } +} + +// MARK: - Reading + +private extension Decoder { + + /// The `payload` object of the answer. + func payload() throws -> KeyedDecodingContainer { + try container(keyedBy: AnswerKey.self).object("payload") + } +} + +private extension KeyedDecodingContainer where Key == AnswerKey { + + /// The object at `key`; missing, `null` or not an object, the answer is not the method's. + func object(_ key: AnswerKey) throws -> KeyedDecodingContainer { + guard let object = try? nestedContainer(keyedBy: AnswerKey.self, forKey: key) else { + throw missing(key, "an object") + } + return object + } + + /// The list at `key` without the elements that do not read; missing, `null` or not a list, the + /// answer is not the method's. + func list(_ type: Element.Type, _ key: AnswerKey) throws -> [Element] { + guard let list = lenientList(type, key) else { + throw missing(key, "a list") + } + return list + } + + /// A string the model needs: missing, empty or not a scalar, the element does not read. + func requiredString(_ key: AnswerKey) throws -> String { + guard let value = lenientString(key) else { throw missing(key, "a string") } + return value + } + + /// An integer the model needs: missing or not one, the element does not read. + func requiredInt(_ key: AnswerKey) throws -> Int { + guard let value = lenientInt(key) else { throw missing(key, "an integer") } + return value + } + + private func missing(_ key: AnswerKey, _ what: String) -> DecodingError { + var path = codingPath + path.append(key) + return DecodingError.dataCorrupted(DecodingError.Context( + codingPath: path, + debugDescription: "\(key.stringValue) is not \(what)" + )) + } +} diff --git a/REES46/Classes/Reviews/ReviewsModels.swift b/REES46/Classes/Reviews/ReviewsModels.swift new file mode 100644 index 00000000..f2beaad3 --- /dev/null +++ b/REES46/Classes/Reviews/ReviewsModels.swift @@ -0,0 +1,223 @@ +// +// ReviewsModels.swift +// REES46 +// +// The models of `reviews` (`sdk/contract/reviews.md`, "Модели"): flat, so a bridge hands them over as +// they are. They are read from the answers by `ReviewsAnswers`; none is `Decodable` itself. +// + +import Foundation + +/// A score the server kept (`createNps`, `createCsat`, `createCes`). +@_spi(Bridge) +public struct PollReview: Equatable { + /// The id of the review saved, or of the one updated: a score sent again the same day for the same + /// channel, category or campaign, order and label replaces the earlier one. 64-bit, as the server's + /// ids of reviews. + public let id: Int + + public init(id: Int) { + self.id = id + } +} + +/// An NPS category of the shop's account: what is scored, with the question to ask and the thanks to +/// show for each group of scores — 0–6 detractor, 7–8 passive, 9–10 promoter. +@_spi(Bridge) +public struct NpsCategory: Equatable { + public let code: String + public let name: String + public let detractorQuestion: String? + public let passiveQuestion: String? + public let promoterQuestion: String? + public let detractorSuccess: String? + public let passiveSuccess: String? + public let promoterSuccess: String? + /// The text of the button after the score is sent. + public let buttonLabel: String? + + public init( + code: String, name: String, + detractorQuestion: String? = nil, passiveQuestion: String? = nil, promoterQuestion: String? = nil, + detractorSuccess: String? = nil, passiveSuccess: String? = nil, promoterSuccess: String? = nil, + buttonLabel: String? = nil + ) { + self.code = code + self.name = name + self.detractorQuestion = detractorQuestion + self.passiveQuestion = passiveQuestion + self.promoterQuestion = promoterQuestion + self.detractorSuccess = detractorSuccess + self.passiveSuccess = passiveSuccess + self.promoterSuccess = promoterSuccess + self.buttonLabel = buttonLabel + } +} + +/// A CSAT campaign of the shop's account, with the question and the thanks for each group of scores — +/// 1–2 dissatisfied, 3 neutral, 4–5 satisfied. +@_spi(Bridge) +public struct CsatCampaign: Equatable { + public let code: String + public let name: String + public let dissatisfiedQuestion: String? + public let neutralQuestion: String? + public let satisfiedQuestion: String? + public let dissatisfiedSuccess: String? + public let neutralSuccess: String? + public let satisfiedSuccess: String? + /// The text of the button after the score is sent. + public let buttonLabel: String? + + public init( + code: String, name: String, + dissatisfiedQuestion: String? = nil, neutralQuestion: String? = nil, satisfiedQuestion: String? = nil, + dissatisfiedSuccess: String? = nil, neutralSuccess: String? = nil, satisfiedSuccess: String? = nil, + buttonLabel: String? = nil + ) { + self.code = code + self.name = name + self.dissatisfiedQuestion = dissatisfiedQuestion + self.neutralQuestion = neutralQuestion + self.satisfiedQuestion = satisfiedQuestion + self.dissatisfiedSuccess = dissatisfiedSuccess + self.neutralSuccess = neutralSuccess + self.satisfiedSuccess = satisfiedSuccess + self.buttonLabel = buttonLabel + } +} + +/// A CES campaign of the shop's account, with the question and the thanks for each group of scores — +/// 1–3 difficult, 4–5 neutral, 6–7 easy. +@_spi(Bridge) +public struct CesCampaign: Equatable { + public let code: String + public let name: String + public let difficultQuestion: String? + public let neutralQuestion: String? + public let easyQuestion: String? + public let difficultSuccess: String? + public let neutralSuccess: String? + public let easySuccess: String? + /// The text of the button after the score is sent. + public let buttonLabel: String? + + public init( + code: String, name: String, + difficultQuestion: String? = nil, neutralQuestion: String? = nil, easyQuestion: String? = nil, + difficultSuccess: String? = nil, neutralSuccess: String? = nil, easySuccess: String? = nil, + buttonLabel: String? = nil + ) { + self.code = code + self.name = name + self.difficultQuestion = difficultQuestion + self.neutralQuestion = neutralQuestion + self.easyQuestion = easyQuestion + self.difficultSuccess = difficultSuccess + self.neutralSuccess = neutralSuccess + self.easySuccess = easySuccess + self.buttonLabel = buttonLabel + } +} + +/// A channel of the polls, one for NPS, CSAT and CES. +@_spi(Bridge) +public struct PollChannel: Equatable { + public let code: String + public let name: String + + public init(code: String, name: String) { + self.code = code + self.name = name + } +} + +/// The published reviews of a product and its rating (`getProductReviews`). +@_spi(Bridge) +public struct ProductReviewsResponse: Equatable { + /// Over every published review, whatever page the list is. + public let summary: ProductRatingSummary + /// The page asked for, newest first. + public let reviews: [ProductReview] + + public init(summary: ProductRatingSummary, reviews: [ProductReview]) { + self.summary = summary + self.reviews = reviews + } +} + +/// The rating of a product over its published reviews. +@_spi(Bridge) +public struct ProductRatingSummary: Equatable { + /// How many published reviews the product has. + public let count: Int + /// The mean score, rounded to 0.1 by the server; `nil` without reviews. + public let averageRating: Double? + /// How many reviews gave each score from 1 to 5. + public let ratings: [Int: Int] + + public init(count: Int, averageRating: Double? = nil, ratings: [Int: Int] = [:]) { + self.count = count + self.averageRating = averageRating + self.ratings = ratings + } +} + +/// A published review of a product; `id` is 64-bit, as the server's ids of reviews. +@_spi(Bridge) +public struct ProductReview: Equatable { + public let id: Int + /// From 1 to 5. + public let rating: Int + /// `nil` when the customer left a score only. + public let comment: String? + /// The author's name in the CDP. + public let author: String? + /// The date and time, ISO 8601, as the API gives it. + public let createdAt: String + + public init(id: Int, rating: Int, comment: String? = nil, author: String? = nil, createdAt: String) { + self.id = id + self.rating = rating + self.comment = comment + self.author = author + self.createdAt = createdAt + } +} + +/// A review the customer of this device left in an order (`getClientReviews`); `id` is 64-bit. +@_spi(Bridge) +public struct ClientReview: Equatable { + public let id: Int + /// The product reviewed. + public let itemId: String + public let orderId: String + /// From 1 to 5. + public let rating: Int + public let comment: String? + /// Where its moderation is; `nil` for a state this version of the SDK does not know. + public let state: ReviewState? + /// The date and time, ISO 8601, as the API gives it. + public let createdAt: String + + public init( + id: Int, itemId: String, orderId: String, rating: Int, + comment: String? = nil, state: ReviewState? = nil, createdAt: String + ) { + self.id = id + self.itemId = itemId + self.orderId = orderId + self.rating = rating + self.comment = comment + self.state = state + self.createdAt = createdAt + } +} + +/// The moderation of a review. A state the server adds later is read as `nil`, never as `decoding`. +@_spi(Bridge) +public enum ReviewState: String, Equatable { + case moderation + case published + case rejected +} diff --git a/REES46/Classes/Sdk/Facade/Rees46+Bridge.swift b/REES46/Classes/Sdk/Facade/Rees46+Bridge.swift index 3c6d4913..8bc7cbd8 100644 --- a/REES46/Classes/Sdk/Facade/Rees46+Bridge.swift +++ b/REES46/Classes/Sdk/Facade/Rees46+Bridge.swift @@ -110,6 +110,21 @@ extension Rees46 { @_spi(Bridge) extension PersonalizationSDK { + /// `deleteUserCredentials()` for `async` code (`deleteUserCredentials` of the contract): it returns, + /// as the synchronous one does, once the customer's data — the queue's files too — is wiped, and the + /// wipe holds no thread of the caller, the main one included. On either core. + /// + /// For the bridges only: beside the synchronous method an `async` one would take over every call of + /// that method an app makes from `async` code, which then would not compile without `await`. + public func deleteUserCredentials() async { + await withCheckedContinuation { (continuation: CheckedContinuation) in + DispatchQueue.global(qos: .userInitiated).async { + self.deleteUserCredentials() + continuation.resume() + } + } + } + /// Calls `listener` on the main thread with every new session id (`sid`) until the handle is /// cancelled, so a bridge tells its app instead of asking for `sessionId` on a timer. On the new /// core each `sid` an `/init` brings; on the old core the one `deleteUserCredentials()` makes. diff --git a/REES46/Classes/Sdk/Facade/Rees46.swift b/REES46/Classes/Sdk/Facade/Rees46.swift index bdcc1f93..93b402ba 100644 --- a/REES46/Classes/Sdk/Facade/Rees46.swift +++ b/REES46/Classes/Sdk/Facade/Rees46.swift @@ -113,6 +113,7 @@ public enum Rees46 { needReInitialization: config.needReInitialization, storageKey: config.storageKey, coreV2: config.coreV2, + appDomain: config.appDomain, deviceId: config.deviceId, segment: segment, completion: completion diff --git a/REES46/Classes/Sdk/Facade/Rees46Config.swift b/REES46/Classes/Sdk/Facade/Rees46Config.swift index fa4f0243..545af761 100644 --- a/REES46/Classes/Sdk/Facade/Rees46Config.swift +++ b/REES46/Classes/Sdk/Facade/Rees46Config.swift @@ -25,6 +25,13 @@ public struct Rees46Config { public let shopId: String /// API host the instance talks to (a region points here). public let apiDomain: String + /// The host of API v3, without a scheme: `app.rees46.ru`, unless the shop's cluster has its own; an + /// empty one is the default. The SDK's methods that call API v3 go there — the namespaces of the new + /// core, the bridges' (`Rees46.initializeBridge`); no method an app calls goes there yet. Popups v3 + /// and stories v3 keep their own settings of it (`popups.appHost`, `PersonalizationStories.apiV3Domain`). + public let appDomain: String + /// `appDomain` when none is given. + static let defaultAppDomain = "app.rees46.ru" /// Traffic stream label sent with every request. public let stream: String /// The device id (`did`) the app already keeps — say from another version of the SDK — for a shop @@ -73,6 +80,7 @@ public struct Rees46Config { public init( shopId: String, apiDomain: String = "api.rees46.ru", + appDomain: String = "app.rees46.ru", stream: String = "ios", deviceId: String? = nil, enableLogs: Bool = false, @@ -86,6 +94,7 @@ public struct Rees46Config { self.init( shopId: shopId, apiDomain: apiDomain, + appDomain: appDomain, stream: stream, deviceId: deviceId, enableLogs: enableLogs, @@ -103,6 +112,7 @@ public struct Rees46Config { init( shopId: String, apiDomain: String = "api.rees46.ru", + appDomain: String = Rees46Config.defaultAppDomain, stream: String = "ios", deviceId: String? = nil, enableLogs: Bool = false, @@ -127,6 +137,8 @@ public struct Rees46Config { self.needReInitialization = needReInitialization self.storageKey = storageKey self.coreV2 = coreV2 + let host = appDomain.trimmingCharacters(in: .whitespacesAndNewlines) + self.appDomain = host.isEmpty ? Self.defaultAppDomain : host } /// This configuration on the new core: what `Rees46.initializeBridge` makes of a bridge's one. @@ -148,6 +160,7 @@ public struct Rees46Config { && enableAutoPopupPresentation == other.enableAutoPopupPresentation && needReInitialization == other.needReInitialization && storageKey == other.storageKey + && appDomain == other.appDomain && coreV2 == other.coreV2 } } diff --git a/REES46/Classes/Sdk/Model/Search.struct.swift b/REES46/Classes/Sdk/Model/Search.struct.swift index e8367bf0..6a241949 100644 --- a/REES46/Classes/Sdk/Model/Search.struct.swift +++ b/REES46/Classes/Sdk/Model/Search.struct.swift @@ -5,12 +5,15 @@ struct Search: Codable { var landing: String var type: String var settings: Settings + /// `blank_mode`: `agent` when the shop turned the search agent on (`search.agentEnabled`). + var blankMode: String? init(json: [String: Any]) { enable = json["enabled"] as? Int ?? 0 landing = json["landing"] as? String ?? "" type = json["type"] as? String ?? "" settings = Settings(json: json["settings"] as? [String: Any] ?? [:]) + blankMode = json["blank_mode"] as? String } init() { diff --git a/REES46/Classes/Sdk/impl/SimplePersonalizationSDK+Push.swift b/REES46/Classes/Sdk/impl/SimplePersonalizationSDK+Push.swift index d4aa569b..7d40e37d 100644 --- a/REES46/Classes/Sdk/impl/SimplePersonalizationSDK+Push.swift +++ b/REES46/Classes/Sdk/impl/SimplePersonalizationSDK+Push.swift @@ -72,7 +72,7 @@ extension SimplePersonalizationSDK { let later: (Result, Rees46.SdkError?) -> Void = { result, error in DispatchQueue.global(qos: .utility).async { CurrentError.with(error) { completion(result) } } } - guard !Self.isBlank(code), !Self.isBlank(type) else { + guard !ApiArguments.isBlank(code), !ApiArguments.isBlank(type) else { let what = "\(event.path): the code and the type of the push must not be empty" logger.warning(LogCode.invalidArgument, what, ["reason": "empty"]) later(.failure(.legacy(.invalidArgument(what))), .invalidArgument(what)) @@ -85,30 +85,46 @@ extension SimplePersonalizationSDK { enqueuePushEvent(event, type: type, code: code, completion: completion) } + /// An event of `notifications.track…` (`sdk/contract/notifications.md`), its arguments checked by + /// the caller: through the queue, once per message in the process, a click storing the source — as + /// `receivePush` sends it, without a callback: the app knows of the event. `accepted` hears the + /// contract's result once: `nil` once the queue took the event, and for a repeat, which sends + /// nothing; otherwise why it was not taken — `notInitialized`, `shopBlocked`. + func queuePushEvent(_ event: Rees46.PushEvent, type: String, code: String, accepted: @escaping (Rees46.SdkError?) -> Void) { + guard PushCenter.reserve(event, code: code, shopId: shopId) else { + logger.debug(LogCode.pushReceived, "the push event was handled already in this launch", ["event": event.rawValue, "repeat": "true"]) + accepted(nil) + return + } + enqueuePushEvent(event, type: type, code: code, completion: nil, onAccepted: { accepted(nil) }, onRefused: { accepted($0) }) + } + /// The event into the shop's queue (`sdk/core/queue.md`), its message reserved by the caller /// (`PushCenter.reserve`): it counts as sent once the queue accepted it, and `onAccepted` runs /// then; a queue that does not take it — a released instance, a refused shop — frees it, so the - /// event may go when it comes again, and `notTaken` hears a released instance's. A click stores the - /// push as the source of the `/push` events of the next 48 hours, when its type is a source - /// (`TrackingSourceType`). + /// event may go when it comes again, `onRefused` hears why, and `notTaken` hears a released + /// instance's. A click stores the push as the source of the `/push` events of the next 48 hours, + /// when its type is a source (`TrackingSourceType`). private func enqueuePushEvent( _ event: Rees46.PushEvent, type: String, code: String, completion: ((Result) -> Void)?, notTaken: (() -> Void)? = nil, - onAccepted: @escaping () -> Void = {} + onAccepted: @escaping () -> Void = {}, + onRefused: ((Rees46.SdkError) -> Void)? = nil ) { if event == .clicked, let source = TrackingSourceType(rawValue: type) { sourceStore.store(type: source.rawValue, code: code) } let shopId = self.shopId let accepted: (Rees46.SdkError?) -> Void = { error in - guard error == nil else { + if let error = error { PushCenter.release(event, code: code, shopId: shopId) if error == .notInitialized { notTaken?() } + onRefused?(error) return } PushCenter.confirm(event, code: code, shopId: shopId) @@ -119,10 +135,6 @@ extension SimplePersonalizationSDK { } } - private static func isBlank(_ value: String) -> Bool { - value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - // MARK: - Callbacks /// The instance's own push callbacks: they win over the facade's, one by one; `nil` removes them. @@ -207,22 +219,26 @@ extension SimplePersonalizationSDK { request.identity = { [weak self] in self?.identity(ifCurrent: generation) } let logger = self.logger core.send(request) { response in + // A `2xx` whose body says it failed took no token: `decoding`, as the namespaces read such an + // answer (`sdk/contract/README.md`, "Ответы"), and the week stays free. + let saysError = ((try? response.result.get()) as? [String: Any])?["status"] as? String == "error" + let result: Result = saysError ? .failure(.legacy(.decoding)) : response.result.map { _ in () } + let error: Rees46.SdkError? = saysError ? .decoding : response.error let sent: Bool - if case .success = response.result { + if case .success = result { sent = true } else { sent = false } let joined = PushTokenWeek.finish(claim, sent: sent, at: clock.now()) - let result: Result = response.result.map { _ in () } - switch response.result { + switch result { case .success: logger.info(LogCode.pushTokenSent, "the push token was sent") - case .failure(let error): - logger.warning(LogCode.pushTokenFailed, "the push token was not sent", ["error": error.logKind]) + case .failure(let failure): + logger.warning(LogCode.pushTokenFailed, "the push token was not sent", ["error": failure.logKind]) } - completion(result, response.error) - joined.forEach { $0(result, response.error) } + completion(result, error) + joined.forEach { $0(result, error) } } } } diff --git a/REES46/Classes/Sdk/impl/SimplePersonalizationSDK.swift b/REES46/Classes/Sdk/impl/SimplePersonalizationSDK.swift index ced3ea3f..33b856fc 100644 --- a/REES46/Classes/Sdk/impl/SimplePersonalizationSDK.swift +++ b/REES46/Classes/Sdk/impl/SimplePersonalizationSDK.swift @@ -147,6 +147,8 @@ class SimplePersonalizationSDK: PersonalizationSDK { private var legacySession: URLSession? private let sessionLock = NSLock() var userInfo: InitResponse = InitResponse() + /// Whether the last `/init` answer of the new core turned the search agent on (`search.agentEnabled`). + let agentSearch = AgentSearchSwitch() /// This shop's requests: another shop's wait for its device id does not hold them. private let requestQueue: ShopSessionQueue @@ -227,6 +229,7 @@ class SimplePersonalizationSDK: PersonalizationSDK { needReInitialization: Bool = false, storageKey: String? = nil, coreV2: Bool = false, + appDomain: String = Rees46Config.defaultAppDomain, deviceId configuredDeviceId: String? = nil, segment broughtSegment: String? = nil, environment: CoreEnvironment? = nil, @@ -252,6 +255,7 @@ class SimplePersonalizationSDK: PersonalizationSDK { self.config = Rees46Config( shopId: shopId, apiDomain: apiDomain, + appDomain: appDomain, stream: stream, deviceId: configuredDeviceId, enableLogs: enableLogs, @@ -1070,37 +1074,35 @@ class SimplePersonalizationSDK: PersonalizationSDK { } } + /// `GET api/v3/cdp/users/probability-to-purchase` on `Rees46Config.appDomain`, on either core: the + /// API host's `predict/probability-to-purchase` answers `503`, its service is no longer deployed there + /// (question 42 of `sdk/questions.md`). The contacts of `params` are not sent: the server finds the + /// customer by the device id, which wins over any contact (question 44). The answer's `payload` is the + /// forecast `predict.getProbabilityToPurchase` reads; a customer the server does not know has an empty + /// `clientId`. Errors as before: any answer but a `2xx` is `invalidResponse`, one without a numeric + /// probability `decodeError`. func getProbabilityToPurchase( params: PurchasePredictParams, completion: @escaping (Result) -> Void ) { sessionQueue.addOperation { - let path = "predict/probability-to-purchase" - var queryParams: [String: String] = [ + let queryParams: [String: String] = [ "shop_id": self.shopId, "did": self.deviceId, "seance": self.userSeance, "sid": self.userSeance, "segment": self.segment ] - if let email = params.email, !email.isEmpty { - queryParams["email"] = email - } - if let phone = params.phone, !phone.isEmpty { - queryParams["phone"] = phone - } - if let telegramId = params.telegramId, !telegramId.isEmpty { - queryParams["telegram_id"] = telegramId - } - if let loyaltyId = params.loyaltyId, !loyaltyId.isEmpty { - queryParams["loyalty_id"] = loyaltyId - } - - self.getRequest(path: path, params: queryParams, timeout: ProbabilityToPurchaseNetworkConstants.requestTimeoutIntervalSeconds) { result in + self.sendGet( + path: PredictAPIImpl.probabilityPath, + params: queryParams, + timeout: ProbabilityToPurchaseNetworkConstants.requestTimeoutIntervalSeconds, + host: self.config.appDomain + ) { _, result in switch result { case let .success(json): - if let parsed = ProbabilityToPurchaseResponse(json: json) { - completion(.success(parsed)) + if let forecast = ProbabilityAnswer.forecast(in: json) { + completion(.success(ProbabilityToPurchaseResponse(forecast))) } else { completion(.failure(.decodeError)) } @@ -2112,7 +2114,7 @@ class SimplePersonalizationSDK: PersonalizationSDK { /// One GET of `path` with the call's own timeout, through the instance's core. Hands back the /// answer's HTTP status — nil when no answer came — and its decoded JSON. With `savesAnswerOf`, an /// `/init` that saves its answer: only while that init generation is the instance's, under the lock - /// `deleteUserCredentials` takes. + /// `deleteUserCredentials` takes. `host` is a host other than the API's (`CoreRequest.host`). func sendGet( path: String, params: [String: String], @@ -2120,6 +2122,7 @@ class SimplePersonalizationSDK: PersonalizationSDK { timeout: TimeInterval?, waitsForNetwork: Bool = true, forgetsSavedInit: Bool = true, + host: String? = nil, completion: @escaping (_ status: Int?, _ result: Result) -> Void ) { // The old core forgets the saved answer on every request of a forced re-initialization, as it @@ -2127,7 +2130,8 @@ class SimplePersonalizationSDK: PersonalizationSDK { if forgetsSavedInit && needReInitialization && !usesCoreV2 { removeSavedInitAnswer() } - let request = CoreRequest(method: .get, path: path, query: params, timeout: timeout, waitsForNetwork: waitsForNetwork) + var request = CoreRequest(method: .get, path: path, query: params, timeout: timeout, waitsForNetwork: waitsForNetwork) + request.host = host core.send(request) { response in if let generation = initGeneration, case .success = response.result { self.ifCurrentInit(generation) { @@ -2247,6 +2251,7 @@ extension SimplePersonalizationSDK: InitMachineDelegate { func initMachine(adopt response: InitResponse, fromServer: Bool) { userInfo = response + agentSearch.adopt(blankMode: response.search.blankMode) if !response.deviceId.isEmpty { deviceId = response.deviceId } diff --git a/REES46/Classes/Search/AgentSearchModels.swift b/REES46/Classes/Search/AgentSearchModels.swift new file mode 100644 index 00000000..73d2e63f --- /dev/null +++ b/REES46/Classes/Search/AgentSearchModels.swift @@ -0,0 +1,173 @@ +// +// AgentSearchModels.swift +// REES46 +// +// The models of the search agent, the AI search of `search` (`sdk/contract/search.md`): the dialog of +// the customer with the agent, its sessions, messages and the products the agent offers. +// + +import Foundation + +@_spi(Bridge) +extension Rees46 { + + /// The customer's dialog with the agent (`search.agentDialog`). + public struct AgentDialogResponse: Equatable { + /// The last 20 sessions, the latest first, without their messages; none is an empty list. + public let sessions: [AgentSession] + /// The session asked for, or the latest one, with its messages; `nil` while the customer has + /// none. + public let session: AgentSession? + } + + /// The agent's answer to a message (`search.agent`). + public struct AgentResponse: Equatable { + /// The session the message went to — a new one without a `sessionId` —, without its messages. + public let session: AgentSession + /// The agent's answer. + public let message: AgentMessage + } + + /// A session of the dialog; `id` is 64-bit, as the server's ids of sessions. + public struct AgentSession: Equatable { + public let id: Int + /// The start of the customer's first message. + public let title: String? + /// The time of the last message, ISO 8601 as the answer has it. + public let updatedAt: String? + /// Empty where the answer gives the session without them: in the list of sessions and in + /// `AgentResponse`. + public let messages: [AgentMessage] + } + + /// A message of the dialog; `id` is 64-bit, as the server's ids of messages. + public struct AgentMessage: Equatable { + public let id: Int? + public let role: AgentMessageRole? + public let content: String? + /// ISO 8601 as the answer has it. + public let createdAt: String? + /// The products the agent offered; empty for the customer's messages. + public let products: [AgentProduct] + } + + /// Who wrote a message. An open set: a role the server adds comes as it is. + public struct AgentMessageRole: RawRepresentable, Hashable { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + /// The customer. + public static let user = AgentMessageRole(rawValue: "user") + /// The agent. + public static let assistant = AgentMessageRole(rawValue: "assistant") + } + + /// A product the agent offered: not a `Product`, a short one of its own with why it fits. + /// + /// The server loads the products of the history anew on every `agentDialog`: one no longer in stock + /// is gone, a price is today's. + public struct AgentProduct: Equatable { + public let id: String + public let name: String? + /// In the customer's location when the server knows it. + public let price: Double? + /// `nil` when the product has none: the server's 0 too. + public let oldPrice: Double? + public let priceFormatted: String? + public let oldPriceFormatted: String? + public let picture: String? + /// With the attribution of the agent (`recommended_by=agent_search&recommended_code=`); + /// `nil` when the product has no absolute link. + public let url: String? + /// Why the product fits the request; empty when the agent gave no reason. + public let reason: String + } +} + +// MARK: - Answers + +extension Rees46.AgentDialogResponse: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + sessions = answer.models(Rees46.AgentSession.self, "sessions") ?? [] + session = answer.model(Rees46.AgentSession.self, "session") + } +} + +extension Rees46.AgentResponse: AnswerReadable { + + /// Without its session or the agent's message it is not the agent's answer (`decoding`). + init(answer: KeyedDecodingContainer) throws { + guard let session = answer.model(Rees46.AgentSession.self, "session"), + let message = answer.model(Rees46.AgentMessage.self, "message") + else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: answer.codingPath, debugDescription: "no session or message")) + } + self.session = session + self.message = message + } +} + +extension Rees46.AgentSession: AnswerReadable { + + /// A session without an id is left out: the dialog cannot go on in it. + init(answer: KeyedDecodingContainer) throws { + guard let id = answer.lenientInt("id") else { + throw DecodingError.keyNotFound(AnswerKey("id"), DecodingError.Context(codingPath: answer.codingPath, debugDescription: "no id")) + } + self.id = id + title = answer.lenientString("title") + updatedAt = answer.lenientString("updated_at") + messages = answer.models(Rees46.AgentMessage.self, "messages") ?? [] + } +} + +extension Rees46.AgentMessage: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + id = answer.lenientInt("id") + role = answer.lenientString("role").map(Rees46.AgentMessageRole.init(rawValue:)) + content = answer.lenientString("content") + createdAt = answer.lenientString("created_at") + products = answer.models(Rees46.AgentProduct.self, "products") ?? [] + } +} + +extension Rees46.AgentProduct: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + id = try answer.requiredString("id") + name = answer.lenientString("name") + price = answer.lenientDouble("price") + // No old price is 0.0 in the answer. + oldPrice = answer.lenientDouble("oldprice").flatMap { $0 > 0 ? $0 : nil } + priceFormatted = answer.lenientString("price_formatted") + oldPriceFormatted = answer.lenientString("oldprice_formatted") + picture = answer.lenientString("picture") + url = answer.lenientString("url") + reason = answer.lenientString("reason") ?? "" + } +} + +/// Whether the shop turned the search agent on: `search.blank_mode` of the instance's last `/init` +/// answer is `agent`. Written by the `/init` of the new core, read from any thread. +final class AgentSearchSwitch { + + private let lock = NSLock() + private var on = false + + var isOn: Bool { + lock.lock(); defer { lock.unlock() } + return on + } + + /// The `blank_mode` of an answer: any value but `agent`, and none, is the usual empty search. + func adopt(blankMode: String?) { + lock.lock() + on = blankMode == "agent" + lock.unlock() + } +} diff --git a/REES46/Classes/Search/SearchAPI.swift b/REES46/Classes/Search/SearchAPI.swift new file mode 100644 index 00000000..13c9c98e --- /dev/null +++ b/REES46/Classes/Search/SearchAPI.swift @@ -0,0 +1,171 @@ +// +// SearchAPI.swift +// REES46 +// +// The `search` namespace of the contract (`sdk/contract/search.md`). +// + +import Foundation + +/** + Search in the shop's catalog: what to show in an empty search field (`blank`), products and hints while + the customer types (`instant`), and the page of results with facets, sorting and pages (`full`). When + the shop turned the AI search agent on (`agentEnabled`), a dialog with the agent (`agentDialog`, + `agent`) takes the place of the empty search; the agent's requests go to `Rees46Config.appDomain`. + + The methods send no event: when the customer searched, the app calls `tracking.search` itself. A + product opened from the results counts for the search with the source `instantSearch` or `fullSearch` + and the query as its code. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + + Every `completion` is called once, on the main thread, with the value or the error: `notInitialized` on + the old core or after `release()`, `shopBlocked`, `invalidArgument` for an argument refused before + anything is sent, `network`, `timeout`, `http(code:serverCode:)`, `decoding`, `cancelled` for a call + `release()` ended. The `async` forms throw the same `Rees46.SdkError`, and cancelling the task ends the + call as `cancelled`. Nothing is repeated: the app decides. + */ +@_spi(Bridge) +public protocol SearchAPI { + + /// The empty search (`GET search/blank`): the customer's last queries, the products they viewed last + /// or popular ones, hints, popular categories, brands and links. + func blank(completion: @escaping (Result) -> Void) + + func blank() async throws -> Rees46.SearchBlankResponse + + /// The search while the customer types (`GET search`, `instant_search`). `query` is not empty. + /// `excludedMerchants` goes only with `locations`: the server looks for the merchants inside them, + /// and without any it finds no product. + func instant( + query: String, + locations: [String]?, + excludedMerchants: [String]?, + excludedBrands: [String]?, + completion: @escaping (Result) -> Void + ) + + func instant( + query: String, + locations: [String]?, + excludedMerchants: [String]?, + excludedBrands: [String]? + ) async throws -> Rees46.SearchInstantResponse + + /// The page of results (`GET search`, `full_search`). `query` is not empty. + func full( + query: String, + request: Rees46.SearchFullRequest, + completion: @escaping (Result) -> Void + ) + + func full(query: String, request: Rees46.SearchFullRequest) async throws -> Rees46.SearchFullResponse + + /// Whether the shop turned the search agent on: `search.blank_mode` of the instance's last `/init` + /// answer is `agent`. Then show the dialog with the agent instead of the empty search. Read at once + /// on any thread; `false` before any answer and on the old core. + var agentEnabled: Bool { get } + + /// The customer's dialog with the agent (`GET api/v3/storefront/search/agent` on `appDomain`): their + /// sessions and the messages of `sessionId`, or of the latest session. Call it when the agent's + /// window opens. `locations` — the customer's, else the profile's — go as one value joined by `,`. + /// `sessionId` is 64-bit, as the server's ids of sessions: Swift's `Int` on every supported device. + /// + /// The server's refusals are `http(code:serverCode:)`: `400` without a device id yet, `402` for + /// search not paid, `403` for an inactive shop, `404` for a session of another customer, `429` over + /// its limit, `503` for an agent that is not available or a customer in the control group of search + /// — show the empty search (`blank`) then. + func agentDialog( + sessionId: Int?, + locations: [String]?, + completion: @escaping (Result) -> Void + ) + + func agentDialog(sessionId: Int?, locations: [String]?) async throws -> Rees46.AgentDialogResponse + + /// Sends the customer's message to the agent and gives its answer + /// (`POST api/v3/storefront/search/agent` on `appDomain`), in `sessionId` or a new session. The + /// message is not empty and at most 500 characters: otherwise `invalidArgument`, and nothing is + /// sent. The agent may think for up to a minute: the request waits 60 seconds for the answer. + /// + /// For the views, carts and purchases of its products to count for the agent, the products' links + /// carry `recommended_by=agent_search&recommended_code=`. The errors are `agentDialog`'s. + func agent( + message: String, + sessionId: Int?, + locations: [String]?, + completion: @escaping (Result) -> Void + ) + + func agent(message: String, sessionId: Int?, locations: [String]?) async throws -> Rees46.AgentResponse +} + +/// The arguments by default: protocol requirements cannot carry them. +@_spi(Bridge) +extension SearchAPI { + + public func instant( + query: String, + locations: [String]? = nil, + excludedMerchants: [String]? = nil, + excludedBrands: [String]? = nil, + completion: @escaping (Result) -> Void + ) { + instant(query: query, locations: locations, excludedMerchants: excludedMerchants, excludedBrands: excludedBrands, completion: completion) + } + + public func instant( + query: String, + locations: [String]? = nil, + excludedMerchants: [String]? = nil, + excludedBrands: [String]? = nil + ) async throws -> Rees46.SearchInstantResponse { + try await instant(query: query, locations: locations, excludedMerchants: excludedMerchants, excludedBrands: excludedBrands) + } + + /// The first page of results without filters. + public func full(query: String, completion: @escaping (Result) -> Void) { + full(query: query, request: Rees46.SearchFullRequest(), completion: completion) + } + + /// The first page of results without filters. + public func full(query: String) async throws -> Rees46.SearchFullResponse { + try await full(query: query, request: Rees46.SearchFullRequest()) + } + + public func agentDialog( + sessionId: Int? = nil, + locations: [String]? = nil, + completion: @escaping (Result) -> Void + ) { + agentDialog(sessionId: sessionId, locations: locations, completion: completion) + } + + public func agentDialog(sessionId: Int? = nil, locations: [String]? = nil) async throws -> Rees46.AgentDialogResponse { + try await agentDialog(sessionId: sessionId, locations: locations) + } + + public func agent( + message: String, + sessionId: Int? = nil, + locations: [String]? = nil, + completion: @escaping (Result) -> Void + ) { + agent(message: message, sessionId: sessionId, locations: locations, completion: completion) + } + + public func agent(message: String, sessionId: Int? = nil, locations: [String]? = nil) async throws -> Rees46.AgentResponse { + try await agent(message: message, sessionId: sessionId, locations: locations) + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// Search in the shop's catalog (`SearchAPI`): on the new core only. + public var search: SearchAPI { + SearchAPIImpl(requests: NamespaceRequests(self), instance: self as? SimplePersonalizationSDK) + } +} diff --git a/REES46/Classes/Search/SearchAPIImpl.swift b/REES46/Classes/Search/SearchAPIImpl.swift new file mode 100644 index 00000000..a42b039d --- /dev/null +++ b/REES46/Classes/Search/SearchAPIImpl.swift @@ -0,0 +1,199 @@ +// +// SearchAPIImpl.swift +// REES46 +// + +import Foundation + +struct SearchAPIImpl: SearchAPI { + + let requests: NamespaceRequests + /// The instance whose `/init` says whether the agent is on. + weak var instance: SimplePersonalizationSDK? + + func blank(completion: @escaping (Result) -> Void) { + requests.call("search.blank", completion: completion) { Self.blankRequest } + } + + func blank() async throws -> Rees46.SearchBlankResponse { + try await requests.value("search.blank") { Self.blankRequest } + } + + func instant( + query: String, + locations: [String]?, + excludedMerchants: [String]?, + excludedBrands: [String]?, + completion: @escaping (Result) -> Void + ) { + requests.call("search.instant", completion: completion) { + try Self.instantRequest(query: query, locations: locations, excludedMerchants: excludedMerchants, excludedBrands: excludedBrands) + } + } + + func instant( + query: String, + locations: [String]?, + excludedMerchants: [String]?, + excludedBrands: [String]? + ) async throws -> Rees46.SearchInstantResponse { + try await requests.value("search.instant") { + try Self.instantRequest(query: query, locations: locations, excludedMerchants: excludedMerchants, excludedBrands: excludedBrands) + } + } + + func full( + query: String, + request: Rees46.SearchFullRequest, + completion: @escaping (Result) -> Void + ) { + requests.call("search.full", completion: completion) { try Self.fullRequest(query: query, request) } + } + + func full(query: String, request: Rees46.SearchFullRequest) async throws -> Rees46.SearchFullResponse { + try await requests.value("search.full") { try Self.fullRequest(query: query, request) } + } + + var agentEnabled: Bool { + guard let instance = instance, instance.core is CoreV2 else { return false } + return instance.agentSearch.isOn + } + + func agentDialog( + sessionId: Int?, + locations: [String]?, + completion: @escaping (Result) -> Void + ) { + requests.call("search.agentDialog", completion: completion) { Self.agentDialogRequest(sessionId: sessionId, locations: locations) } + } + + func agentDialog(sessionId: Int?, locations: [String]?) async throws -> Rees46.AgentDialogResponse { + try await requests.value("search.agentDialog") { Self.agentDialogRequest(sessionId: sessionId, locations: locations) } + } + + func agent( + message: String, + sessionId: Int?, + locations: [String]?, + completion: @escaping (Result) -> Void + ) { + requests.call("search.agent", completion: completion) { + try Self.agentRequest(message: message, sessionId: sessionId, locations: locations) + } + } + + func agent(message: String, sessionId: Int?, locations: [String]?) async throws -> Rees46.AgentResponse { + try await requests.value("search.agent") { + try Self.agentRequest(message: message, sessionId: sessionId, locations: locations) + } + } + + // MARK: - Requests + + /// `GET search/blank` with the common fields alone. An answer without a body, or an empty list — the + /// server's empty object (PHP) —, has nothing to show. + static var blankRequest: ApiRequest { + ApiRequest(method: .get, path: "search/blank") { body in + if body.isEmpty || ((try? JSONSerialization.jsonObject(with: body)) as? [Any])?.isEmpty == true { + return try Readable.read(Data("{}".utf8)) + } + return try Readable.read(body) + } + } + + static func instantRequest( + query: String, + locations: [String]?, + excludedMerchants: [String]?, + excludedBrands: [String]? + ) throws -> ApiRequest { + let text = try CatalogQuery.identifier(query, "query") + var fields = CatalogQuery(["type": "instant_search", "search_query": text]) + fields.set("locations", list: locations) + fields.set("excluded_merchants", list: merchantsToExclude(excludedMerchants, locations: locations)) + fields.set("excluded_brands", list: excludedBrands) + return ApiRequest(method: .get, path: "search", query: fields.fields) { body in + try Readable.read(body) + } + } + + /// The direction goes as `order`, the page as `page`: the names of the documentation, which the + /// server reads beside `sort_dir` and `offset`. + static func fullRequest(query: String, _ request: Rees46.SearchFullRequest) throws -> ApiRequest { + let text = try CatalogQuery.identifier(query, "query") + var fields = CatalogQuery(["type": "full_search", "search_query": text]) + try CatalogQuery.positive(request.limit, "limit") + try CatalogQuery.positive(request.page, "page") + try CatalogQuery.positive(request.categoryLimit, "categoryLimit") + try CatalogQuery.positive(request.brandLimit, "brandLimit") + try CatalogQuery.prices(request.priceMin, request.priceMax) + fields.set("categories", list: request.categoryIds) + fields.set("brands", list: request.brands) + fields.set("excluded_brands", list: request.excludedBrands) + fields.set("merchants", list: request.merchants) + fields.set("excluded_merchants", list: merchantsToExclude(request.excludedMerchants, locations: request.locations)) + fields.set("locations", list: request.locations) + fields.set("price_min", number: request.priceMin) + fields.set("price_max", number: request.priceMax) + fields.set("colors", list: request.colors) + fields.set("fashion_sizes", list: request.fashionSizes) + fields.set("exclude", list: request.excludedItemIds) + try fields.set("filters", filters: request.filters) + fields.set("sort_by", request.sortBy?.rawValue) + fields.set("order", request.sortDir?.rawValue) + fields.set("no_clarification", request.disableClarification ? "true" : nil) + fields.set("category_limit", int: request.categoryLimit) + fields.set("brand_limit", int: request.brandLimit) + fields.set("limit", int: request.limit) + fields.set("page", int: request.page) + return ApiRequest(method: .get, path: "search", query: fields.fields) { body in + try Readable.read(body) + } + } + + /// The path of the agent on the host of API v3. + static let agentPath = "api/v3/storefront/search/agent" + /// The server gives the agent up to 40 seconds and two more tries of its model: the read timeout of a + /// message (`sdk/contract/search.md`). The dialog has the common one. + static let agentTimeout: TimeInterval = 60 + /// The longest message the server takes. + static let agentMessageLimit = 500 + + /// `GET api/v3/storefront/search/agent` on `appDomain`. An answer without a body has no session. + static func agentDialogRequest(sessionId: Int?, locations: [String]?) -> ApiRequest { + var fields = CatalogQuery() + fields.set("session_id", int: sessionId) + fields.set("location", list: locations) + var request = ApiRequest(method: .get, path: agentPath, query: fields.fields) { body in + try Readable.read(body.isEmpty ? Data("{}".utf8) : body) + } + request.host = .app + return request + } + + /// `POST api/v3/storefront/search/agent` on `appDomain`, a JSON body, read timeout 60 seconds. The + /// message is counted in characters as the server counts them, by Unicode scalars. + static func agentRequest(message: String, sessionId: Int?, locations: [String]?) throws -> ApiRequest { + let text = try CatalogQuery.identifier(message, "message") + guard text.unicodeScalars.count <= agentMessageLimit else { + throw Rees46.SdkError.invalidArgument("message is longer than \(agentMessageLimit) characters") + } + var body: [String: Any] = ["message": text] + body["session_id"] = sessionId + if let locations = locations, !locations.isEmpty { + body["location"] = locations.joined(separator: ",") + } + var request = ApiRequest(method: .post, path: agentPath, body: body, timeout: agentTimeout) { body in + try Readable.read(body) + } + request.host = .app + return request + } + + /// The merchants to leave out, only with locations: the server looks for them inside the locations, + /// and without any the search finds no product. + private static func merchantsToExclude(_ merchants: [String]?, locations: [String]?) -> [String]? { + guard let locations = locations, !locations.isEmpty else { return nil } + return merchants + } +} diff --git a/REES46/Classes/Search/SearchModels.swift b/REES46/Classes/Search/SearchModels.swift new file mode 100644 index 00000000..9434bd4c --- /dev/null +++ b/REES46/Classes/Search/SearchModels.swift @@ -0,0 +1,241 @@ +// +// SearchModels.swift +// REES46 +// +// The models of the `search` namespace (`sdk/contract/search.md`). Nested in the facade, as the +// catalog's are: the released `SearchBlankResponse`, `Query` and `PopularItem` stay as the old methods +// return them. +// + +import Foundation + +@_spi(Bridge) +extension Rees46 { + + /// The filters, sorting and page of `search.full`. + /// + /// Lists go as one value joined by `,`, an empty one as none. `limit`, `page`, `categoryLimit` and + /// `brandLimit` start at 1, a price is not negative and `priceMin` not above `priceMax`: otherwise + /// the call is `invalidArgument` and sends nothing. + public struct SearchFullRequest: Equatable { + public var categoryIds: [String]? + public var brands: [String]? + public var excludedBrands: [String]? + /// For marketplaces. + public var merchants: [String]? + /// For marketplaces; sent only with `locations`: the server looks for the merchants inside them, + /// and without any it finds no product. + public var excludedMerchants: [String]? + public var locations: [String]? + public var priceMin: Double? + public var priceMax: Double? + public var colors: [String]? + public var fashionSizes: [String]? + /// Products to leave out: the ones in the cart, say. + public var excludedItemIds: [String]? + /// A parameter of the products → its values; sent as JSON. + public var filters: [String: [String]]? + public var sortBy: SortBy? + public var sortDir: SortDirection? + /// Turns the clarifying search off. + public var disableClarification: Bool + /// How many categories the facet has. + public var categoryLimit: Int? + /// How many brands the facet has; 1000 by default. + public var brandLimit: Int? + public var limit: Int? + public var page: Int? + + public init( + categoryIds: [String]? = nil, + brands: [String]? = nil, + excludedBrands: [String]? = nil, + merchants: [String]? = nil, + excludedMerchants: [String]? = nil, + locations: [String]? = nil, + priceMin: Double? = nil, + priceMax: Double? = nil, + colors: [String]? = nil, + fashionSizes: [String]? = nil, + excludedItemIds: [String]? = nil, + filters: [String: [String]]? = nil, + sortBy: SortBy? = nil, + sortDir: SortDirection? = nil, + disableClarification: Bool = false, + categoryLimit: Int? = nil, + brandLimit: Int? = nil, + limit: Int? = nil, + page: Int? = nil + ) { + self.categoryIds = categoryIds + self.brands = brands + self.excludedBrands = excludedBrands + self.merchants = merchants + self.excludedMerchants = excludedMerchants + self.locations = locations + self.priceMin = priceMin + self.priceMax = priceMax + self.colors = colors + self.fashionSizes = fashionSizes + self.excludedItemIds = excludedItemIds + self.filters = filters + self.sortBy = sortBy + self.sortDir = sortDir + self.disableClarification = disableClarification + self.categoryLimit = categoryLimit + self.brandLimit = brandLimit + self.limit = limit + self.page = page + } + } + + /// What an empty search field shows. + public struct SearchBlankResponse: Equatable { + /// The products the customer viewed last (`lastProducts`), or popular ones; none is an empty list. + public let products: [Product] + /// Whether `products` are the ones the customer viewed last; missing is `false`. + public let lastProducts: Bool + public let lastQueries: [Query]? + public let suggests: [Query]? + public let popularCategories: [PopularItem]? + public let popularBrands: [PopularItem]? + public let popularLinks: [PopularItem]? + } + + /// The products and hints while the customer types. + public struct SearchInstantResponse: Equatable { + /// The query after the layout and typos were fixed. + public let searchQuery: String? + public let searchQueryOriginal: String? + /// Whether the clarifying search worked. + public let clarification: Bool? + public let productsTotal: Int? + public let products: [Product] + public let categories: [ProductCategory]? + /// Hints of queries. + public let queries: [Query]? + public let locations: [Location]? + /// The page the shop opens for this query instead of results. + public let redirect: SearchRedirect? + } + + /// The page of results. + public struct SearchFullResponse: Equatable { + public let searchQuery: String? + public let searchQueryOriginal: String? + public let clarification: Bool? + public let productsTotal: Int? + public let products: [Product] + public let categories: [ProductCategory]? + public let brands: [Brand]? + public let locations: [Location]? + /// The name of a parameter → its facet. + public let filters: [String: SearchFilter]? + public let industrialFilters: IndustrialFilters? + public let priceRange: PriceRange? + public let priceRanges: [PriceInterval]? + public let priceMedian: Double? + } + + /// A hint or a past query. + public struct Query: Equatable { + public let name: String + /// The full search by it. + public let url: String? + /// Only in the hints of the instant search. + public let score: Double? + } + + /// A popular category, brand or link. + public struct PopularItem: Equatable { + public let name: String + public let url: String + } + + /// A query for which the shop opens a page instead of results (`search_query_redirects`). + public struct SearchRedirect: Equatable { + public let query: String? + /// `redirect_link`. + public let url: String? + /// `deep_link`. + public let deeplink: String? + } +} + +// MARK: - Answers + +extension Rees46.SearchBlankResponse: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + products = answer.models(Rees46.Product.self, "products") ?? [] + lastProducts = answer.lenientBool("last_products") ?? false + lastQueries = answer.models(Rees46.Query.self, "last_queries") + suggests = answer.models(Rees46.Query.self, "suggests") + popularCategories = answer.models(Rees46.PopularItem.self, "popular_categories") + popularBrands = answer.models(Rees46.PopularItem.self, "popular_brands") + popularLinks = answer.models(Rees46.PopularItem.self, "popular_links") + } +} + +extension Rees46.SearchInstantResponse: AnswerReadable { + + /// Without a list of products it is not the search's answer (`decoding`). + init(answer: KeyedDecodingContainer) throws { + products = try answer.requiredModels(Rees46.Product.self, "products") + searchQuery = answer.lenientString("search_query") + searchQueryOriginal = answer.lenientString("search_query_original") + clarification = answer.lenientBool("clarification") + productsTotal = answer.lenientInt("products_total") + categories = answer.models(Rees46.ProductCategory.self, "categories") + queries = answer.models(Rees46.Query.self, "queries") + locations = answer.models(Rees46.Location.self, "locations") + redirect = answer.model(Rees46.SearchRedirect.self, "search_query_redirects") + } +} + +extension Rees46.SearchFullResponse: AnswerReadable { + + /// Without a list of products it is not the search's answer (`decoding`). + init(answer: KeyedDecodingContainer) throws { + products = try answer.requiredModels(Rees46.Product.self, "products") + searchQuery = answer.lenientString("search_query") + searchQueryOriginal = answer.lenientString("search_query_original") + clarification = answer.lenientBool("clarification") + productsTotal = answer.lenientInt("products_total") + categories = answer.models(Rees46.ProductCategory.self, "categories") + brands = answer.models(Rees46.Brand.self, "brands") + locations = answer.models(Rees46.Location.self, "locations") + filters = answer.modelMap(Rees46.SearchFilter.self, "filters") + industrialFilters = answer.model(Rees46.IndustrialFilters.self, "industrial_filters") + priceRange = answer.model(Rees46.PriceRange.self, "price_range") + priceRanges = answer.models(Rees46.PriceInterval.self, "price_ranges") + priceMedian = answer.lenientDouble("price_median") + } +} + +extension Rees46.Query: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + name = try answer.requiredString("name") + url = answer.lenientString("url") + score = answer.lenientDouble("score") + } +} + +extension Rees46.PopularItem: AnswerReadable { + + /// An item without a name or a link is left out. + init(answer: KeyedDecodingContainer) throws { + name = try answer.requiredText("name") + url = try answer.requiredText("url") + } +} + +extension Rees46.SearchRedirect: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + query = answer.lenientString("query") + url = answer.lenientString("redirect_link") + deeplink = answer.lenientString("deep_link") + } +} diff --git a/REES46/Classes/Segments/SegmentsAPI.swift b/REES46/Classes/Segments/SegmentsAPI.swift new file mode 100644 index 00000000..86488420 --- /dev/null +++ b/REES46/Classes/Segments/SegmentsAPI.swift @@ -0,0 +1,187 @@ +// +// SegmentsAPI.swift +// REES46 +// +// The `segments` namespace of the contract (`sdk/contract/segments.md`). +// + +import Foundation + +/** + The customer's segments and the device's A/B group. The SDK adds the customer to the shop's static + segments and removes them; the server works out the dynamic ones, which the SDK only reads. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core `add`, `remove` and `get` end + as `notInitialized` and send nothing; `getAbGroup` is the device's on either. + + Every `completion` is called once, on the main thread, with the value or the error: `notInitialized` on + the old core or after `release()`, `shopBlocked`, `invalidArgument` — a `segmentId` not above 0, an + empty contact — before anything is sent, `network`, `timeout`, `http(code:serverCode:)`, `decoding`, + `cancelled` for a call `release()` ended. The `async` forms throw the same `Rees46.SdkError`, and + cancelling the task ends the call as `cancelled`. Nothing is repeated: the app decides. + */ +@_spi(Bridge) +public protocol SegmentsAPI { + + /// Adds the customer to a static segment (`POST segments/add`). With `email` or `phone` the server + /// acts on the contact's owner without moving the device to them, unlike `profile.set`. + func add(segmentId: Int, email: String?, phone: String?, completion: @escaping (Result) -> Void) + + func add(segmentId: Int, email: String?, phone: String?) async throws + + /// Removes the customer from a static segment (`POST segments/remove`); not being in it is no error. + func remove(segmentId: Int, email: String?, phone: String?, completion: @escaping (Result) -> Void) + + func remove(segmentId: Int, email: String?, phone: String?) async throws + + /// The segments the customer is in now, static and dynamic (`GET segments/get`); none is an empty + /// list. A device the server does not know is `http(404)`. + func get(completion: @escaping (Result<[Rees46.Segment], Rees46.SdkError>) -> Void) + + func get() async throws -> [Rees46.Segment] + + /// The device's A/B group, `"A"` or `"B"`: picked once, the same for every shop of the app, kept + /// across launches, `release()` and `deleteUserCredentials()`. It goes as `segment` in every + /// request. No network, no error. + func getAbGroup() -> String +} + +/// The arguments by default: protocol requirements cannot carry them. +@_spi(Bridge) +extension SegmentsAPI { + + public func add( + segmentId: Int, + email: String? = nil, + phone: String? = nil, + completion: @escaping (Result) -> Void + ) { + add(segmentId: segmentId, email: email, phone: phone, completion: completion) + } + + public func add(segmentId: Int, email: String? = nil, phone: String? = nil) async throws { + try await add(segmentId: segmentId, email: email, phone: phone) + } + + public func remove( + segmentId: Int, + email: String? = nil, + phone: String? = nil, + completion: @escaping (Result) -> Void + ) { + remove(segmentId: segmentId, email: email, phone: phone, completion: completion) + } + + public func remove(segmentId: Int, email: String? = nil, phone: String? = nil) async throws { + try await remove(segmentId: segmentId, email: email, phone: phone) + } +} + +@_spi(Bridge) +extension Rees46 { + + /// A segment the customer is in. + public struct Segment: Equatable { + public let id: Int + /// `dynamic`, `static`, `less_often`, `rfm`, `rfm3`, `unknown`: an open set, a new type the + /// server adds comes as it is. + public let type: String? + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The customer's segments and the device's A/B group (`SegmentsAPI`): the requests on the new core + /// only. + public var segments: SegmentsAPI { + SegmentsAPIImpl(requests: NamespaceRequests(self), abGroup: segment, popups: self as? SimplePersonalizationSDK) + } +} + +struct SegmentsAPIImpl: SegmentsAPI { + + let requests: NamespaceRequests + /// The device's A/B group: it does not change. + let abGroup: String + /// The instance whose popups v3 hear that the segments changed. + weak var popups: SimplePersonalizationSDK? + + func add(segmentId: Int, email: String?, phone: String?, completion: @escaping (Result) -> Void) { + requests.call("segments.add", completion: completion) { + try changing(Self.changeRequest("segments/add", segmentId: segmentId, email: email, phone: phone), "add") + } + } + + func add(segmentId: Int, email: String?, phone: String?) async throws { + try await requests.value("segments.add") { + try changing(Self.changeRequest("segments/add", segmentId: segmentId, email: email, phone: phone), "add") + } + } + + func remove(segmentId: Int, email: String?, phone: String?, completion: @escaping (Result) -> Void) { + requests.call("segments.remove", completion: completion) { + try changing(Self.changeRequest("segments/remove", segmentId: segmentId, email: email, phone: phone), "remove") + } + } + + func remove(segmentId: Int, email: String?, phone: String?) async throws { + try await requests.value("segments.remove") { + try changing(Self.changeRequest("segments/remove", segmentId: segmentId, email: email, phone: phone), "remove") + } + } + + func get(completion: @escaping (Result<[Rees46.Segment], Rees46.SdkError>) -> Void) { + requests.call("segments.get", completion: completion) { Self.listRequest } + } + + func get() async throws -> [Rees46.Segment] { + try await requests.value("segments.get") { Self.listRequest } + } + + func getAbGroup() -> String { + abGroup + } + + /// `request` once it is on its way: popups v3 load their list anew for segments new in the session, + /// as for the old `addToSegment` and `removeFromSegment`. + private func changing(_ request: ApiRequest, _ action: String) -> ApiRequest { + popups?.popupsV3.contextChanged("segment", signature: action + ClientBody.signature(request.body)) + return request + } + + // MARK: - Requests + + /// A request of `path` for the segment: `segment_id` a number, as the API has it. + static func changeRequest(_ path: String, segmentId: Int, email: String?, phone: String?) throws -> ApiRequest { + guard segmentId > 0 else { + throw Rees46.SdkError.invalidArgument("segmentId must be above 0") + } + var body = ClientBody(["segment_id": segmentId]) + try body.identifier("email", email, "email") + try body.identifier("phone", phone, "phone") + return ApiRequest(method: .post, path: path, body: body.fields) { _ in () } + } + + /// `GET segments/get` — the server answers no `POST` there —: a list at the top of the answer; an + /// answer without a body is none. An answer that is not a list is `decoding`. + static var listRequest: ApiRequest<[Rees46.Segment]> { + ApiRequest(method: .get, path: "segments/get") { body in + guard !body.isEmpty else { return [] } + return try Readable.readList(body) + } + } +} + +extension Rees46.Segment: AnswerReadable { + + /// A segment without an id is left out. + init(answer: KeyedDecodingContainer) throws { + guard let id = answer.lenientInt("id") else { + throw DecodingError.keyNotFound(AnswerKey("id"), DecodingError.Context(codingPath: answer.codingPath, debugDescription: "no id")) + } + self.id = id + type = answer.lenientString("type") + } +} diff --git a/REES46/Classes/Sliders/SlidersAPI.swift b/REES46/Classes/Sliders/SlidersAPI.swift new file mode 100644 index 00000000..08d9e041 --- /dev/null +++ b/REES46/Classes/Sliders/SlidersAPI.swift @@ -0,0 +1,95 @@ +// +// SlidersAPI.swift +// REES46 +// +// The `sliders` namespace of the contract (`sdk/contract/sliders.md`). +// + +import Foundation + +/** + Banner sliders: the banners of a slider of the shop's account, for a carousel the app draws. A banner + shown or tapped is an event of `tracking`: `bannerView(bannerId:code:)` and + `bannerClick(bannerId:code:)`, with the banner's `id` and `code`. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + */ +@_spi(Bridge) +public protocol SlidersAPI { + + /** + The banners of the slider `code` for the customer of this device (`GET slider`), chosen by the + account's settings: the time they show, segments and locations. `tags` narrows them to the + account's tags; `locationId` is the customer's location (its `external_id`) — a banner for some + locations is not given without it. A slider without banners is one with an empty list. + + `completion` is called once, on the main thread, with the slider or the error: `invalidArgument` + for an empty `code`, or a tag that is empty or has a comma — the tags go joined by commas —, + nothing sent; `notInitialized` on the old core or after `release()`, `shopBlocked`, `network`, + `timeout`, `http(code:serverCode:)` — `404` for an unknown or inactive slider, `402` for a shop + without the service, `403` for an unknown or disabled shop —, `decoding` for an answer that is not + a slider, `cancelled` for a call `release()` ended. Nothing is repeated: the app decides. + */ + func get(code: String, tags: [String]?, locationId: String?, completion: @escaping (Result) -> Void) + + /// `get(code:tags:locationId:completion:)` for `async` code: throws the `Rees46.SdkError`; cancelling + /// the task ends the call as `cancelled`. + func get(code: String, tags: [String]?, locationId: String?) async throws -> Slider +} + +/// The default arguments of `SlidersAPI`: a requirement of a protocol cannot have them. +@_spi(Bridge) +extension SlidersAPI { + + public func get( + code: String, + tags: [String]? = nil, + locationId: String? = nil, + completion: @escaping (Result) -> Void + ) { + get(code: code, tags: tags, locationId: locationId, completion: completion) + } + + public func get(code: String, tags: [String]? = nil, locationId: String? = nil) async throws -> Slider { + try await get(code: code, tags: tags, locationId: locationId) + } +} + +/// A slider and its banners. +@_spi(Bridge) +public struct Slider { + public let code: String + /// The width of the block, in pixels. + public let width: Int + /// The height of the block, in pixels. + public let height: Int + public let banners: [SliderBanner] +} + +/// A banner of a slider. +@_spi(Bridge) +public struct SliderBanner { + /// The banner's id (`banner_id`) for `tracking.bannerView` and `bannerClick`. + public let id: String + /// The slider's code (`recommended_code`), the same for every banner of it: the `code` of the + /// banner's events. + public let code: String + public let imageUrl: String? + /// The landing page. + public let url: String? + public let deeplinkIos: String? + public let deeplinkAndroid: String? + /// The banner's own markup. + public let html: String? +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// Banner sliders (`SlidersAPI`): on the new core only. + public var sliders: SlidersAPI { + SlidersAPIImpl(requests: NamespaceRequests(self)) + } +} diff --git a/REES46/Classes/Sliders/SlidersAPIImpl.swift b/REES46/Classes/Sliders/SlidersAPIImpl.swift new file mode 100644 index 00000000..006f7d7b --- /dev/null +++ b/REES46/Classes/Sliders/SlidersAPIImpl.swift @@ -0,0 +1,93 @@ +// +// SlidersAPIImpl.swift +// REES46 +// + +import Foundation + +struct SlidersAPIImpl: SlidersAPI { + + let requests: NamespaceRequests + + func get(code: String, tags: [String]?, locationId: String?, completion: @escaping (Result) -> Void) { + requests.call("sliders.get", completion: completion) { try Self.getRequest(code: code, tags: tags, locationId: locationId) } + } + + func get(code: String, tags: [String]?, locationId: String?) async throws -> Slider { + try await requests.value("sliders.get") { try Self.getRequest(code: code, tags: tags, locationId: locationId) } + } + + /// `GET slider` for the customer of the device id: the tags joined by commas, the location as + /// `location`. No contacts: the device id is the customer, a contact goes to it through `profile`. + static func getRequest(code: String, tags: [String]?, locationId: String?) throws -> ApiRequest { + guard !ApiArguments.isBlank(code) else { + throw Rees46.SdkError.invalidArgument("the code of the slider must not be empty") + } + if tags?.contains(where: { ApiArguments.isBlank($0) || $0.contains(",") }) == true { + throw Rees46.SdkError.invalidArgument("a tag must not be empty or have a comma") + } + var query = ["code": code] + if let tags = tags, !tags.isEmpty { + query["tags"] = tags.joined(separator: ",") + } + if let location = locationId, !ApiArguments.isBlank(location) { + query["location"] = location + } + return .get("slider", query: query, answer: SliderAnswer.self) { $0.slider } + } +} + +/// `{"status": "success", "payload": {"properties": {"code", "width", "height"}, "slides": [...]}}`: the +/// banners are `payload.slides`. A banner without a `banner_id` cannot be tracked and is left out; one +/// without a `recommended_code` takes the slider's. `content_type` and `content` are the server's own. +/// Without `payload` it is not a slider (`decoding`). +struct SliderAnswer: Decodable { + + let slider: Slider + + init(from decoder: Decoder) throws { + let root = try decoder.container(keyedBy: AnswerKey.self) + guard let payload = try? root.nestedContainer(keyedBy: AnswerKey.self, forKey: "payload") else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "no payload")) + } + let properties = try? payload.nestedContainer(keyedBy: AnswerKey.self, forKey: "properties") + let code = properties?.lenientString("code") ?? "" + slider = Slider( + code: code, + width: properties?.lenientInt("width") ?? 0, + height: properties?.lenientInt("height") ?? 0, + banners: (payload.lenientList(BannerAnswer.self, "slides") ?? []).map { $0.banner(of: code) } + ) + } + + private struct BannerAnswer: Decodable { + let id: String + let code: String? + let imageUrl: String? + let url: String? + let deeplinkIos: String? + let deeplinkAndroid: String? + let html: String? + + init(from decoder: Decoder) throws { + let item = try decoder.container(keyedBy: AnswerKey.self) + guard let id = item.lenientString("banner_id") else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "no banner_id")) + } + self.id = id + code = item.lenientString("recommended_code") + imageUrl = item.lenientString("image_url") + url = item.lenientString("url") + deeplinkIos = item.lenientString("deeplink_ios") + deeplinkAndroid = item.lenientString("deeplink_android") + html = item.lenientString("html") + } + + func banner(of slider: String) -> SliderBanner { + SliderBanner( + id: id, code: code ?? slider, imageUrl: imageUrl, url: url, + deeplinkIos: deeplinkIos, deeplinkAndroid: deeplinkAndroid, html: html + ) + } + } +} diff --git a/REES46/Classes/Stories/API/StoriesAPI.swift b/REES46/Classes/Stories/API/StoriesAPI.swift new file mode 100644 index 00000000..12af7242 --- /dev/null +++ b/REES46/Classes/Stories/API/StoriesAPI.swift @@ -0,0 +1,47 @@ +// +// StoriesAPI.swift +// REES46 +// +// The `stories` namespace of the contract (`sdk/contract/stories.md`). +// + +import Foundation + +/** + The data of a stories block, for an app or a bridge that draws the stories itself. The views and the + clicks of the slides are events of `tracking` (`storyView`, `storyClick`). + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + */ +@_spi(Bridge) +public protocol StoriesAPI { + + /** + The block `code` of the shop's account (`GET stories/{code}`): its stories, their slides and the + elements of the slides. A block without stories, or one on pause, is a `StoriesBlock` with no + stories, not an error. The request goes once the device is known to the server. + + `completion` is called once, on the main thread, with the block or the error: `invalidArgument` + for an empty `code`, nothing sent; `notInitialized` on the old core or after `release()`, + `shopBlocked`, `network`, `timeout`, `http(code:serverCode:)` — `404` for an unknown block, `402` + for a shop without the stories service, `400` for a device the server does not know —, `decoding` + for an answer that is not a JSON object, `cancelled` for a call `release()` ended. Nothing is + repeated: the app decides. + */ + func get(code: String, completion: @escaping (Result) -> Void) + + /// `get(code:completion:)` for `async` code: throws the `Rees46.SdkError`; cancelling the task ends + /// the call as `cancelled`. + func get(code: String) async throws -> StoriesBlock +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The data of stories blocks (`StoriesAPI`): on the new core only. + public var stories: StoriesAPI { + StoriesAPIImpl(requests: NamespaceRequests(self)) + } +} diff --git a/REES46/Classes/Stories/API/StoriesAPIImpl.swift b/REES46/Classes/Stories/API/StoriesAPIImpl.swift new file mode 100644 index 00000000..ce0321da --- /dev/null +++ b/REES46/Classes/Stories/API/StoriesAPIImpl.swift @@ -0,0 +1,198 @@ +// +// StoriesAPIImpl.swift +// REES46 +// + +import Foundation + +struct StoriesAPIImpl: StoriesAPI { + + let requests: NamespaceRequests + + func get(code: String, completion: @escaping (Result) -> Void) { + requests.call("stories.get", completion: completion) { try Self.getRequest(code: code) } + } + + func get(code: String) async throws -> StoriesBlock { + try await requests.value("stories.get") { try Self.getRequest(code: code) } + } + + /// `GET stories/{code}`, the code made safe for one segment of the path; the core adds the shop, + /// the device id and the rest of the common fields. An answer without a body is not a block. + static func getRequest(code: String) throws -> ApiRequest { + guard !ApiArguments.isBlank(code) else { + throw Rees46.SdkError.invalidArgument("the code of the stories block must not be empty") + } + guard let segment = code.addingPercentEncoding(withAllowedCharacters: pathSegment) else { + throw Rees46.SdkError.invalidArgument("the code of the stories block is not text") + } + return .get("stories/\(segment)", answer: StoriesAnswer.self) { $0.block } + } + + /// What one segment of a path may hold as it is: no `/`, `?`, `#` or `%`. + private static let pathSegment = CharacterSet.urlPathAllowed.subtracting(CharacterSet(charactersIn: "/?#%;")) +} + +// MARK: - The answer + +/// The answer of `GET stories/{code}` (`sdk/contract/stories.md`), read as leniently as the Flutter SDK +/// and the old view read it: numbers may come as strings, ids as numbers, a missing field is its +/// default; an element of a type the SDK does not draw — `header`, `poll`, an unknown one — is left +/// out. Anything but a JSON object is not a block (`decoding`). `settings` — the colours of the old view +/// — and the fields of API v3 are not read. +struct StoriesAnswer: Decodable { + + let block: StoriesBlock + + init(from decoder: Decoder) throws { + let root = try decoder.container(keyedBy: AnswerKey.self) + block = StoriesBlock( + id: root.lenientString("id") ?? "", + stories: (root.lenientList(StoryAnswer.self, "stories") ?? []).map(\.story) + ) + } + + private struct StoryAnswer: Decodable { + let story: Story + + init(from decoder: Decoder) throws { + let item = try decoder.container(keyedBy: AnswerKey.self) + story = Story( + id: item.lenientString("id") ?? "", + name: item.lenientString("name") ?? "", + avatar: item.lenientString("avatar") ?? "", + viewed: item.lenientBool("viewed") ?? false, + pinned: item.lenientBool("pinned") ?? false, + startPosition: item.lenientInt("start_position") ?? 0, + slides: (item.lenientList(SlideAnswer.self, "slides") ?? []).map(\.slide) + ) + } + } + + private struct SlideAnswer: Decodable { + let slide: StorySlide + + init(from decoder: Decoder) throws { + let item = try decoder.container(keyedBy: AnswerKey.self) + let seconds = item.lenientInt("duration") ?? 0 + let type: StorySlideType + switch item.lenientString("type") { + case "image": type = .image + case "video": type = .video + // A slide of products: the answer gives it an empty type. + default: type = .product + } + slide = StorySlide( + id: item.lenientString("id") ?? "", + type: type, + background: item.lenientString("background") ?? "", + backgroundColor: item.lenientString("background_color") ?? "", + preview: item.lenientString("preview") ?? "", + duration: seconds > 0 ? seconds : StorySlide.defaultDuration, + elements: (item.lenientList(ElementAnswer.self, "elements") ?? []).compactMap(\.element) + ) + } + } + + /// One element; `element` is `nil` for a type the SDK leaves out. + private struct ElementAnswer: Decodable { + let element: StoryElement? + + init(from decoder: Decoder) throws { + let item = try decoder.container(keyedBy: AnswerKey.self) + switch item.lenientString("type") { + case "button": + element = .button(StoryButtonElement( + title: item.lenientString("title") ?? "", + link: item.lenientString("link") ?? "", + linkAndroid: item.lenientString("link_android") ?? "", + linkIos: item.lenientString("link_ios") ?? "", + background: item.lenientString("background") ?? "", + color: item.lenientString("color") ?? "", + textBold: item.lenientBool("text_bold") == true || item.lenientBool("bold") == true + )) + case "product": + element = .product(StoryProductElement( + title: item.lenientString("title") ?? "", + item: item.lenient(ProductAnswer.self, "item")?.product + )) + case "products": + let labels = try? item.nestedContainer(keyedBy: AnswerKey.self, forKey: "labels") + element = .products(StoryProductsElement( + showLabel: labels?.lenientString("show_carousel") ?? "", + hideLabel: labels?.lenientString("hide_carousel") ?? "", + products: (item.lenientList(ProductAnswer.self, "products") ?? []).map(\.product) + )) + case "text_block": + element = .textBlock(StoryTextBlockElement( + text: item.lenientString("text_input") ?? "", + fontSize: item.lenientDouble("font_size") ?? StoryTextBlockElement.defaultFontSize, + fontType: item.lenientString("font_type") ?? "", + bold: item.lenientBool("bold") == true || item.lenientBool("text_bold") == true, + italic: item.lenientBool("italic") ?? false, + textAlign: item.lenientString("text_align") ?? "", + textColor: item.lenientString("text_color") ?? "", + backgroundColor: item.lenientString("text_background_color") ?? "", + backgroundOpacity: item.opacity("text_background_color_opacity"), + lineSpacing: item.lenientDouble("text_line_spacing") ?? 0, + yOffset: item.lenientDouble("y_offset") ?? 0, + promocode: item.lenientString("promocode") + )) + default: + element = nil + } + } + } + + /// A product; an empty object is none. + private struct ProductAnswer: Decodable { + let product: StoryProduct + + init(from decoder: Decoder) throws { + let item = try decoder.container(keyedBy: AnswerKey.self) + guard !item.allKeys.isEmpty else { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "an empty product")) + } + let price = item.lenientDouble("price") ?? 0 + let oldPrice = item.lenientDouble("oldprice") + product = StoryProduct( + id: item.lenientString("id") ?? "", + name: item.lenientString("name") ?? "", + brand: item.lenientString("brand") ?? "", + picture: item.lenientString("picture") ?? "", + imageUrl: item.lenientString("image_url") ?? "", + price: price, + priceFormatted: item.lenientString("price_formatted") ?? "", + // Without a discount the server sends the price itself. + oldPrice: oldPrice.flatMap { $0 > price ? $0 : nil }, + oldPriceFormatted: item.lenientString("oldprice_formatted") ?? "", + discountPercent: item.lenientDouble("discount_percent") ?? 0, + promocode: item.lenientString("promocode") ?? "", + priceWithPromocode: item.lenientDouble("price_with_promocode") ?? 0, + priceWithPromocodeFormatted: item.lenientString("price_with_promocode_formatted") ?? "", + currency: item.lenientString("currency") ?? "", + url: item.lenientString("url") ?? "", + deeplinkAndroid: item.lenientString("deeplink_android") ?? "", + deeplinkIos: item.lenientString("deeplink_ios") ?? "" + ) + } + } +} + +private extension KeyedDecodingContainer where Key == AnswerKey { + + /// An opacity of 0…1, as the account sends it and Flutter reads it: a string is percents with or + /// without the sign (`"50%"`, `"50"`), a number above 1 is percents too, otherwise a fraction. + /// Anything else, or none, is 0. + func opacity(_ key: Key) -> Double { + let number: Double? + if let text = try? decodeIfPresent(String.self, forKey: key) { + let digits = text.replacingOccurrences(of: "%", with: "").trimmingCharacters(in: .whitespaces) + number = Double(digits).map { $0 / 100 } + } else { + number = lenientDouble(key).map { $0 > 1 ? $0 / 100 : $0 } + } + guard let value = number, value.isFinite, value > 0 else { return 0 } + return min(value, 1) + } +} diff --git a/REES46/Classes/Stories/API/StoriesBlock.swift b/REES46/Classes/Stories/API/StoriesBlock.swift new file mode 100644 index 00000000..fdd74729 --- /dev/null +++ b/REES46/Classes/Stories/API/StoriesBlock.swift @@ -0,0 +1,165 @@ +// +// StoriesBlock.swift +// REES46 +// +// The models of `stories.get` (`sdk/contract/stories.md`), the same as the Flutter SDK's. A string +// field without a value is an empty string, not `nil`, as Flutter has it: a model reads without checks. +// + +import Foundation + +/// A stories block: what `stories.get` gives. +@_spi(Bridge) +public struct StoriesBlock { + /// The block's id on the server. + public let id: String + /// Empty for a block without stories or one on pause. + public let stories: [Story] +} + +/// One story: a cover in the bar and the slides it plays. +@_spi(Bridge) +public struct Story { + public let id: String + public let name: String + /// The cover's URL. + public let avatar: String + /// The server remembers the device saw it. + public let viewed: Bool + /// Pinned by the shop to the start of the bar. + public let pinned: Bool + /// The slide to start from: the first one the device has not seen. + public let startPosition: Int + public let slides: [StorySlide] +} + +/// One slide of a story. +@_spi(Bridge) +public struct StorySlide { + /// A number for a slide with media; `_`, like `39_0`, for a slide of products. + public let id: String + public let type: StorySlideType + /// The URL of the picture or the video; a slide of products has the one of the stories' settings. + public let background: String + /// `#RRGGBB`; empty when not set. + public let backgroundColor: String + /// The poster of a video; empty when there is none. + public let preview: String + /// How long the slide stays, in seconds: 10 when the answer has none or 0. + public let duration: Int + /// The elements the SDK knows, in the answer's order: others — `header`, `poll` — are left out. + public let elements: [StoryElement] + + /// The seconds of a slide whose answer has no duration, or 0. + public static let defaultDuration = 10 +} + +/// What a slide shows behind its elements. +@_spi(Bridge) +public enum StorySlideType { + /// `background` is a picture. + case image + /// `background` is a video, `preview` its poster. + case video + /// A slide of products of a campaign: its product comes in a `StoryProductElement`. The answer + /// gives it no type of media. + case product +} + +/// An element of a slide. +@_spi(Bridge) +public enum StoryElement { + case button(StoryButtonElement) + case product(StoryProductElement) + case products(StoryProductsElement) + case textBlock(StoryTextBlockElement) +} + +/// `button`: a button with a link. +@_spi(Bridge) +public struct StoryButtonElement { + public let title: String + public let link: String + public let linkAndroid: String + public let linkIos: String + /// The colours of the old stories view. + public let background: String + public let color: String + public let textBold: Bool +} + +/// `product`: the product of a slide of products. +@_spi(Bridge) +public struct StoryProductElement { + public let title: String + /// `nil` when the answer has none. + public let item: StoryProduct? +} + +/// `products`: the products of a slide behind a "show / hide" toggle. +@_spi(Bridge) +public struct StoryProductsElement { + /// The toggle's text while the products are hidden (`labels.show_carousel`). + public let showLabel: String + /// The toggle's text while they are shown (`labels.hide_carousel`). + public let hideLabel: String + public let products: [StoryProduct] +} + +/// `text_block`: a text over the slide. +@_spi(Bridge) +public struct StoryTextBlockElement { + /// The text (`text_input`). + public let text: String + /// 14 when not set. + public let fontSize: Double + /// `serif`, `sans-serif`, `monospace` or empty. + public let fontType: String + public let bold: Bool + public let italic: Bool + /// `left`, `center`, `right` or empty. + public let textAlign: String + /// `#RRGGBB` or empty. + public let textColor: String + /// `#RRGGBB` behind the text, or empty. + public let backgroundColor: String + /// 0…1, read from `"50%"`, `"50"` or `0.5`; 0 — no frame. + public let backgroundOpacity: Double + /// A multiple of the font size; 0 — the font's own. + public let lineSpacing: Double + /// The top of the block, in percent of the slide's height. + public let yOffset: Double + /// The code the block copies when tapped; `nil` when it has none. + public let promocode: String? + + /// The font size of a block whose answer has none. + public static let defaultFontSize: Double = 14 +} + +/// A product of a stories block. +@_spi(Bridge) +public struct StoryProduct { + public let id: String + public let name: String + public let brand: String + /// The reduced picture: the one to show. + public let picture: String + /// The original picture. + public let imageUrl: String + public let price: Double + public let priceFormatted: String + /// The price without the discount; `nil` unless it is above `price` — without a discount the + /// server sends `price` here. + public let oldPrice: Double? + public let oldPriceFormatted: String + /// Only when the shop loaded it into its catalog; 0 otherwise. `price` already has the discount. + public let discountPercent: Double + public let promocode: String + /// 0 when the answer has none. + public let priceWithPromocode: Double + public let priceWithPromocodeFormatted: String + public let currency: String + public let url: String + public let deeplinkAndroid: String + public let deeplinkIos: String +} diff --git a/REES46/Classes/Stories/CollectionCell/StoriesCollectionViewPreviewCell.swift b/REES46/Classes/Stories/CollectionCell/StoriesCollectionViewPreviewCell.swift index b03be104..8f60d941 100644 --- a/REES46/Classes/Stories/CollectionCell/StoriesCollectionViewPreviewCell.swift +++ b/REES46/Classes/Stories/CollectionCell/StoriesCollectionViewPreviewCell.swift @@ -95,7 +95,7 @@ class StoriesCollectionViewPreviewCell: UICollectionViewCell { self.storyImage.load.request(with: url) } - public func configure(story: Story) { + public func configure(story: LegacyStory) { setImage(imagePathSdk: story.avatar) if SdkConfiguration.stories.storiesBlockCharWrapping { storyAuthorNameLabel.text = "\(story.name)".truncWords(length: SdkConfiguration.stories.storiesBlockCharCountWrap) diff --git a/REES46/Classes/Stories/StoriesView.swift b/REES46/Classes/Stories/StoriesView.swift index 76562a8c..e8cd1a19 100644 --- a/REES46/Classes/Stories/StoriesView.swift +++ b/REES46/Classes/Stories/StoriesView.swift @@ -78,7 +78,7 @@ public class StoriesView: UIView, UINavigationControllerDelegate { return collectionView }() - private var stories: [Story]? + private var stories: [LegacyStory]? private var settings: StoriesSettings? private var sdk: PersonalizationSDK? @@ -413,14 +413,14 @@ extension StoriesView: UICollectionViewDelegate, UICollectionViewDataSource, UIC /// The loaded list and the cells the collection asks for can disagree for a moment (see /// `numberOfItemsInSection`), so every read of it goes through a bounds check. - private func story(at index: Int) -> Story? { + private func story(at index: Int) -> LegacyStory? { guard let stories = stories, stories.indices.contains(index) else { return nil } return stories[index] } - private func showStories(at index: Int, for story: Story) { + private func showStories(at index: Int, for story: LegacyStory) { let storyVC = StoryViewController() storyVC.sdkLinkDelegate = self storyVC.sdk = sdk diff --git a/REES46/Classes/Stories/StoryViewController/StoryViewController.swift b/REES46/Classes/Stories/StoryViewController/StoryViewController.swift index c2375555..0fc07e23 100644 --- a/REES46/Classes/Stories/StoryViewController/StoryViewController.swift +++ b/REES46/Classes/Stories/StoryViewController/StoryViewController.swift @@ -68,7 +68,7 @@ class StoryViewController: UINavigationController, UINavigationControllerDelegat return view }() - public var stories: [Story] = [] + public var stories: [LegacyStory] = [] public var startWithIndexPath: IndexPath? = .init(item: 1, section: 0) public var currentPosition: IndexPath = IndexPath() diff --git a/REES46/Classes/Subscription/SubscriptionsAPI.swift b/REES46/Classes/Subscription/SubscriptionsAPI.swift new file mode 100644 index 00000000..bb42f229 --- /dev/null +++ b/REES46/Classes/Subscription/SubscriptionsAPI.swift @@ -0,0 +1,319 @@ +// +// SubscriptionsAPI.swift +// REES46 +// +// The `subscriptions` namespace of the contract (`sdk/contract/subscriptions.md`). +// + +import Foundation + +/** + The customer's subscriptions: to the channels and kinds of mailings, and to a product's price drop or its + return to stock. The server finds the customer by the device id; a contact in a request says which + address or number the subscription is for. Pass a contact only when the app knows it is the customer's: + the server acts on its owner. + + For the Flutter and React Native bridges, as every namespace but `tracking`: `@_spi(Bridge) import + REES46` and a shop started with `Rees46.initializeBridge`. On the old core every method ends as + `notInitialized` and sends nothing. + + Every `completion` is called once, on the main thread, with the value or the error: `notInitialized` on + the old core or after `release()`, `shopBlocked`, `invalidArgument` — an empty `itemId`, a + `currentPrice` not above 0, an empty string in `itemIds` or in a contact, `manage` without a flag — + before anything is sent, `network`, `timeout`, `http(code:serverCode:)`, `decoding`, `cancelled` for a + call `release()` ended. The `async` forms throw the same `Rees46.SdkError`, and cancelling the task + ends the call as `cancelled`. Nothing is repeated: the app decides. The server checks the email and the + phone. + */ +@_spi(Bridge) +public protocol SubscriptionsAPI { + + /// Subscribes the customer to channels and kinds of mailings or unsubscribes them + /// (`POST subscriptions/manage`): `true` subscribes, `false` unsubscribes, `nil` changes nothing. + func manage(_ request: Rees46.SubscriptionsUpdateRequest, completion: @escaping (Result) -> Void) + + func manage(_ request: Rees46.SubscriptionsUpdateRequest) async throws + + /// The customer's subscriptions on every channel and kind (`GET subscriptions/check`). A device the + /// server does not know is `http(400)`. + func check(completion: @escaping (Result) -> Void) + + func check() async throws -> Rees46.SubscriptionStatus + + /// Subscribes the customer to the drop of a product's price + /// (`POST subscriptions/subscribe_for_product_price`); the server ends it once it told them. + func subscribeForPriceDrop( + itemId: String, + currentPrice: Double, + email: String?, + phone: String?, + completion: @escaping (Result) -> Void + ) + + func subscribeForPriceDrop(itemId: String, currentPrice: Double, email: String?, phone: String?) async throws + + /// Unsubscribes the customer from the drop of the products' prices + /// (`POST subscriptions/unsubscribe_from_product_price`): an empty `itemIds` is every product. + func unsubscribeFromPriceDrop( + itemIds: [String], + email: String?, + phone: String?, + completion: @escaping (Result) -> Void + ) + + func unsubscribeFromPriceDrop(itemIds: [String], email: String?, phone: String?) async throws + + /// Subscribes the customer to a product's return to stock, in the variant of `properties` + /// (`POST subscriptions/subscribe_for_product_available`); the server ends it once it told them. + func subscribeForBackInStock( + itemId: String, + properties: Rees46.BackInStockProperties?, + email: String?, + phone: String?, + completion: @escaping (Result) -> Void + ) + + func subscribeForBackInStock(itemId: String, properties: Rees46.BackInStockProperties?, email: String?, phone: String?) async throws + + /// Unsubscribes the customer from the products' return to stock + /// (`POST subscriptions/unsubscribe_from_product_available`): an empty `itemIds` is every product. + func unsubscribeFromBackInStock( + itemIds: [String], + email: String?, + phone: String?, + completion: @escaping (Result) -> Void + ) + + func unsubscribeFromBackInStock(itemIds: [String], email: String?, phone: String?) async throws +} + +/// The arguments by default: protocol requirements cannot carry them. +@_spi(Bridge) +extension SubscriptionsAPI { + + public func subscribeForPriceDrop( + itemId: String, + currentPrice: Double, + email: String? = nil, + phone: String? = nil, + completion: @escaping (Result) -> Void + ) { + subscribeForPriceDrop(itemId: itemId, currentPrice: currentPrice, email: email, phone: phone, completion: completion) + } + + public func subscribeForPriceDrop(itemId: String, currentPrice: Double, email: String? = nil, phone: String? = nil) async throws { + try await subscribeForPriceDrop(itemId: itemId, currentPrice: currentPrice, email: email, phone: phone) + } + + public func unsubscribeFromPriceDrop( + itemIds: [String], + email: String? = nil, + phone: String? = nil, + completion: @escaping (Result) -> Void + ) { + unsubscribeFromPriceDrop(itemIds: itemIds, email: email, phone: phone, completion: completion) + } + + public func unsubscribeFromPriceDrop(itemIds: [String], email: String? = nil, phone: String? = nil) async throws { + try await unsubscribeFromPriceDrop(itemIds: itemIds, email: email, phone: phone) + } + + public func subscribeForBackInStock( + itemId: String, + properties: Rees46.BackInStockProperties? = nil, + email: String? = nil, + phone: String? = nil, + completion: @escaping (Result) -> Void + ) { + subscribeForBackInStock(itemId: itemId, properties: properties, email: email, phone: phone, completion: completion) + } + + public func subscribeForBackInStock( + itemId: String, + properties: Rees46.BackInStockProperties? = nil, + email: String? = nil, + phone: String? = nil + ) async throws { + try await subscribeForBackInStock(itemId: itemId, properties: properties, email: email, phone: phone) + } + + public func unsubscribeFromBackInStock( + itemIds: [String], + email: String? = nil, + phone: String? = nil, + completion: @escaping (Result) -> Void + ) { + unsubscribeFromBackInStock(itemIds: itemIds, email: email, phone: phone, completion: completion) + } + + public func unsubscribeFromBackInStock(itemIds: [String], email: String? = nil, phone: String? = nil) async throws { + try await unsubscribeFromBackInStock(itemIds: itemIds, email: email, phone: phone) + } +} + +@_spi(Bridge) +extension Rees46 { + + /// What `subscriptions.manage` changes: `true` subscribes, `false` unsubscribes, `nil` is not sent. + /// The kinds of mailings: `bulk`, mass mailings; `chain`, triggered ones; `transactional`, the + /// service ones. + public struct SubscriptionsUpdateRequest: Equatable { + public var email: String? + public var phone: String? + /// The customer's id in the shop's system. + public var externalId: String? + /// The id in an external loyalty program. + public var loyaltyId: String? + public var telegramId: String? + public var emailBulk: Bool? + public var emailChain: Bool? + public var emailTransactional: Bool? + public var smsBulk: Bool? + public var smsChain: Bool? + public var smsTransactional: Bool? + public var webPushBulk: Bool? + public var webPushChain: Bool? + public var webPushTransactional: Bool? + public var mobilePushBulk: Bool? + public var mobilePushChain: Bool? + public var mobilePushTransactional: Bool? + public var telegramBulk: Bool? + public var telegramChain: Bool? + public var telegramTransactional: Bool? + public var whatsappBulk: Bool? + public var whatsappChain: Bool? + public var whatsappTransactional: Bool? + public var maxBulk: Bool? + public var maxChain: Bool? + public var maxTransactional: Bool? + public var walletBulk: Bool? + public var walletChain: Bool? + public var walletTransactional: Bool? + + public init( + email: String? = nil, + phone: String? = nil, + externalId: String? = nil, + loyaltyId: String? = nil, + telegramId: String? = nil, + emailBulk: Bool? = nil, + emailChain: Bool? = nil, + emailTransactional: Bool? = nil, + smsBulk: Bool? = nil, + smsChain: Bool? = nil, + smsTransactional: Bool? = nil, + webPushBulk: Bool? = nil, + webPushChain: Bool? = nil, + webPushTransactional: Bool? = nil, + mobilePushBulk: Bool? = nil, + mobilePushChain: Bool? = nil, + mobilePushTransactional: Bool? = nil, + telegramBulk: Bool? = nil, + telegramChain: Bool? = nil, + telegramTransactional: Bool? = nil, + whatsappBulk: Bool? = nil, + whatsappChain: Bool? = nil, + whatsappTransactional: Bool? = nil, + maxBulk: Bool? = nil, + maxChain: Bool? = nil, + maxTransactional: Bool? = nil, + walletBulk: Bool? = nil, + walletChain: Bool? = nil, + walletTransactional: Bool? = nil + ) { + self.email = email + self.phone = phone + self.externalId = externalId + self.loyaltyId = loyaltyId + self.telegramId = telegramId + self.emailBulk = emailBulk + self.emailChain = emailChain + self.emailTransactional = emailTransactional + self.smsBulk = smsBulk + self.smsChain = smsChain + self.smsTransactional = smsTransactional + self.webPushBulk = webPushBulk + self.webPushChain = webPushChain + self.webPushTransactional = webPushTransactional + self.mobilePushBulk = mobilePushBulk + self.mobilePushChain = mobilePushChain + self.mobilePushTransactional = mobilePushTransactional + self.telegramBulk = telegramBulk + self.telegramChain = telegramChain + self.telegramTransactional = telegramTransactional + self.whatsappBulk = whatsappBulk + self.whatsappChain = whatsappChain + self.whatsappTransactional = whatsappTransactional + self.maxBulk = maxBulk + self.maxChain = maxChain + self.maxTransactional = maxTransactional + self.walletBulk = walletBulk + self.walletChain = walletChain + self.walletTransactional = walletTransactional + } + } + + /// The customer's subscriptions: for each channel and kind, whether the customer has the channel's + /// contact and is subscribed. A field the answer does not have is `false`. + public struct SubscriptionStatus: Equatable { + /// Whether the CDP has the customer. + public let exists: Bool + public let emailBulk: Bool + public let emailChain: Bool + public let emailTransactional: Bool + public let smsBulk: Bool + public let smsChain: Bool + public let smsTransactional: Bool + public let webPushBulk: Bool + public let webPushChain: Bool + public let webPushTransactional: Bool + public let mobilePushBulk: Bool + public let mobilePushChain: Bool + public let mobilePushTransactional: Bool + public let telegramBulk: Bool + public let telegramChain: Bool + public let telegramTransactional: Bool + public let whatsappBulk: Bool + public let whatsappChain: Bool + public let whatsappTransactional: Bool + public let maxBulk: Bool + public let maxChain: Bool + public let maxTransactional: Bool + public let walletBulk: Bool + public let walletChain: Bool + public let walletTransactional: Bool + /// `web_push`: whether the customer has a working web push token. + public let hasWebPush: Bool + /// `mobile_push`: whether the customer has a working mobile push token. + public let hasMobilePush: Bool + public let emailInvalid: Bool + public let emailBlacklisted: Bool + /// The email does not exist. + public let emailBounced: Bool + /// The email is blocked: its subscriptions cannot change. + public let emailSuppressed: Bool + public let emailConfirmed: Bool + } + + /// The variant of a product a subscription to its return to stock is for. + public struct BackInStockProperties: Equatable { + public var fashionSize: String? + public var fashionColor: String? + public var barcode: String? + + public init(fashionSize: String? = nil, fashionColor: String? = nil, barcode: String? = nil) { + self.fashionSize = fashionSize + self.fashionColor = fashionColor + self.barcode = barcode + } + } +} + +@_spi(Bridge) +extension PersonalizationSDK { + + /// The customer's subscriptions (`SubscriptionsAPI`): on the new core only. + public var subscriptions: SubscriptionsAPI { + SubscriptionsAPIImpl(requests: NamespaceRequests(self), popups: self as? SimplePersonalizationSDK) + } +} diff --git a/REES46/Classes/Subscription/SubscriptionsAPIImpl.swift b/REES46/Classes/Subscription/SubscriptionsAPIImpl.swift new file mode 100644 index 00000000..8ea94b47 --- /dev/null +++ b/REES46/Classes/Subscription/SubscriptionsAPIImpl.swift @@ -0,0 +1,240 @@ +// +// SubscriptionsAPIImpl.swift +// REES46 +// + +import Foundation + +struct SubscriptionsAPIImpl: SubscriptionsAPI { + + let requests: NamespaceRequests + /// The instance whose popups v3 hear that the subscriptions changed. + weak var popups: SimplePersonalizationSDK? + + func manage(_ request: Rees46.SubscriptionsUpdateRequest, completion: @escaping (Result) -> Void) { + requests.call("subscriptions.manage", completion: completion) { try changing(Self.manageRequest(request)) } + } + + func manage(_ request: Rees46.SubscriptionsUpdateRequest) async throws { + try await requests.value("subscriptions.manage") { try changing(Self.manageRequest(request)) } + } + + func check(completion: @escaping (Result) -> Void) { + requests.call("subscriptions.check", completion: completion) { Self.checkRequest } + } + + func check() async throws -> Rees46.SubscriptionStatus { + try await requests.value("subscriptions.check") { Self.checkRequest } + } + + func subscribeForPriceDrop( + itemId: String, + currentPrice: Double, + email: String?, + phone: String?, + completion: @escaping (Result) -> Void + ) { + requests.call("subscriptions.subscribeForPriceDrop", completion: completion) { + try Self.priceDropRequest(itemId: itemId, currentPrice: currentPrice, email: email, phone: phone) + } + } + + func subscribeForPriceDrop(itemId: String, currentPrice: Double, email: String?, phone: String?) async throws { + try await requests.value("subscriptions.subscribeForPriceDrop") { + try Self.priceDropRequest(itemId: itemId, currentPrice: currentPrice, email: email, phone: phone) + } + } + + func unsubscribeFromPriceDrop( + itemIds: [String], + email: String?, + phone: String?, + completion: @escaping (Result) -> Void + ) { + requests.call("subscriptions.unsubscribeFromPriceDrop", completion: completion) { + try Self.unsubscribeRequest("subscriptions/unsubscribe_from_product_price", itemIds: itemIds, email: email, phone: phone) + } + } + + func unsubscribeFromPriceDrop(itemIds: [String], email: String?, phone: String?) async throws { + try await requests.value("subscriptions.unsubscribeFromPriceDrop") { + try Self.unsubscribeRequest("subscriptions/unsubscribe_from_product_price", itemIds: itemIds, email: email, phone: phone) + } + } + + func subscribeForBackInStock( + itemId: String, + properties: Rees46.BackInStockProperties?, + email: String?, + phone: String?, + completion: @escaping (Result) -> Void + ) { + requests.call("subscriptions.subscribeForBackInStock", completion: completion) { + try Self.backInStockRequest(itemId: itemId, properties: properties, email: email, phone: phone) + } + } + + func subscribeForBackInStock(itemId: String, properties: Rees46.BackInStockProperties?, email: String?, phone: String?) async throws { + try await requests.value("subscriptions.subscribeForBackInStock") { + try Self.backInStockRequest(itemId: itemId, properties: properties, email: email, phone: phone) + } + } + + func unsubscribeFromBackInStock( + itemIds: [String], + email: String?, + phone: String?, + completion: @escaping (Result) -> Void + ) { + requests.call("subscriptions.unsubscribeFromBackInStock", completion: completion) { + try Self.unsubscribeRequest("subscriptions/unsubscribe_from_product_available", itemIds: itemIds, email: email, phone: phone) + } + } + + func unsubscribeFromBackInStock(itemIds: [String], email: String?, phone: String?) async throws { + try await requests.value("subscriptions.unsubscribeFromBackInStock") { + try Self.unsubscribeRequest("subscriptions/unsubscribe_from_product_available", itemIds: itemIds, email: email, phone: phone) + } + } + + /// `request` once it is on its way: popups v3 load their list anew for subscriptions new in the + /// session, as for the old `manageSubscription`. + private func changing(_ request: ApiRequest) -> ApiRequest { + popups?.popupsV3.contextChanged("subscription", signature: ClientBody.signature(request.body)) + return request + } + + // MARK: - Requests + + /// The flags of `SubscriptionsUpdateRequest` and `SubscriptionStatus` by their names on the wire. + static let flags: [(name: String, request: KeyPath)] = [ + ("email_bulk", \.emailBulk), ("email_chain", \.emailChain), ("email_transactional", \.emailTransactional), + ("sms_bulk", \.smsBulk), ("sms_chain", \.smsChain), ("sms_transactional", \.smsTransactional), + ("web_push_bulk", \.webPushBulk), ("web_push_chain", \.webPushChain), ("web_push_transactional", \.webPushTransactional), + ("mobile_push_bulk", \.mobilePushBulk), ("mobile_push_chain", \.mobilePushChain), + ("mobile_push_transactional", \.mobilePushTransactional), + ("telegram_bulk", \.telegramBulk), ("telegram_chain", \.telegramChain), ("telegram_transactional", \.telegramTransactional), + ("whatsapp_bulk", \.whatsappBulk), ("whatsapp_chain", \.whatsappChain), ("whatsapp_transactional", \.whatsappTransactional), + ("max_bulk", \.maxBulk), ("max_chain", \.maxChain), ("max_transactional", \.maxTransactional), + ("wallet_bulk", \.walletBulk), ("wallet_chain", \.walletChain), ("wallet_transactional", \.walletTransactional) + ] + + /// `POST subscriptions/manage` with the contacts and the flags given; without a flag there is + /// nothing to change. + static func manageRequest(_ request: Rees46.SubscriptionsUpdateRequest) throws -> ApiRequest { + var body = ClientBody() + try body.identifier("email", request.email, "email") + try body.identifier("phone", request.phone, "phone") + try body.identifier("external_id", request.externalId, "externalId") + try body.identifier("loyalty_id", request.loyaltyId, "loyaltyId") + try body.identifier("telegram_id", request.telegramId, "telegramId") + var changes = 0 + for flag in flags { + if let value = request[keyPath: flag.request] { + body.set(flag.name, value) + changes += 1 + } + } + guard changes > 0 else { + throw Rees46.SdkError.invalidArgument("the request changes no subscription") + } + return ApiRequest(method: .post, path: "subscriptions/manage", body: body.fields) { _ in () } + } + + /// `GET subscriptions/check`: the customer of the device. An answer without a body has no + /// subscription. + static var checkRequest: ApiRequest { + ApiRequest(method: .get, path: "subscriptions/check") { body in + try Readable.read(body.isEmpty ? Data("{}".utf8) : body) + } + } + + /// `POST subscriptions/subscribe_for_product_price`: the product as `item_id`; the price goes as + /// `price`, which the server takes from the catalog instead. + static func priceDropRequest(itemId: String, currentPrice: Double, email: String?, phone: String?) throws -> ApiRequest { + let id = try CatalogQuery.identifier(itemId, "itemId") + var body = ClientBody(["item_id": id]) + guard currentPrice.isFinite, currentPrice > 0 else { + throw Rees46.SdkError.invalidArgument("currentPrice must be above 0") + } + body.set("price", currentPrice) + try body.identifier("email", email, "email") + try body.identifier("phone", phone, "phone") + return ApiRequest(method: .post, path: "subscriptions/subscribe_for_product_price", body: body.fields) { _ in () } + } + + /// `POST subscriptions/subscribe_for_product_available`: the product as `item_id`, its variant in + /// `properties` when it has a field. + static func backInStockRequest( + itemId: String, + properties: Rees46.BackInStockProperties?, + email: String?, + phone: String? + ) throws -> ApiRequest { + let id = try CatalogQuery.identifier(itemId, "itemId") + var body = ClientBody(["item_id": id]) + var variant = ClientBody() + variant.set("fashion_size", ApiArguments.given(properties?.fashionSize)) + variant.set("fashion_color", ApiArguments.given(properties?.fashionColor)) + variant.set("barcode", ApiArguments.given(properties?.barcode)) + if !variant.fields.isEmpty { + body.set("properties", variant.fields) + } + try body.identifier("email", email, "email") + try body.identifier("phone", phone, "phone") + return ApiRequest(method: .post, path: "subscriptions/subscribe_for_product_available", body: body.fields) { _ in () } + } + + /// A request of `path` that unsubscribes from the products of `itemIds`, one value joined by `,` — + /// the only form the server reads —; an empty list is every product. + static func unsubscribeRequest(_ path: String, itemIds: [String], email: String?, phone: String?) throws -> ApiRequest { + guard !itemIds.contains(where: ApiArguments.isBlank) else { + throw Rees46.SdkError.invalidArgument("itemIds has an empty id") + } + var body = ClientBody(["item_ids": itemIds.joined(separator: ",")]) + try body.identifier("email", email, "email") + try body.identifier("phone", phone, "phone") + return ApiRequest(method: .post, path: path, body: body.fields) { _ in () } + } +} + +extension Rees46.SubscriptionStatus: AnswerReadable { + + init(answer: KeyedDecodingContainer) throws { + func flag(_ name: AnswerKey) -> Bool { + answer.lenientBool(name) ?? false + } + exists = flag("exists") + emailBulk = flag("email_bulk") + emailChain = flag("email_chain") + emailTransactional = flag("email_transactional") + smsBulk = flag("sms_bulk") + smsChain = flag("sms_chain") + smsTransactional = flag("sms_transactional") + webPushBulk = flag("web_push_bulk") + webPushChain = flag("web_push_chain") + webPushTransactional = flag("web_push_transactional") + mobilePushBulk = flag("mobile_push_bulk") + mobilePushChain = flag("mobile_push_chain") + mobilePushTransactional = flag("mobile_push_transactional") + telegramBulk = flag("telegram_bulk") + telegramChain = flag("telegram_chain") + telegramTransactional = flag("telegram_transactional") + whatsappBulk = flag("whatsapp_bulk") + whatsappChain = flag("whatsapp_chain") + whatsappTransactional = flag("whatsapp_transactional") + maxBulk = flag("max_bulk") + maxChain = flag("max_chain") + maxTransactional = flag("max_transactional") + walletBulk = flag("wallet_bulk") + walletChain = flag("wallet_chain") + walletTransactional = flag("wallet_transactional") + hasWebPush = flag("web_push") + hasMobilePush = flag("mobile_push") + emailInvalid = flag("email_invalid") + emailBlacklisted = flag("email_blacklisted") + emailBounced = flag("email_bounced") + emailSuppressed = flag("email_suppressed") + emailConfirmed = flag("email_confirmed") + } +} diff --git a/REES46/Classes/Tracking/API/TrackingAPI+Banners.swift b/REES46/Classes/Tracking/API/TrackingAPI+Banners.swift new file mode 100644 index 00000000..b527a9cd --- /dev/null +++ b/REES46/Classes/Tracking/API/TrackingAPI+Banners.swift @@ -0,0 +1,123 @@ +// +// TrackingAPI+Banners.swift +// REES46 +// +// The events of the banners of a slider (`sdk/contract/tracking.md`, `bannerView` and `bannerClick`; +// `sdk/contract/sliders.md`): for the bridges, on the new core only. +// + +import Foundation + +/** + A banner of a slider (`sliders.get`) shown or tapped. For the Flutter and React Native bridges: + `@_spi(Bridge) import REES46` and a shop started with `Rees46.initializeBridge`. + + The event goes through the shop's queue (`sdk/core/queue.md`), as every event of `tracking` does on + the new core: kept on the device and sent once the device is known to the server, after no network or + a restart too. `completion` is called once, on the main thread, when the queue took the event — not when + it was sent —, or with why it did not: `invalidArgument` for a `bannerId` that is not a positive whole + number, or an empty `code`; `notInitialized` on the old core, which sends nothing, or after + `release()`; `shopBlocked`. + */ +@_spi(Bridge) +extension TrackingAPI { + + /// A banner was shown (`POST track/slider`, `event=view`): once, when it first became visible in + /// this showing of the slider. `bannerId` and `code` are the banner's `SliderBanner.id` and + /// `SliderBanner.code`. + public func bannerView( + bannerId: String, + code: String, + completion: @escaping (Result) -> Void = { _ in } + ) { + BannerEvent.view.send(bannerId: bannerId, code: code, by: self, completion: completion) + } + + /// A banner was tapped (`POST track/slider`, `event=click`). `bannerId` and `code` are the banner's + /// `SliderBanner.id` and `SliderBanner.code`. + public func bannerClick( + bannerId: String, + code: String, + completion: @escaping (Result) -> Void = { _ in } + ) { + BannerEvent.click.send(bannerId: bannerId, code: code, by: self, completion: completion) + } + + /// `bannerView(bannerId:code:completion:)` for `async` code: returns once the queue took the event, + /// throws the `Rees46.SdkError` otherwise. + public func bannerView(bannerId: String, code: String) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + bannerView(bannerId: bannerId, code: code) { continuation.resume(with: $0) } + } + } + + /// `bannerClick(bannerId:code:completion:)` for `async` code: returns once the queue took the event, + /// throws the `Rees46.SdkError` otherwise. + public func bannerClick(bannerId: String, code: String) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + bannerClick(bannerId: bannerId, code: code) { continuation.resume(with: $0) } + } + } +} + +/// An event of a banner: its `event` on the wire. +enum BannerEvent: String { + case view + case click + + static let path = "track/slider" + + /// The method's name in the log. + var call: String { + switch self { + case .view: return "tracking.bannerView" + case .click: return "tracking.bannerClick" + } + } + + /// The largest `banner_id` the server takes: an unsigned 32-bit number. + static let maxBannerId = 4_294_967_295 + + /// The event's own fields: `banner_id` a number, `recommended_code` the slider's code. No + /// `recommended_by`: the address does not read it. The queue adds the shop, the device and the + /// session when the event goes. + func body(bannerId: String, code: String) throws -> [String: Any] { + guard !bannerId.isEmpty else { + throw Rees46.SdkError.invalidArgument("the banner id must not be empty") + } + guard bannerId.allSatisfy({ ("0"..."9").contains($0) }), let id = Int(bannerId), (1...Self.maxBannerId).contains(id) else { + throw Rees46.SdkError.invalidArgument("the banner id must be a positive whole number") + } + guard !ApiArguments.isBlank(code) else { + throw Rees46.SdkError.invalidArgument("the code of the slider must not be empty") + } + return ["event": rawValue, "banner_id": id, "recommended_code": code] + } + + /// Hands the event to the queue of the instance behind `api`; `completion` hears, on the main + /// thread, when the queue took it or why not. + func send(bannerId: String, code: String, by api: TrackingAPI, completion: @escaping (Result) -> Void) { + let finish: (Rees46.SdkError?) -> Void = { error in + DispatchQueue.main.async { completion(error.map { .failure($0) } ?? .success(())) } + } + let ours = (api as? TrackingAPIImpl)?.instance + guard let instance = NamespaceRequests.onTheNewCore(ours, isTheSdks: false, call: call, owner: "TrackingAPI") else { + finish(.notInitialized) + return + } + let fields: [String: Any] + do { + fields = try body(bannerId: bannerId, code: code) + } catch { + let refusal = error as? Rees46.SdkError ?? .invalidArgument(String(describing: error)) + instance.logger.warning(LogCode.invalidArgument, "\(call): \(refusal.message)", ["call": call]) + finish(refusal) + return + } + // `accepted`: the event is on disk, or why the queue refused it (released, a refused shop). + guard instance.enqueueEvent(path: Self.path, body: fields, accepted: finish, completion: { _ in }) else { + finish(.notInitialized) + return + } + } +} diff --git a/REES46/Classes/Tracking/API/TrackingAPIImpl.swift b/REES46/Classes/Tracking/API/TrackingAPIImpl.swift index 5aa6ab56..57e9492b 100644 --- a/REES46/Classes/Tracking/API/TrackingAPIImpl.swift +++ b/REES46/Classes/Tracking/API/TrackingAPIImpl.swift @@ -217,3 +217,12 @@ private extension TrackingItem { CartItem(productId: id, quantity: quantity, price: price) } } + +extension TrackingAPIImpl { + + /// The SDK's own instance behind the services, for the events only its new core sends + /// (`bannerView`, `bannerClick`); `nil` when the services are another's. + var instance: SimplePersonalizationSDK? { + (trackService as? TrackEventServiceImpl)?.instance + } +} diff --git a/REES46/Classes/Tracking/Service/impl/TrackServiceImpl.swift b/REES46/Classes/Tracking/Service/impl/TrackServiceImpl.swift index b45723f3..dd2320a2 100644 --- a/REES46/Classes/Tracking/Service/impl/TrackServiceImpl.swift +++ b/REES46/Classes/Tracking/Service/impl/TrackServiceImpl.swift @@ -884,3 +884,12 @@ final class TrackingSourceStoreImpl: TrackingSourceStore { return (type: type, code: code) } } + +extension TrackEventServiceImpl { + + /// The SDK's own instance the events go through: the events only its new core sends + /// (`TrackingAPI.bannerView`, `bannerClick`) need it. `nil` for another conformer of the protocol. + var instance: SimplePersonalizationSDK? { + sdk as? SimplePersonalizationSDK + } +} diff --git a/Tests/REES46CoreTests/AgentSearchPackageTests.swift b/Tests/REES46CoreTests/AgentSearchPackageTests.swift new file mode 100644 index 00000000..c18aeef5 --- /dev/null +++ b/Tests/REES46CoreTests/AgentSearchPackageTests.swift @@ -0,0 +1,50 @@ +// +// AgentSearchPackageTests.swift +// REES46CoreTests +// +// The search agent of `search` without a server, beyond the cases of `search.json`: its requests go to +// the host of API v3, a message with the read timeout of the agent, and the length of a message counts +// as the server counts it. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class AgentSearchPackageTests: XCTestCase { + + func test_the_agents_requests_go_to_the_host_of_api_v3() throws { + let dialog = SearchAPIImpl.agentDialogRequest(sessionId: nil, locations: nil) + XCTAssertEqual(dialog.host, .app) + XCTAssertNil(dialog.timeout, "the dialog has the common timeout") + let message = try SearchAPIImpl.agentRequest(message: "hi", sessionId: 12, locations: []) + XCTAssertEqual(message.host, .app) + XCTAssertEqual(message.method, .post) + XCTAssertEqual(message.timeout, 60) + XCTAssertNil(message.body["location"], "an empty list is none") + XCTAssertEqual(message.body["session_id"] as? Int, 12) + // The rest of search stays on the API host. + XCTAssertEqual(SearchAPIImpl.blankRequest.host, .api) + XCTAssertEqual(try SearchAPIImpl.fullRequest(query: "q", Rees46.SearchFullRequest()).host, .api) + } + + func test_a_message_is_counted_in_unicode_scalars_as_the_server_counts_it() { + XCTAssertNoThrow(try SearchAPIImpl.agentRequest(message: String(repeating: "я", count: 500), sessionId: nil, locations: nil)) + XCTAssertThrowsError(try SearchAPIImpl.agentRequest(message: String(repeating: "я", count: 501), sessionId: nil, locations: nil)) + // A flag is one character on screen and two scalars on the server. + XCTAssertThrowsError(try SearchAPIImpl.agentRequest(message: String(repeating: "🇷🇺", count: 251), sessionId: nil, locations: nil)) + XCTAssertNoThrow(try SearchAPIImpl.agentRequest(message: String(repeating: "🇷🇺", count: 250), sessionId: nil, locations: nil)) + } + + func test_the_switch_of_the_agent_follows_blank_mode() { + let agent = AgentSearchSwitch() + XCTAssertFalse(agent.isOn, "no answer of /init") + agent.adopt(blankMode: "agent") + XCTAssertTrue(agent.isOn) + agent.adopt(blankMode: nil) + XCTAssertFalse(agent.isOn) + agent.adopt(blankMode: "Agent") + XCTAssertFalse(agent.isOn, "the value as the server writes it") + XCTAssertEqual(InitResponse(json: ["search": ["blank_mode": "agent"]]).search.blankMode, "agent") + XCTAssertNil(InitResponse(json: [:]).search.blankMode) + } +} diff --git a/Tests/REES46CoreTests/CartPackageTests.swift b/Tests/REES46CoreTests/CartPackageTests.swift new file mode 100644 index 00000000..2be6f0b2 --- /dev/null +++ b/Tests/REES46CoreTests/CartPackageTests.swift @@ -0,0 +1,70 @@ +// +// CartPackageTests.swift +// REES46CoreTests +// +// `cart.get` without a server: what the request path makes of each answer of the proposed fixture, as +// the client classifies it, and which bodies are a cart. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class CartPackageTests: XCTestCase { + + /// Every answer of the proposed `cart` fixture, as the client classifies it and the path reads it. + func test_the_cart_fixture_answers_end_as_the_fixture_says() throws { + // A case without an answer runs over the stub server (`NamespaceRequestTests`). + let cases = try ContractFixtures.fixture("cart", from: .proposed).filter { $0.response?.status != nil } + XCTAssertFalse(cases.isEmpty) + let logger = SdkLogger(shopId: "package-\(UUID().uuidString)", level: .none) + for item in cases { + let response = try XCTUnwrap(item.response, item.name) + let status = try XCTUnwrap(response.status, item.name) + let answer = NetworkClient.Response( + status: status, body: response.body, retryAfter: nil, + result: NetworkClient.classify(status: status, body: response.body, path: "products/cart") + ) + let result = NamespaceRequests.value(of: answer, for: CartAPIImpl.cartRequest, call: "cart.get", logger: logger) + assert(result, as: item) + } + } + + /// `result` ends as `item` expects: its error, or its `result` by the contract's field names. + private func assert(_ result: Result<[CartItem], Rees46.SdkError>, as item: ContractCase, file: StaticString = #filePath, line: UInt = #line) { + switch result { + case .success(let items): + XCTAssertNil(item.expectedError, "\(item.name): \(items)", file: file, line: line) + let expected = (item.expect["result"] as? [[String: Any]] ?? []).map { "\($0["id"] ?? "")×\($0["quantity"] ?? "")" } + XCTAssertEqual(items.map { "\($0.id)×\($0.quantity)" }, expected, item.name, file: file, line: line) + case .failure(let error): + XCTAssertTrue(item.expectedError?.matches(error) == true, "\(item.name): \(error), expected \(String(describing: item.expectedError))", file: file, line: line) + } + } + + func test_the_body_of_a_cart_is_its_value_whatever_else_the_body_holds() { + let logger = SdkLogger(shopId: "package-\(UUID().uuidString)", level: .none) + func items(_ json: String) -> [CartItem]? { + let body = Data(json.utf8) + let answer = NetworkClient.Response(status: 200, body: body, retryAfter: nil, result: NetworkClient.classify(status: 200, body: body)) + return try? NamespaceRequests.value(of: answer, for: CartAPIImpl.cartRequest, call: "cart.get", logger: logger).get() + } + XCTAssertEqual(items("")?.count, 0, "a 2xx without a body is an empty cart") + XCTAssertNil(items("{}"), "an empty object is not a cart") + XCTAssertNil(items(#"{"data": {}}"#), "no list of lines: not a cart") + XCTAssertNil(items(#"{"data": {"items": null}}"#)) + XCTAssertNil(items(#"{"data": {"items": "37"}}"#)) + XCTAssertNil(items(#"[]"#)) + XCTAssertEqual(items(#"{"data": {"items": [{"uniqid": "1"}]}, "payload": {"cart_items": []}}"#)?.map(\.id), ["1"], "today's shape first") + XCTAssertEqual(items(#"{"data": {"items": "37"}, "payload": {"cart_items": [{"uniqid": "2"}]}}"#)?.map(\.id), ["2"], "else the documented one") + XCTAssertEqual(items(#"{"data": {"items": [{"uniqid": " "}, {"uniqid": "3"}]}}"#)?.map(\.id), ["3"], "a blank id is none") + } + + func test_the_cart_fixture_is_proposed_until_the_contract_has_one() throws { + let cart = try ContractFixtures.fixture("cart", from: .proposed) + XCTAssertEqual(try ContractFixtures.load("cart", from: .proposed)["contract"] as? String, ContractFixtures.version) + XCTAssertEqual(cart.first?.call?.name, "cart.get") + XCTAssertEqual(cart.first?.request?.path, "products/cart") + XCTAssertTrue(cart.contains { $0.expectedError?.matches(.http(code: 404, serverCode: nil)) == true }) + XCTAssertFalse(FileManager.default.fileExists(atPath: ContractFixtures.url("cart").path), "the contract has cart.json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one") + } +} diff --git a/Tests/REES46CoreTests/CatalogPackageTests.swift b/Tests/REES46CoreTests/CatalogPackageTests.swift new file mode 100644 index 00000000..0fadeebb --- /dev/null +++ b/Tests/REES46CoreTests/CatalogPackageTests.swift @@ -0,0 +1,420 @@ +// +// CatalogPackageTests.swift +// REES46CoreTests +// +// The catalog's namespaces without a server — `products`, `collections`, `recommendations` and the +// search of `search` —: the request of each call of the proposed fixtures, the calls refused before +// anything is sent, and what the request path makes of each answer. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class CatalogPackageTests: XCTestCase { + + private typealias Fixtures = NamespaceFixtures + + // MARK: - The fixtures + + func test_products_build_the_fixtures_requests_and_refuse_its_arguments() throws { + try Fixtures.checkRequests("products", build: Self.products) + } + + func test_products_end_as_the_fixture_says_for_each_answer() throws { + try Fixtures.checkAnswers("products", build: Self.products) + } + + func test_collections_build_the_fixtures_requests_and_refuse_its_arguments() throws { + try Fixtures.checkRequests("collections", build: Self.collections) + } + + func test_collections_end_as_the_fixture_says_for_each_answer() throws { + try Fixtures.checkAnswers("collections", build: Self.collections) + } + + func test_recommendations_build_the_fixtures_requests_and_refuse_its_arguments() throws { + try Fixtures.checkRequests("recommendations", build: Self.recommendations) + } + + func test_recommendations_end_as_the_fixture_says_for_each_answer() throws { + try Fixtures.checkAnswers("recommendations", build: Self.recommendations) + } + + func test_search_builds_the_fixtures_requests_and_refuses_its_arguments() throws { + try Fixtures.checkRequests("search", build: Self.search) + } + + func test_search_ends_as_the_fixture_says_for_each_answer() throws { + try Fixtures.checkAnswers("search", build: Self.search) + } + + func test_the_catalogs_fixtures_are_proposed_until_the_contract_has_them() throws { + for name in ["products", "collections", "recommendations", "search"] { + XCTAssertEqual(try ContractFixtures.load(name, from: .proposed)["contract"] as? String, ContractFixtures.version, name) + let cases = try ContractFixtures.fixture(name, from: .proposed) + XCTAssertTrue(cases.allSatisfy { $0.call?.namespace == name }, name) + XCTAssertFalse( + FileManager.default.fileExists(atPath: ContractFixtures.url(name).path), + "the contract has \(name).json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one" + ) + } + } + + // MARK: - Calls of the fixtures + + private static func products(_ call: ContractCase.Call) throws -> ErasedRequest { + let args = call.args + switch call.method { + case "getInfo": + return ErasedRequest(try ProductsAPIImpl.infoRequest(itemId: Fixtures.string(args["itemId"]) ?? ""), call: call.name) + case "getList": + return ErasedRequest(try ProductsAPIImpl.listRequest(listRequest(args["request"])), call: call.name) + case "getCounters": + return ErasedRequest(try ProductsAPIImpl.countersRequest(itemId: Fixtures.string(args["itemId"]) ?? ""), call: call.name) + case "getCategory": + let request = categoryRequest(args["request"]) + return ErasedRequest(try ProductsAPIImpl.categoryRequest(categoryId: Fixtures.string(args["categoryId"]) ?? "", request), call: call.name) + default: + throw Unknown(call: call.name) + } + } + + private static func collections(_ call: ContractCase.Call) throws -> ErasedRequest { + guard call.method == "get" else { throw Unknown(call: call.name) } + return ErasedRequest(try CollectionsAPIImpl.collectionRequest(collectionId: Fixtures.string(call.args["collectionId"]) ?? ""), call: call.name) + } + + private static func recommendations(_ call: ContractCase.Call) throws -> ErasedRequest { + guard call.method == "get" else { throw Unknown(call: call.name) } + let json = call.args["request"] as? [String: Any] ?? [:] + let request = Rees46.RecommendationRequest( + itemId: Fixtures.string(json["itemId"]), + categoryId: Fixtures.string(json["categoryId"]), + searchQuery: Fixtures.string(json["searchQuery"]), + excludedItemIds: Fixtures.strings(json["excludedItemIds"]), + brands: Fixtures.strings(json["brands"]), + locations: Fixtures.strings(json["locations"]), + limit: Fixtures.int(json["limit"]), + extended: Fixtures.bool(json["extended"]) ?? true, + withLocations: Fixtures.bool(json["withLocations"]) ?? false + ) + return ErasedRequest(try RecommendationsAPIImpl.blockRequest(code: Fixtures.string(call.args["code"]) ?? "", request), call: call.name) + } + + private static func search(_ call: ContractCase.Call) throws -> ErasedRequest { + let args = call.args + switch call.method { + case "blank": + return ErasedRequest(SearchAPIImpl.blankRequest, call: call.name) + case "instant": + return ErasedRequest(try SearchAPIImpl.instantRequest( + query: Fixtures.string(args["query"]) ?? "", + locations: Fixtures.strings(args["locations"]), + excludedMerchants: Fixtures.strings(args["excludedMerchants"]), + excludedBrands: Fixtures.strings(args["excludedBrands"]) + ), call: call.name) + case "full": + let json = args["request"] as? [String: Any] ?? [:] + let request = Rees46.SearchFullRequest( + categoryIds: Fixtures.strings(json["categoryIds"]), + brands: Fixtures.strings(json["brands"]), + excludedBrands: Fixtures.strings(json["excludedBrands"]), + merchants: Fixtures.strings(json["merchants"]), + excludedMerchants: Fixtures.strings(json["excludedMerchants"]), + locations: Fixtures.strings(json["locations"]), + priceMin: Fixtures.double(json["priceMin"]), + priceMax: Fixtures.double(json["priceMax"]), + colors: Fixtures.strings(json["colors"]), + fashionSizes: Fixtures.strings(json["fashionSizes"]), + excludedItemIds: Fixtures.strings(json["excludedItemIds"]), + filters: Fixtures.filters(json["filters"]), + sortBy: Fixtures.sortBy(json["sortBy"]), + sortDir: Fixtures.sortDir(json["sortDir"]), + disableClarification: Fixtures.bool(json["disableClarification"]) ?? false, + categoryLimit: Fixtures.int(json["categoryLimit"]), + brandLimit: Fixtures.int(json["brandLimit"]), + limit: Fixtures.int(json["limit"]), + page: Fixtures.int(json["page"]) + ) + return ErasedRequest(try SearchAPIImpl.fullRequest(query: Fixtures.string(args["query"]) ?? "", request), call: call.name) + case "agentDialog": + return ErasedRequest(SearchAPIImpl.agentDialogRequest( + sessionId: Fixtures.int(args["sessionId"]), + locations: Fixtures.strings(args["locations"]) + ), call: call.name) + case "agent": + return ErasedRequest(try SearchAPIImpl.agentRequest( + message: Fixtures.string(args["message"]) ?? "", + sessionId: Fixtures.int(args["sessionId"]), + locations: Fixtures.strings(args["locations"]) + ), call: call.name) + case "agentEnabled": + // Not a request: the answer of `/init` the instance adopts, and the value it then has. + return ErasedRequest(ApiRequest(method: .get, path: "init") { body in + let object = try JSONSerialization.jsonObject(with: body) as? [String: Any] ?? [:] + let agent = AgentSearchSwitch() + agent.adopt(blankMode: InitResponse(json: object).search.blankMode) + return agent.isOn + }, call: call.name) + default: + throw Unknown(call: call.name) + } + } + + private static func listRequest(_ value: Any?) -> Rees46.ProductsListRequest { + let json = value as? [String: Any] ?? [:] + return Rees46.ProductsListRequest( + categoryIds: Fixtures.strings(json["categoryIds"]), + brands: Fixtures.strings(json["brands"]), + merchants: Fixtures.strings(json["merchants"]), + locations: Fixtures.strings(json["locations"]), + priceMin: Fixtures.double(json["priceMin"]), + priceMax: Fixtures.double(json["priceMax"]), + filters: Fixtures.filters(json["filters"]), + sortBy: Fixtures.sortBy(json["sortBy"]), + sortDir: Fixtures.sortDir(json["sortDir"]), + limit: Fixtures.int(json["limit"]), + page: Fixtures.int(json["page"]) + ) + } + + private static func categoryRequest(_ value: Any?) -> Rees46.CategoryRequest { + let json = value as? [String: Any] ?? [:] + return Rees46.CategoryRequest( + brands: Fixtures.strings(json["brands"]), + locations: Fixtures.strings(json["locations"]), + filters: Fixtures.filters(json["filters"]), + priceMin: Fixtures.double(json["priceMin"]), + priceMax: Fixtures.double(json["priceMax"]), + sortBy: Fixtures.sortBy(json["sortBy"]), + sortDir: Fixtures.sortDir(json["sortDir"]), + limit: Fixtures.int(json["limit"]), + page: Fixtures.int(json["page"]) + ) + } + + private struct Unknown: Error { + let call: String + } + + // MARK: - Beyond the fixtures + + private func value(_ request: ApiRequest, _ json: String, status: Int = 200) -> Result { + let body = Data(json.utf8) + let answer = NetworkClient.Response(status: status, body: body, retryAfter: nil, result: NetworkClient.classify(status: status, body: body)) + return NamespaceRequests.value(of: answer, for: request, call: "test", logger: SdkLogger(shopId: "package-\(UUID().uuidString)", level: .none)) + } + + func test_a_2xx_without_a_body_is_the_empty_value_where_the_method_has_one() throws { + XCTAssertNil(try value(ProductsAPIImpl.infoRequest(itemId: "37"), "").get(), "no product") + let counters = try value(ProductsAPIImpl.countersRequest(itemId: "37"), "").get() + XCTAssertNil(counters.daily) + XCTAssertNil(counters.triggers) + let block = try value(RecommendationsAPIImpl.blockRequest(code: "b", Rees46.RecommendationRequest()), "").get() + XCTAssertEqual(block.products, []) + XCTAssertEqual(block.itemIds, []) + XCTAssertEqual(try value(SearchAPIImpl.blankRequest, "").get().products, []) + XCTAssertEqual(try value(SearchAPIImpl.blankRequest, "[]").get().products, [], "the server's empty object") + // A listing, a collection and a search have no empty value: a body without products is not one. + XCTAssertThrowsError(try value(ProductsAPIImpl.listRequest(Rees46.ProductsListRequest()), "").get()) + XCTAssertThrowsError(try value(CollectionsAPIImpl.collectionRequest(collectionId: "1"), "").get()) + XCTAssertThrowsError(try value(SearchAPIImpl.fullRequest(query: "q", Rees46.SearchFullRequest()), "").get()) + } + + func test_counters_the_answer_does_not_have_are_zero_as_the_released_model_reads_them() throws { + let counters = try value(ProductsAPIImpl.countersRequest(itemId: "37"), #"{"daily": {"view": "4"}, "now": [], "triggers": {}}"#).get() + XCTAssertEqual(counters.daily?.view, 4) + XCTAssertEqual(counters.daily?.cart, 0) + XCTAssertNil(counters.now, "not an object") + XCTAssertEqual(counters.triggers?.priceDrop, 0) + } + + func test_an_answer_that_is_not_an_object_is_decoding() throws { + XCTAssertEqual(value(try ProductsAPIImpl.infoRequest(itemId: "37"), "[]"), .failure(.decoding)) + XCTAssertEqual(value(try RecommendationsAPIImpl.blockRequest(code: "b", Rees46.RecommendationRequest()), #""paused""#), .failure(.decoding)) + XCTAssertEqual(value(SearchAPIImpl.blankRequest, "[1]"), .failure(.decoding)) + } + + func test_a_product_reads_whatever_shape_its_fields_come_in() throws { + let read = try value(ProductsAPIImpl.infoRequest(itemId: "37"), """ + {"id": 37, "name": 5, "url": "", "price": "12.5", "currency": "", "brand": "", + "discount": "12", "is_new": "1", "rating": 4.5, "categories": {"id": "1"}, + "params": [{"values": ["x"]}, {"key": "k"}, 7], "image_url_resized": {"120": 120, "x": {"a": 1}}, + "category_ids": ["1", null, "", 2.0, true]} + """).get() + let product = try XCTUnwrap(read) + XCTAssertEqual(product.id, "37", "a number is its digits") + XCTAssertEqual(product.name, "5") + XCTAssertEqual(product.url, "", "an empty required text is a value") + XCTAssertEqual(product.price, 12.5) + XCTAssertEqual(product.currency, "") + XCTAssertNil(product.brand, "an empty optional text is none") + XCTAssertEqual(product.discountPercent, 12, "discount as a number when there is no discount_percent") + XCTAssertTrue(product.isNew) + XCTAssertNil(product.rating, "not an integer") + XCTAssertNil(product.categories, "not a list") + XCTAssertEqual(product.params, [Rees46.ProductParam(key: "k", values: [])], "a parameter without a key is left out") + XCTAssertEqual(product.resizedImages, ["120": "120"]) + XCTAssertEqual(product.categoryIds, ["1", "2"]) + } + + /// The card's answer (`products/get`) writes `params` as an object, name → `{"searchable", "value"}`, + /// where every other answer has a list of `{"key", "values"}`: the shape of the demo shop's answer. + func test_the_cards_params_object_is_the_list_of_parameters_in_the_answers_order() throws { + let read = try value(ProductsAPIImpl.infoRequest(itemId: "37"), #""" + {"uniqid": "37", "id": "37", "name": "Наушники", "url": "https://shop.example/p/37", "price": 4990, + "currency": "₽", "locations": {"7": {"price": 4990, "stock_quantity": 9}}, "tags": ["a", "{b}"], + "params": { + "merchant": {"searchable": true, "value": ["Shop"]}, + "stickers": {"searchable": true, "value": ["{\"slug\": \"0_0_24\", \"title\": \"0-0-24\"}"]}, + "\u0426вет": {"searchable": true, "value": ["белый"]}, + "Акции": {"searchable": true, "value": ["Товары со скидкой", "Комплектом дешевле"]}, + "is_preorder": {"searchable": true, "value": ["False"]}, + "Время работы, ч": {"searchable": false, "value": [20, 7.5]}, + "Бренд": {"searchable": true, "value": "Apple"}, + "Особенности": ["Изоляция голоса", "Адаптивный эквалайзер"], + "Пустой": {"searchable": true, "value": []}, + "a \"quoted\" name": {"searchable": true, "value": ["x"]} + }, + "barcode": "300252"} + """#).get() + let product = try XCTUnwrap(read) + XCTAssertEqual(product.params, [ + Rees46.ProductParam(key: "merchant", values: ["Shop"]), + Rees46.ProductParam(key: "stickers", values: [#"{"slug": "0_0_24", "title": "0-0-24"}"#]), + Rees46.ProductParam(key: "Цвет", values: ["белый"]), + Rees46.ProductParam(key: "Акции", values: ["Товары со скидкой", "Комплектом дешевле"]), + Rees46.ProductParam(key: "is_preorder", values: ["False"]), + Rees46.ProductParam(key: "Время работы, ч", values: ["20", "7.5"]), + Rees46.ProductParam(key: "Бренд", values: ["Apple"]), + Rees46.ProductParam(key: "Особенности", values: ["Изоляция голоса", "Адаптивный эквалайзер"]), + Rees46.ProductParam(key: "Пустой", values: []), + Rees46.ProductParam(key: #"a "quoted" name"#, values: ["x"]), + ], "every parameter, in the order of the answer") + XCTAssertEqual(product.barcode, "300252", "the fields after params are read") + } + + func test_a_params_object_of_another_answer_is_read_by_name() throws { + let block = try value(RecommendationsAPIImpl.blockRequest(code: "b", Rees46.RecommendationRequest()), """ + {"id": 1, "recommends": [{"id": "37", "name": "n", "url": "u", "price": 1, "currency": "c", + "params": {"Цвет": {"value": ["белый"]}, "merchant": {"value": ["Shop"]}}}]} + """).get() + XCTAssertEqual(block.products.first?.params, [ + Rees46.ProductParam(key: "merchant", values: ["Shop"]), + Rees46.ProductParam(key: "Цвет", values: ["белый"]), + ]) + } + + func test_the_fixtures_answers_are_their_bodies_as_the_file_writes_them() throws { + for name in ["products", "collections", "recommendations", "search"] { + let cases = try ContractFixtures.cases(name, from: .proposed).compactMap { $0["response"] as? [String: Any] } + for response in cases where !(response["body"] is NSNull) && response["body"] != nil { + let bytes = try XCTUnwrap(response[FixtureBodies.key] as? Data, name) + let read = try JSONSerialization.jsonObject(with: bytes, options: .fragmentsAllowed) + XCTAssertEqual(read as? NSObject, response["body"] as? NSObject, name) + } + } + let card = try ContractFixtures.fixture("products", from: .proposed).first { $0.name.contains("params словарём") } + let body = String(decoding: try XCTUnwrap(card?.response?.body), as: UTF8.self) + XCTAssertNotNil(body.range(of: #""Цвет": { "value": [ "графит" ]"#), "the card's params as the file has them") + } + + func test_the_order_of_an_objects_keys_is_read_from_the_answer() { + func keys(_ json: String) -> [String]? { + AnswerKeyOrder.keys(ofObjectAt: "params", in: Data(json.utf8)) + } + XCTAssertEqual(keys(#"{"params": {"b": 1, "a": [1, {"z": "}"}], "c": null}}"#), ["b", "a", "c"]) + XCTAssertEqual(keys(#" { "x" : {"params": {"no": 1}} , "y": "params", "params" : { "\"q\"": true, "\u0430": -1.5e3 } } "#), [#""q""#, "а"]) + XCTAssertEqual(keys(#"{"params": {}}"#), []) + XCTAssertNil(keys(#"{"params": [{"key": "a"}]}"#), "a list") + XCTAssertNil(keys(#"{"other": {"a": 1}}"#), "no params") + XCTAssertNil(keys(#"[{"params": {"a": 1}}]"#), "not an object at the top") + XCTAssertNil(keys(#"{"params": {"a": 1"#), "cut") + XCTAssertNil(keys("")) + } + + func test_a_product_without_a_field_every_product_has_is_left_out() throws { + let fields = [#""id": "1""#, #""name": "a""#, #""url": "u""#, #""price": 1"#, #""currency": "c""#] + for (index, name) in ["id", "name", "url", "price", "currency"].enumerated() { + var rest = fields + rest.remove(at: index) + let partial = "{" + rest.joined(separator: ", ") + "}" + let whole = "{" + fields.joined(separator: ", ") + "}" + let list = try value(ProductsAPIImpl.listRequest(Rees46.ProductsListRequest()), #"{"products": ["# + whole + ", " + partial + "]}").get() + XCTAssertEqual(list.products.count, 1, name) + XCTAssertEqual(value(try ProductsAPIImpl.infoRequest(itemId: "1"), partial).failure, .decoding, "the card without \(name)") + } + let priceless = try value(ProductsAPIImpl.listRequest(Rees46.ProductsListRequest()), #"{"products": [{"id": "1", "name": "a", "url": "u", "price": "free", "currency": "c"}]}"#).get() + XCTAssertEqual(priceless.products, [], "a price that is not a number") + } + + func test_a_listing_reads_brands_filters_and_prices_leniently() throws { + let list = try value(ProductsAPIImpl.listRequest(Rees46.ProductsListRequest()), """ + {"products": [], "brands": [{"name": "A", "count": "2"}, {"name": "B"}], "filters": {"a": {"values": {"x": "2", "y": "many"}}, "b": 3}, + "locations": [{"id": "1", "name": "M"}, {"id": "2"}], "price_range": {"min": 1}, + "price_ranges": [{"from": "1", "to": "2", "count": "3"}, {"to": 5}], "price_median": "7.5"} + """).get() + XCTAssertEqual(list.brands, [Rees46.Brand(name: "A", count: 2)], "a brand without a count is left out") + XCTAssertEqual(list.locations?.map(\.id), ["1"], "a location without a name is left out") + XCTAssertEqual(list.filters?["a"]?.values, ["x": 2]) + XCTAssertNil(list.filters?["b"], "not a facet") + XCTAssertNil(list.priceRange, "a range without its max is none") + XCTAssertEqual(list.priceRanges, [Rees46.PriceInterval(from: 1, to: 2, count: 3), Rees46.PriceInterval(from: 0, to: 5, count: nil)]) + XCTAssertEqual(list.priceMedian, 7.5) + let empty = try value(ProductsAPIImpl.listRequest(Rees46.ProductsListRequest()), #"{"products": [], "filters": [], "brands": {}}"#).get() + XCTAssertEqual(empty.filters, [:], "an empty list is the server's empty object") + XCTAssertNil(empty.brands) + } + + func test_recommendations_by_what_recommends_holds() throws { + let objects = #"{"recommends": [{"id": "1", "name": "a", "url": "u", "price": 1, "currency": "c"}]}"# + let ids = #"{"recommends": ["1", 2, ""]}"# + let request = { try RecommendationsAPIImpl.blockRequest(code: "b", Rees46.RecommendationRequest()) } + XCTAssertEqual(try value(request(), objects).get().itemIds, ["1"]) + XCTAssertEqual(try value(request(), ids).get().itemIds, ["1", "2"]) + XCTAssertEqual(try value(request(), ids).get().products, []) + XCTAssertEqual(try value(request(), #"{"state": "paused", "recommends": "x"}"#).get().products, [], "on pause") + XCTAssertEqual(value(try request(), #"{"recommends": null}"#).failure, .decoding, "neither a list nor on pause") + XCTAssertEqual(value(try request(), #"{"state": "test"}"#).failure, .decoding) + } + + func test_numbers_go_without_a_needless_fraction() { + XCTAssertEqual(CatalogQuery.number(100), "100") + XCTAssertEqual(CatalogQuery.number(100.0), "100") + XCTAssertEqual(CatalogQuery.number(999.5), "999.5") + XCTAssertEqual(CatalogQuery.number(0.1), "0.1") + XCTAssertEqual(CatalogQuery.number(-0.0), "0") + } + + func test_a_segment_of_a_path_is_percent_encoded_slashes_and_letters_of_any_script_included() { + XCTAssertEqual(CatalogQuery.pathSegment("block-1_a.b~c"), "block-1_a.b~c") + XCTAssertEqual(CatalogQuery.pathSegment("a/b c?d#e"), "a%2Fb%20c%3Fd%23e") + XCTAssertEqual(CatalogQuery.pathSegment("й"), "%D0%B9") + XCTAssertEqual(CatalogQuery.pathSegment("a+b"), "a%2Bb") + } + + func test_prices_must_be_finite() { + XCTAssertThrowsError(try ProductsAPIImpl.listRequest(Rees46.ProductsListRequest(priceMin: .nan))) + XCTAssertThrowsError(try ProductsAPIImpl.listRequest(Rees46.ProductsListRequest(priceMax: .infinity))) + XCTAssertNoThrow(try ProductsAPIImpl.listRequest(Rees46.ProductsListRequest(priceMin: 0, priceMax: 0))) + } + + func test_filters_go_as_json_with_sorted_keys_and_plain_slashes() throws { + let request = try ProductsAPIImpl.listRequest(Rees46.ProductsListRequest(filters: ["b": ["1/2"], "a": ["x", "y"]])) + XCTAssertEqual(request.query["filters"], #"{"a":["x","y"],"b":["1/2"]}"#) + } + + func test_a_sort_key_the_server_added_goes_as_it_is() throws { + let request = try ProductsAPIImpl.listRequest(Rees46.ProductsListRequest(sortBy: Rees46.SortBy(rawValue: "popular"))) + XCTAssertEqual(request.query["sort_by"], "popular") + XCTAssertEqual(try SearchAPIImpl.fullRequest(query: "q", Rees46.SearchFullRequest(sortBy: .relevance)).query["sort_by"], "relevance") + } +} + +private extension Result { + + var failure: Failure? { + if case .failure(let error) = self { return error } + return nil + } +} diff --git a/Tests/REES46CoreTests/ClientPackageTests.swift b/Tests/REES46CoreTests/ClientPackageTests.swift new file mode 100644 index 00000000..2f4f5abc --- /dev/null +++ b/Tests/REES46CoreTests/ClientPackageTests.swift @@ -0,0 +1,266 @@ +// +// ClientPackageTests.swift +// REES46CoreTests +// +// The client's namespaces without a server — `profile`, `subscriptions`, `segments` —: the request of +// each call of the proposed fixtures, the calls refused before anything is sent, and what the request +// path makes of each answer. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class ClientPackageTests: XCTestCase { + + private typealias Fixtures = NamespaceFixtures + + // MARK: - The fixtures + + func test_profile_builds_the_fixtures_requests_and_refuses_its_arguments() throws { + try Fixtures.checkRequests("profile", build: Self.profile) + } + + func test_profile_ends_as_the_fixture_says_for_each_answer() throws { + try Fixtures.checkAnswers("profile", build: Self.profile) + } + + func test_subscriptions_build_the_fixtures_requests_and_refuse_its_arguments() throws { + try Fixtures.checkRequests("subscriptions", build: Self.subscriptions) + } + + func test_subscriptions_end_as_the_fixture_says_for_each_answer() throws { + try Fixtures.checkAnswers("subscriptions", build: Self.subscriptions) + } + + func test_segments_build_the_fixtures_requests_and_refuse_its_arguments() throws { + try Fixtures.checkRequests("segments", build: Self.segments) + } + + func test_segments_end_as_the_fixture_says_for_each_answer() throws { + try Fixtures.checkAnswers("segments", build: Self.segments) + } + + func test_the_clients_fixtures_are_proposed_until_the_contract_has_them() throws { + for name in ["profile", "subscriptions", "segments"] { + XCTAssertEqual(try ContractFixtures.load(name, from: .proposed)["contract"] as? String, ContractFixtures.version, name) + XCTAssertTrue(try ContractFixtures.fixture(name, from: .proposed).allSatisfy { $0.call?.namespace == name }, name) + XCTAssertFalse( + FileManager.default.fileExists(atPath: ContractFixtures.url(name).path), + "the contract has \(name).json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one" + ) + } + } + + // MARK: - Calls of the fixtures + + private static func profile(_ call: ContractCase.Call) throws -> ErasedRequest { + switch call.method { + case "get": + return ErasedRequest(ProfileAPIImpl.profileRequest, call: call.name) + case "set": + return ErasedRequest(try ProfileAPIImpl.setRequest(profileRequest(call.args["request"])), call: call.name) + case "getLastOrder": + return ErasedRequest(ProfileAPIImpl.lastOrderRequest, call: call.name) + default: + throw Unknown(call: call.name) + } + } + + private static func subscriptions(_ call: ContractCase.Call) throws -> ErasedRequest { + let args = call.args + let email = Fixtures.string(args["email"]) + let phone = Fixtures.string(args["phone"]) + switch call.method { + case "manage": + return ErasedRequest(try SubscriptionsAPIImpl.manageRequest(updateRequest(args["request"])), call: call.name) + case "check": + return ErasedRequest(SubscriptionsAPIImpl.checkRequest, call: call.name) + case "subscribeForPriceDrop": + return ErasedRequest(try SubscriptionsAPIImpl.priceDropRequest( + itemId: Fixtures.string(args["itemId"]) ?? "", + currentPrice: Fixtures.double(args["currentPrice"]) ?? 0, + email: email, + phone: phone + ), call: call.name) + case "unsubscribeFromPriceDrop": + return ErasedRequest(try SubscriptionsAPIImpl.unsubscribeRequest( + "subscriptions/unsubscribe_from_product_price", + itemIds: Fixtures.strings(args["itemIds"]) ?? [], + email: email, + phone: phone + ), call: call.name) + case "subscribeForBackInStock": + let properties = (args["properties"] as? [String: Any]).map { + Rees46.BackInStockProperties( + fashionSize: Fixtures.string($0["fashionSize"]), + fashionColor: Fixtures.string($0["fashionColor"]), + barcode: Fixtures.string($0["barcode"]) + ) + } + return ErasedRequest(try SubscriptionsAPIImpl.backInStockRequest( + itemId: Fixtures.string(args["itemId"]) ?? "", + properties: properties, + email: email, + phone: phone + ), call: call.name) + case "unsubscribeFromBackInStock": + return ErasedRequest(try SubscriptionsAPIImpl.unsubscribeRequest( + "subscriptions/unsubscribe_from_product_available", + itemIds: Fixtures.strings(args["itemIds"]) ?? [], + email: email, + phone: phone + ), call: call.name) + default: + throw Unknown(call: call.name) + } + } + + private static func segments(_ call: ContractCase.Call) throws -> ErasedRequest { + let args = call.args + switch call.method { + case "add", "remove": + return ErasedRequest(try SegmentsAPIImpl.changeRequest( + "segments/\(call.method)", + segmentId: Fixtures.int(args["segmentId"]) ?? 0, + email: Fixtures.string(args["email"]), + phone: Fixtures.string(args["phone"]) + ), call: call.name) + case "get": + return ErasedRequest(SegmentsAPIImpl.listRequest, call: call.name) + default: + throw Unknown(call: call.name) + } + } + + private static func gender(_ value: Any?) -> Gender? { + (value as? String).flatMap(Gender.init(rawValue:)) + } + + private static func profileRequest(_ value: Any?) -> Rees46.ProfileUpdateRequest { + let json = value as? [String: Any] ?? [:] + return Rees46.ProfileUpdateRequest( + email: Fixtures.string(json["email"]), + phone: Fixtures.string(json["phone"]), + externalId: Fixtures.string(json["externalId"]), + loyaltyId: Fixtures.string(json["loyaltyId"]), + telegramId: Fixtures.string(json["telegramId"]), + fbId: Fixtures.string(json["fbId"]), + vkId: Fixtures.string(json["vkId"]), + firstName: Fixtures.string(json["firstName"]), + lastName: Fixtures.string(json["lastName"]), + gender: gender(json["gender"]), + birthday: Fixtures.string(json["birthday"]), + age: Fixtures.int(json["age"]), + location: Fixtures.string(json["location"]), + kids: (json["kids"] as? [[String: Any]])?.map { + Rees46.ProfileKid(gender: gender($0["gender"]), birthday: Fixtures.string($0["birthday"])) + }, + cars: (json["cars"] as? [[String: Any]])?.map { + Rees46.ProfileCar(brand: Fixtures.string($0["brand"]), model: Fixtures.string($0["model"]), vds: Fixtures.string($0["vds"])) + }, + customProperties: json["customProperties"] as? [String: Any] + ) + } + + private static func updateRequest(_ value: Any?) -> Rees46.SubscriptionsUpdateRequest { + let json = value as? [String: Any] ?? [:] + var request = Rees46.SubscriptionsUpdateRequest( + email: Fixtures.string(json["email"]), + phone: Fixtures.string(json["phone"]), + externalId: Fixtures.string(json["externalId"]), + loyaltyId: Fixtures.string(json["loyaltyId"]), + telegramId: Fixtures.string(json["telegramId"]) + ) + let flags: [String: WritableKeyPath] = [ + "emailBulk": \.emailBulk, "emailChain": \.emailChain, "emailTransactional": \.emailTransactional, + "smsBulk": \.smsBulk, "smsChain": \.smsChain, "smsTransactional": \.smsTransactional, + "webPushBulk": \.webPushBulk, "webPushChain": \.webPushChain, "webPushTransactional": \.webPushTransactional, + "mobilePushBulk": \.mobilePushBulk, "mobilePushChain": \.mobilePushChain, "mobilePushTransactional": \.mobilePushTransactional, + "telegramBulk": \.telegramBulk, "telegramChain": \.telegramChain, "telegramTransactional": \.telegramTransactional, + "whatsappBulk": \.whatsappBulk, "whatsappChain": \.whatsappChain, "whatsappTransactional": \.whatsappTransactional, + "maxBulk": \.maxBulk, "maxChain": \.maxChain, "maxTransactional": \.maxTransactional, + "walletBulk": \.walletBulk, "walletChain": \.walletChain, "walletTransactional": \.walletTransactional + ] + for (name, path) in flags { + request[keyPath: path] = Fixtures.bool(json[name]) + } + return request + } + + private struct Unknown: Error { + let call: String + } + + // MARK: - Beyond the fixtures + + func test_a_2xx_without_a_body_is_the_empty_value() throws { + func answer(_ request: ApiRequest) -> Result { + let empty = NetworkClient.Response(status: 204, body: Data(), retryAfter: nil, result: NetworkClient.classify(status: 204, body: Data())) + return NamespaceRequests.value(of: empty, for: request, call: "test", logger: SdkLogger(shopId: "package", level: .none)) + } + XCTAssertNil(try answer(ProfileAPIImpl.profileRequest).get().id) + XCTAssertEqual(try answer(ProfileAPIImpl.lastOrderRequest).get(), []) + XCTAssertFalse(try answer(SubscriptionsAPIImpl.checkRequest).get().exists) + XCTAssertEqual(try answer(SegmentsAPIImpl.listRequest).get(), []) + XCTAssertNoThrow(try answer(SegmentsAPIImpl.changeRequest("segments/add", segmentId: 1, email: nil, phone: nil)).get()) + } + + func test_custom_properties_must_be_json_values() { + func set(_ properties: [String: Any]) throws -> [String: Any] { + try ProfileAPIImpl.setRequest(Rees46.ProfileUpdateRequest(customProperties: properties)).body + } + XCTAssertThrowsError(try set(["date": Date()])) + XCTAssertThrowsError(try set(["list": [1, Date()]])) + XCTAssertThrowsError(try set(["nan": Double.nan])) + XCTAssertThrowsError(try set(["": "x"])) + XCTAssertThrowsError(try set(["seance": "x"])) + XCTAssertThrowsError(try set(["auto": "x"])) + let nothing: String? = nil + let body = try? set(["none": nothing as Any, "some": Optional("x") as Any, "nested": ["a": nothing as Any]]) + XCTAssertTrue(body?["none"] is NSNull, "nil is JSON null") + XCTAssertEqual(body?["some"] as? String, "x") + XCTAssertTrue((body?["nested"] as? [String: Any])?["a"] is NSNull) + // What the client writes. + XCTAssertNotNil(SafeJSON.data(body ?? [:])) + } + + func test_a_birthday_is_an_existing_day_of_the_years_1000_to_2999() { + XCTAssertNoThrow(try ClientBody.birthday("2000-02-29", "birthday")) + XCTAssertNoThrow(try ClientBody.birthday("1000-01-01", "birthday")) + XCTAssertNoThrow(try ClientBody.birthday("2999-12-31", "birthday")) + XCTAssertThrowsError(try ClientBody.birthday("2001-02-29", "birthday")) + XCTAssertThrowsError(try ClientBody.birthday("1900-02-29", "birthday")) + XCTAssertThrowsError(try ClientBody.birthday("2001-04-31", "birthday")) + XCTAssertThrowsError(try ClientBody.birthday("2001-13-01", "birthday")) + XCTAssertThrowsError(try ClientBody.birthday("2001-2-01", "birthday")) + XCTAssertThrowsError(try ClientBody.birthday("+201-02-01", "birthday")) + XCTAssertThrowsError(try ClientBody.birthday("2001-02-01", "birthday"), "digits of another script") + XCTAssertThrowsError(try ClientBody.birthday("0999-12-31", "birthday"), "the server takes the years 1000 to 2999") + XCTAssertThrowsError(try ClientBody.birthday("3000-01-01", "birthday")) + XCTAssertThrowsError(try ClientBody.birthday("", "birthday")) + } + + func test_the_comparison_with_a_fixture_finds_what_differs() { + XCTAssertFalse(ContractJSON.mismatches(["a": 1, "b": "x"], ["a": 2], at: "result").isEmpty) + XCTAssertFalse(ContractJSON.mismatches(["a": NSNull()], ["a": "x"], at: "result").isEmpty) + XCTAssertFalse(ContractJSON.mismatches(["a": "x"], ["a": NSNull()], at: "result").isEmpty) + XCTAssertFalse(ContractJSON.mismatches(["a": [1, 2]], ["a": [1]], at: "result").isEmpty) + XCTAssertFalse(ContractJSON.mismatches([String: Any](), ["a": 1], at: "result").isEmpty) + XCTAssertFalse(ContractJSON.mismatches(["k": "v"], [String: Any](), at: "result").isEmpty, "{} has no field") + XCTAssertFalse(ContractJSON.mismatches(["a": 1, "b": 2], ["a": 1], at: "result").isEmpty, "a field more") + XCTAssertTrue(ContractJSON.mismatches(["b": NSNull()], ["a": NSNull()], at: "result").isEmpty, "a field without a value is none") + XCTAssertTrue(ContractJSON.mismatches(["a": 19990], ["a": 19990.0], at: "result").isEmpty) + let segment = ContractJSON.of(Rees46.Segment(id: 313, type: nil)) as? [String: Any] + XCTAssertEqual(segment?["id"] as? Double, 313) + XCTAssertTrue(segment?["type"] is NSNull) + XCTAssertTrue(ContractJSON.of(()) is NSNull) + XCTAssertEqual(ContractJSON.of(Gender.female) as? String, "female") + } + + func test_the_gender_goes_as_its_letter_and_reads_from_it() { + XCTAssertEqual(Gender.male.wire, "m") + XCTAssertEqual(Gender.female.wire, "f") + XCTAssertEqual(Gender(wire: "F"), .female) + XCTAssertNil(Gender(wire: "x")) + } +} diff --git a/Tests/REES46CoreTests/ContractFixtures.swift b/Tests/REES46CoreTests/ContractFixtures.swift new file mode 100644 index 00000000..feb1cef2 --- /dev/null +++ b/Tests/REES46CoreTests/ContractFixtures.swift @@ -0,0 +1,282 @@ +// +// ContractFixtures.swift +// REES46CoreTests, REES46Tests +// +// The contract's shared fixtures (`sdk/fixtures/*.json`, `sdk/fixtures/README.md`): the package tests +// and the demo app's tests compile this one file. The contract's files are in +// `Fixtures/contract-/` as they are; `Fixtures/proposed/` holds the SDK's cases, in the same +// format, for a namespace the contract has no file for yet. +// + +import Foundation +@testable import REES46 + +enum ContractFixtures { + + /// The version of the contract the copies are of. + static let version = "0" + + enum Source { + /// `sdk/fixtures` of the contract, copied as it is. + case contract + /// The SDK's own cases in the contract's format, until the contract has the namespace's file. + case proposed + + var folder: String { + switch self { + case .contract: return "contract-\(ContractFixtures.version)" + case .proposed: return "proposed" + } + } + } + + /// The file `name` of `source`, next to this file in the repository. + static func url(_ name: String, extension type: String = "json", from source: Source = .contract) -> URL { + URL(fileURLWithPath: "\(#filePath)") + .deletingLastPathComponent() + .appendingPathComponent("Fixtures/\(source.folder)/\(name).\(type)") + } + + static func load(_ name: String, from source: Source = .contract) throws -> [String: Any] { + let data = try Data(contentsOf: url(name, from: source)) + return try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:] + } + + /// The cases of `name`; the `response` of each holds the bytes of its `body` as the file writes them + /// (`FixtureBodies`). + static func cases(_ name: String, from source: Source = .contract) throws -> [[String: Any]] { + let data = try Data(contentsOf: url(name, from: source)) + var cases = (try JSONSerialization.jsonObject(with: data) as? [String: Any])?["cases"] as? [[String: Any]] ?? [] + let bodies = FixtureBodies.bodies(in: data) + guard bodies.count == cases.count else { return cases } + for (index, body) in bodies.enumerated() { + guard let body = body, var response = cases[index]["response"] as? [String: Any] else { continue } + response[FixtureBodies.key] = body + cases[index]["response"] = response + } + return cases + } + + /// The cases of `name`, typed. + static func fixture(_ name: String, from source: Source = .contract) throws -> [ContractCase] { + try cases(name, from: source).map(ContractCase.init) + } +} + +/// One case of a fixture: a call and the request it sends, or an error instead of it; or the answer the +/// server gives and what the method ends with. +struct ContractCase { + + let name: String + /// `namespace.method` and its arguments by the contract's names. + let call: Call? + /// The request the call sends; only the fields listed count. + let request: Request? + /// The answer of the server; `status` `nil` is none (no network, a timeout). + let response: Response? + /// What the method ends with: `error` (`expectedError`), `result`, or a state of the core. + let expect: [String: Any] + /// The error the call ends with: without a request (`error` of the case), or for the answer + /// (`expect.error`). + let expectedError: ErrorSpec? + + struct Call { + let namespace: String + let method: String + let args: [String: Any] + var name: String { "\(namespace).\(method)" } + } + + struct Request { + let method: String + /// Without the host and the leading slash. + let path: String + let query: [String: String] + let body: [String: Any] + } + + struct Response { + let status: Int? + /// The body as JSON, as the file writes it (`FixtureBodies`); empty for `null` or none. + let body: Data + } + + /// An `SdkError` as a fixture names it: its `type`, and `code` for `http`. + struct ErrorSpec: CustomStringConvertible { + let type: String + let code: Int? + + /// Whether `error` is this one; the message of `invalidArgument` is the SDK's own. + func matches(_ error: Rees46.SdkError) -> Bool { + if case .http(let actual, _) = error { + return type == "http" && (code == nil || code == actual) + } + return type == ContractCase.type(of: error) + } + + var description: String { + code.map { "\(type) \($0)" } ?? type + } + } + + init(_ json: [String: Any]) { + name = json["name"] as? String ?? "?" + if let call = json["call"] as? [String: Any] { + self.call = Call( + namespace: call["namespace"] as? String ?? "", + method: call["method"] as? String ?? "", + args: call["args"] as? [String: Any] ?? [:] + ) + } else { + call = nil + } + if let request = json["request"] as? [String: Any] { + self.request = Request( + method: request["method"] as? String ?? "", + path: request["path"] as? String ?? "", + query: (request["query"] as? [String: Any] ?? [:]).mapValues { "\($0)" }, + body: request["body"] as? [String: Any] ?? [:] + ) + } else { + request = nil + } + if let response = json["response"] as? [String: Any] { + let body = response["body"].flatMap { $0 is NSNull ? nil : $0 } + self.response = Response( + status: response["status"] as? Int, + body: body.flatMap { _ in response[FixtureBodies.key] as? Data } + ?? body.flatMap { try? JSONSerialization.data(withJSONObject: $0, options: .fragmentsAllowed) } ?? Data() + ) + } else { + response = nil + } + expect = json["expect"] as? [String: Any] ?? [:] + let error = json["error"] as? [String: Any] ?? expect["error"] as? [String: Any] + expectedError = error.map { ErrorSpec(type: $0["type"] as? String ?? "", code: $0["code"] as? Int) } + } + + /// The name of `error`'s case, as the fixtures write it. + static func type(of error: Rees46.SdkError) -> String { + switch error { + case .notInitialized: return "notInitialized" + case .shopBlocked: return "shopBlocked" + case .invalidArgument: return "invalidArgument" + case .network: return "network" + case .timeout: return "timeout" + case .http: return "http" + case .decoding: return "decoding" + case .cancelled: return "cancelled" + } + } +} + +/// The bytes of each case's `response.body` as the file writes them. A body read into a dictionary loses +/// the order of its keys, and the SDK keeps the order of some: a product card's `params` is an object of +/// the parameters in the shop's order. +final class FixtureBodies { + + /// Where `ContractFixtures.cases` puts a body's bytes in its `response`. + static let key = "__body_bytes" + + private let bytes: [UInt8] + private var index = 0 + + private init(_ data: Data) { + bytes = [UInt8](data) + } + + /// One element per case of the file's `cases`, `nil` for a case without a body; empty when the file + /// does not read. + static func bodies(in data: Data) -> [Data?] { + let reader = FixtureBodies(data) + var bodies: [Data?] = [] + let read = reader.object { key in + guard key == "cases" else { return reader.skipValue() } + return reader.array { + var body: Data? + let read = reader.object { key in + guard key == "response" else { return reader.skipValue() } + return reader.object { key in + guard key == "body" else { return reader.skipValue() } + reader.skipSpace() + let start = reader.index + guard reader.skipValue() else { return false } + body = Data(reader.bytes[start.. Bool) -> Bool { + guard consume("{") else { return false } + if consume("}") { return true } + repeat { + guard let key = string(), consume(":"), member(key) else { return false } + } while consume(",") + return consume("}") + } + + private func array(_ element: () -> Bool) -> Bool { + guard consume("[") else { return false } + if consume("]") { return true } + repeat { + guard element() else { return false } + } while consume(",") + return consume("]") + } + + private func skipValue() -> Bool { + skipSpace() + guard index < bytes.count else { return false } + switch bytes[index] { + case UInt8(ascii: "{"): + return object { _ in skipValue() } + case UInt8(ascii: "["): + return array { skipValue() } + case UInt8(ascii: "\""): + return string() != nil + default: + let start = index + while index < bytes.count, !",}] \t\r\n".utf8.contains(bytes[index]) { + index += 1 + } + return index > start + } + } + + private func string() -> String? { + skipSpace() + guard index < bytes.count, bytes[index] == UInt8(ascii: "\"") else { return nil } + let start = index + index += 1 + while index < bytes.count { + if bytes[index] == UInt8(ascii: "\\") { + index += 2 + } else if bytes[index] == UInt8(ascii: "\"") { + index += 1 + return (try? JSONSerialization.jsonObject(with: Data(bytes[start.. Bool { + skipSpace() + guard index < bytes.count, bytes[index] == UInt8(ascii: character) else { return false } + index += 1 + return true + } + + private func skipSpace() { + while index < bytes.count, " \t\r\n".utf8.contains(bytes[index]) { + index += 1 + } + } +} diff --git a/Tests/REES46CoreTests/FixtureMatching.swift b/Tests/REES46CoreTests/FixtureMatching.swift new file mode 100644 index 00000000..82093460 --- /dev/null +++ b/Tests/REES46CoreTests/FixtureMatching.swift @@ -0,0 +1,134 @@ +// +// FixtureMatching.swift +// REES46CoreTests +// +// How the package tests hold a namespace's method to the cases of a fixture without a server: the +// request it builds against the case's `request`, and its value of an answer — read by the namespaces' +// one request path — against the case's `expect`. +// + +import XCTest +@testable import REES46 + +/// A case of a fixture with what `ContractCase` does not keep: the lists of a query (`promo_codes[]`). +struct FixtureCase { + let item: ContractCase + /// The case's `request.query` as it is in the file. + let rawQuery: [String: Any] + + var name: String { item.name } + var args: [String: Any] { item.call?.args ?? [:] } + var method: String { item.call?.method ?? "" } + + static func load(_ name: String) throws -> [FixtureCase] { + let raw = try ContractFixtures.cases(name, from: .proposed) + return raw.map { json in + FixtureCase( + item: ContractCase(json), + rawQuery: (json["request"] as? [String: Any])?["query"] as? [String: Any] ?? [:] + ) + } + } +} + +enum FixtureMatching { + + /// `request` is the one the case names: its method and path, and every field it lists — a query's + /// list included —; fields it does not list are not checked. + static func assert(_ request: CoreRequest, is item: FixtureCase, file: StaticString = #filePath, line: UInt = #line) { + guard let expected = item.item.request else { + return XCTFail("\(item.name): the case names no request", file: file, line: line) + } + XCTAssertEqual(request.method.rawValue, expected.method, item.name, file: file, line: line) + XCTAssertEqual(request.path, expected.path, item.name, file: file, line: line) + for (key, value) in item.rawQuery { + if let list = value as? [String] { + XCTAssertEqual(request.queryLists[key], list, "\(item.name): \(key)", file: file, line: line) + } else { + XCTAssertEqual(request.query[key], "\(value)", "\(item.name): \(key)", file: file, line: line) + } + } + for (key, value) in expected.body { + let problems = mismatches(request.body[key], value, at: key) + XCTAssertTrue(problems.isEmpty, "\(item.name): \(problems)", file: file, line: line) + } + } + + /// `make` refuses the case's call with its error, so nothing is sent. + static func assertRefused(_ item: FixtureCase, file: StaticString = #filePath, line: UInt = #line, _ make: () throws -> T) { + do { + _ = try make() + XCTFail("\(item.name): built, expected \(String(describing: item.item.expectedError))", file: file, line: line) + } catch let error as Rees46.SdkError { + XCTAssertTrue(item.item.expectedError?.matches(error) == true, "\(item.name): \(error)", file: file, line: line) + } catch { + XCTFail("\(item.name): not an SdkError: \(error)", file: file, line: line) + } + } + + /// What the method ends with for the case's answer, read as the namespaces read every answer. + static func outcome(of item: FixtureCase, for request: ApiRequest, call: String) throws -> Result { + let response = try XCTUnwrap(item.item.response, item.name) + let status = try XCTUnwrap(response.status, item.name) + let answer = NetworkClient.Response( + status: status, body: response.body, retryAfter: nil, + result: NetworkClient.classify(status: status, body: response.body, path: request.path) + ) + let logger = SdkLogger(shopId: "package-\(UUID().uuidString)", level: .none) + return NamespaceRequests.value(of: answer, for: request, call: call, logger: logger) + } + + /// `result` ends as the case expects: its error, or a value whose JSON by the contract's names (`json`) + /// has what `expect.result` lists. + static func assert( + _ result: Result, + as item: FixtureCase, + json: (Value) -> Any, + file: StaticString = #filePath, + line: UInt = #line + ) { + switch result { + case .success(let value): + XCTAssertNil(item.item.expectedError, "\(item.name): \(value)", file: file, line: line) + let problems = mismatches(json(value), item.item.expect["result"], at: "result") + XCTAssertTrue(problems.isEmpty, "\(item.name): \(problems)", file: file, line: line) + case .failure(let error): + XCTAssertTrue( + item.item.expectedError?.matches(error) == true, + "\(item.name): \(error), expected \(String(describing: item.item.expectedError))", + file: file, line: line + ) + } + } + + /// Where `actual` differs from `expected`: an object of `expected` lists the fields to check, a list + /// has as many elements in the same order, `null` is no value, numbers and booleans compare by value. + static func mismatches(_ actual: Any?, _ expected: Any?, at path: String) -> [String] { + let actual = actual.flatMap { $0 is NSNull ? nil : $0 } + switch expected { + case nil, is NSNull: + return actual == nil ? [] : ["\(path): \(String(describing: actual)), expected none"] + case let object as [String: Any]: + guard let fields = actual as? [String: Any] else { return ["\(path): \(String(describing: actual)), expected an object"] } + return object.keys.sorted().flatMap { mismatches(fields[$0], object[$0], at: "\(path).\($0)") } + case let list as [Any]: + guard let elements = actual as? [Any] else { return ["\(path): \(String(describing: actual)), expected a list"] } + guard elements.count == list.count else { return ["\(path): \(elements.count) elements, expected \(list.count)"] } + return zip(elements, list).enumerated().flatMap { mismatches($0.element.0, $0.element.1, at: "\(path)[\($0.offset)]") } + case let number as NSNumber: + guard let value = actual as? NSNumber, abs(value.doubleValue - number.doubleValue) < 1e-9 else { + return ["\(path): \(String(describing: actual)), expected \(number)"] + } + return [] + case let text as String: + return actual as? String == text ? [] : ["\(path): \(String(describing: actual)), expected \(text)"] + default: + return ["\(path): cannot compare \(String(describing: expected))"] + } + } + + /// `value`, or `NSNull` for none: a field of a result's JSON. + static func field(_ value: Any?) -> Any { + value ?? NSNull() + } +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/README.md b/Tests/REES46CoreTests/Fixtures/proposed/README.md new file mode 100644 index 00000000..109ed609 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/README.md @@ -0,0 +1,37 @@ +# Proposed fixtures + +Cases the SDK is tested by for a namespace the contract has no fixture file for yet, written in the format of the +contract's fixtures (`sdk/fixtures/README.md`) and marked with the contract version they follow. They are not the +contract's: when `sdk/fixtures` gets the namespace's file, its copy goes into `contract-/` and the file here +is removed. + +- `cart.json` — `cart.get` (`sdk/contract/cart.md`), the same cases the Android SDK tests by. In `expect`, `result` + is the method's value by the contract's field names; `response.status: null` is no answer, which the tests play as a + connection that is never made (`network`). +- `notifications.json` — the events of pushes and `setPushToken` (`sdk/contract/notifications.md`), the same cases the + Android SDK tests by. A case with `platform` (`ios`, `android`) is of that platform only: the platforms send a push + token with different `platform` and `push_provider`, and each refuses the other's provider. `expect.result: null` is a + success without a value. +- `stories.json` — `stories.get` (`sdk/contract/stories.md`). In `expect.result` an element of a slide is an object with + its `type` — `button`, `product`, `products`, `textBlock` — and its fields. +- `predict.json` — `predict.getProbabilityToPurchase` (`sdk/contract/predict.md`). +- `loyalty.json` — `loyalty.join`, `getStatus`, `getPromotions` (`sdk/contract/loyalty.md`). A query field whose value + is a list goes as a list of Rails: `promo_codes[]=A&promo_codes[]=B`. +- `sliders.json` — `sliders.get` (`sdk/contract/sliders.md`) and the banner events of `tracking` that go with it, + `bannerView` and `bannerClick`, until the contract's `tracking.json` has them. +- `reviews.json` — the nine methods of `reviews` (`sdk/contract/reviews.md`): the request of each call, or the + argument it refuses, and what each answer ends with. A path under `api/v3/` goes to `appDomain`, any other to + `apiDomain`, as the contract's table of methods says; the format has no field for the host. + +In `expect.result` an object lists the fields the case checks; `null` is a field without a value. + +- `products.json`, `collections.json`, `recommendations.json`, `search.json` — the catalog (`sdk/contract/products.md`, + `collections.md`, `recommendations.md`, `search.md`): the Android SDK's files as they are, so both SDKs test the same + cases. In `call.args`, a request model is an object by the contract's field names, a value of a set by its name in + code (`salesRate`). A `result`, and a request's own fields in `query` or `body`, are compared whole, as the Android + SDK compares them: a field without a value counts as missing on either side. +- `search.json` here is the Android SDK's file with the search agent (`agentDialog`, `agent`; DEV-4620) after the + catalog's cases. The agent's path is on the host of API v3, `appDomain`, which the format does not name. +- `profile.json`, `subscriptions.json`, `segments.json` — the client (`sdk/contract/profile.md`, `subscriptions.md`, + `segments.md`): the Android SDK's files as they are, compared as the catalog's. A method without a value expects + `"result": null`. diff --git a/Tests/REES46CoreTests/Fixtures/proposed/cart.json b/Tests/REES46CoreTests/Fixtures/proposed/cart.json new file mode 100644 index 00000000..cff116f9 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/cart.json @@ -0,0 +1,74 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "request": { "method": "GET", "path": "products/cart", "query": {} } + }, + { + "name": "корзина в форме data.items", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "data": { "items": [ { "uniqid": "37", "quantity": 2 }, { "uniqid": "38", "quantity": 1 } ] } } }, + "expect": { "result": [ { "id": "37", "quantity": 2 }, { "id": "38", "quantity": 1 } ] } + }, + { + "name": "корзина в форме payload.cart_items из документации", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", "payload": { "cart_items": [ { "uniqid": "37", "quantity": 2 } ] } } }, + "expect": { "result": [ { "id": "37", "quantity": 2 } ] } + }, + { + "name": "пустая корзина", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "data": { "items": [] } } }, + "expect": { "result": [] } + }, + { + "name": "числа строкой, позиция без uniqid пропускается, без quantity — 1, незнакомые поля не мешают", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "data": { "items": [ { "uniqid": 37, "quantity": "3", "price": 999.5 }, + { "quantity": 1 }, + { "uniqid": "", "quantity": 1 }, + { "uniqid": "38" }, + { "uniqid": "39", "quantity": null } ], + "total": 4 } } }, + "expect": { "result": [ { "id": "37", "quantity": 3 }, { "id": "38", "quantity": 1 }, { "id": "39", "quantity": 1 } ] } + }, + { + "name": "404 — неизвестный did", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 404, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "403 — отказ услуги или магазина, состояние SDK не меняется", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 403, "body": null }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "ответ ни в одной из двух форм", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "items": [ { "uniqid": "37", "quantity": 1 } ] } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "cart", "method": "get", "args": {} }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/collections.json b/Tests/REES46CoreTests/Fixtures/proposed/collections.json new file mode 100644 index 00000000..aad1209b --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/collections.json @@ -0,0 +1,62 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "request": { "method": "GET", "path": "collection/12", "query": {} } + }, + { + "name": "get: идентификатор в пути URL-кодирован", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "a b/c" } }, + "request": { "method": "GET", "path": "collection/a%20b%2Fc", "query": {} } + }, + { + "name": "get с пустым collectionId", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "товары коллекции", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": 200, + "body": { "products": [ { "id": "37", "group_id": "_37_", "name": "Кроссовки", "url": "https://shop.example/p/37", + "price": 4990, "currency": "₽", "oldprice": 5990, + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5" } ] }, + { "id": "38", "name": "Без цены", "url": "https://shop.example/p/38", "currency": "₽" } ] } }, + "expect": { "result": { "products": [ { "id": "37", "groupId": "_37_", "name": "Кроссовки", "url": "https://shop.example/p/37", + "price": 4990, "currency": "₽", "oldPrice": 5990, "isNew": false, + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5" } ] } ] } } + }, + { + "name": "пустая коллекция", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": 200, "body": { "products": [] } }, + "expect": { "result": { "products": [] } } + }, + { + "name": "400 — неизвестная или неактивная коллекция", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "999" } }, + "response": { "status": 400, "body": { "status": "error", "message": "Collection with id 999 was not found" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "ответ без products", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": 200, "body": {} }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "collections", "method": "get", "args": { "collectionId": "12" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/loyalty.json b/Tests/REES46CoreTests/Fixtures/proposed/loyalty.json new file mode 100644 index 00000000..e535434d --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/loyalty.json @@ -0,0 +1,183 @@ +{ + "contract": "0", + "cases": [ + { + "name": "join со всеми полями", + "call": { "namespace": "loyalty", "method": "join", + "args": { "phone": "+79991234567", "firstName": "Anna", "lastName": "Ivanova", "gender": "female", "birthday": "1990-05-17" } }, + "request": { "method": "POST", "path": "loyalty/members/join", + "body": { "phone": "+79991234567", "first_name": "Anna", "last_name": "Ivanova", "gender": "f", "birthday": "1990-05-17" } } + }, + { + "name": "join с телефоном и полом: телефон уходит как есть", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "89991234567", "gender": "male" } }, + "request": { "method": "POST", "path": "loyalty/members/join", "body": { "phone": "89991234567", "gender": "m" } } + }, + { + "name": "join с пустым phone", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "join с birthday не YYYY-MM-DD", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567", "birthday": "17.05.1990" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "join: birthday — несуществующая дата; непонятную дату сервер стёр бы", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567", "birthday": "1990-02-30" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "join: пустой birthday", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567", "birthday": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "join — новый участник", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", "payload": { "message": "Member is registered successfully", "identifier": "79991234567" } } }, + "expect": { "result": { "identifier": "79991234567" } } + }, + { + "name": "join — телефон уже зарегистрирован, тот же идентификатор (В45)", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", "payload": { "message": "Member is already registered", "identifier": 79991234567 } } }, + "expect": { "result": { "identifier": "79991234567" } } + }, + { + "name": "join — 403, у магазина выключены методы лояльности с фронта (В17, В18)", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567" } }, + "response": { "status": 403, "body": { "status": "error", "message": "Shop not found by secret key" } }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "join — ответ без identifier", + "call": { "namespace": "loyalty", "method": "join", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "message": "Member is registered successfully" } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getStatus", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "request": { "method": "GET", "path": "loyalty/members/status", "query": { "identifier": "+79991234567" } } + }, + { + "name": "getStatus с пустым phone", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getStatus — участник на уровне", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "member": true, "level": { "name": "Gold", "code": "level_gold", "expiration_date": "2028-01-01" } } } }, + "expect": { "result": { "isMember": true, "level": { "code": "level_gold", "name": "Gold", "expirationDate": "2028-01-01" } } } + }, + { + "name": "getStatus — базовый уровень: level пусто", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "member": true, "level": { "name": null, "code": null, "expiration_date": null } } } }, + "expect": { "result": { "isMember": true, "level": null } } + }, + { + "name": "getStatus — не участник", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "member": false, "level": { "name": null, "code": null, "expiration_date": null } } } }, + "expect": { "result": { "isMember": false, "level": null } } + }, + { + "name": "getStatus — 400, неверный идентификатор", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "12" } }, + "response": { "status": 400, "body": { "status": "error", "message": "Incorrect member identifier" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "getStatus — 404, лояльность не настроена", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": 404, "body": { "status": "error", "message": "Loyalty program not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "getPromotions без параметров", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "request": { "method": "GET", "path": "loyalty/promos/for-client", "query": {} } + }, + { + "name": "getPromotions со всеми параметрами: промокоды — массивом Rails", + "call": { "namespace": "loyalty", "method": "getPromotions", + "args": { "locationId": "msk-1", "promoCodes": [ "SPRING", "VIP" ], "chargeBonuses": true, "currentTime": "18:30" } }, + "request": { "method": "GET", "path": "loyalty/promos/for-client", + "query": { "location_id": "msk-1", "promo_codes[]": [ "SPRING", "VIP" ], "charge_bonuses": "true", "current_time": "18:30" } } + }, + { + "name": "getPromotions с currentTime не HH:MM", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": { "currentTime": "25:00" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getPromotions с пустым промокодом", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": { "promoCodes": [ "SPRING", "" ] } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getPromotions — акции из документации; id больше 2^31", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "promotions": [ + { "id": 33, "name": "Half price", "start_date": "2026-01-01", "finish_date": "2026-01-14", "stream": "ios", + "badge_label": "-50%", "badge_color": "#AABB00", "description": "On one product", + "reward_type": "discount", + "reward_rules": { "amount_type": "percentage", "reward_type": "discount", "amount_value": 100, + "include_products": [ { "sku": { "values": "300275", "operator": "in" } } ] } }, + { "id": 3000000012, "name": "1+1=3", "start_date": "2026-01-01", "finish_date": "2026-01-14", "stream": null, + "badge_label": "1+1=3", "badge_color": "#AA0000", "description": null, + "reward_type": "bonuses_earn", "reward_rules": {} }, + { "id": "7", "name": "Spend bonuses", "reward_type": "bonuses_usage" } ] } } }, + "expect": { "result": [ + { "id": 33, "name": "Half price", "description": "On one product", "startDate": "2026-01-01", "finishDate": "2026-01-14", + "stream": "ios", "badgeLabel": "-50%", "badgeColor": "#AABB00", "rewardType": "discount" }, + { "id": 3000000012, "name": "1+1=3", "description": null, "stream": null, "badgeLabel": "1+1=3", "rewardType": "bonusesEarn" }, + { "id": 7, "name": "Spend bonuses", "startDate": null, "finishDate": null, "badgeColor": null, "rewardType": "bonusesUsage" } ] } + }, + { + "name": "getPromotions — незнакомый reward_type даёт пустое поле", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", "payload": { "promotions": [ { "id": 5, "name": "Gift", "reward_type": "gift" } ] } } }, + "expect": { "result": [ { "id": 5, "name": "Gift", "rewardType": null } ] } + }, + { + "name": "getPromotions — нет подходящих акций", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "promotions": [] } } }, + "expect": { "result": [] } + }, + { + "name": "getPromotions — 402, услуга лояльности выключена", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 402, "body": { "status": "error", "message": "Loyalty service is disabled" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "loyalty", "method": "getPromotions", "args": {} }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "loyalty", "method": "getStatus", "args": { "phone": "+79991234567" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/notifications.json b/Tests/REES46CoreTests/Fixtures/proposed/notifications.json new file mode 100644 index 00000000..ac446c30 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/notifications.json @@ -0,0 +1,120 @@ +{ + "contract": "0", + "cases": [ + { + "name": "trackDelivered", + "call": { "namespace": "notifications", "method": "trackDelivered", "args": { "code": "m-delivered", "type": "bulk" } }, + "request": { "method": "POST", "path": "track/delivered", "body": { "code": "m-delivered", "type": "bulk" } } + }, + { + "name": "trackOpened", + "call": { "namespace": "notifications", "method": "trackOpened", "args": { "code": "m-opened", "type": "chain" } }, + "request": { "method": "POST", "path": "track/opened", "body": { "code": "m-opened", "type": "chain" } } + }, + { + "name": "trackClicked", + "call": { "namespace": "notifications", "method": "trackClicked", "args": { "code": "m-clicked", "type": "transactional" } }, + "request": { "method": "POST", "path": "track/clicked", "body": { "code": "m-clicked", "type": "transactional" } } + }, + { + "name": "trackClosed с типом digest", + "call": { "namespace": "notifications", "method": "trackClosed", "args": { "code": "m-closed", "type": "digest" } }, + "request": { "method": "POST", "path": "track/closed", "body": { "code": "m-closed", "type": "digest" } } + }, + { + "name": "trackDelivered с пустым code", + "call": { "namespace": "notifications", "method": "trackDelivered", "args": { "code": "", "type": "bulk" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "trackClicked с пустым type", + "call": { "namespace": "notifications", "method": "trackClicked", "args": { "code": "m-1", "type": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "setPushToken FCM на Android", + "platform": "android", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "fcm-token-1", "provider": "fcm" } }, + "request": { "method": "POST", "path": "mobile_push_tokens", + "body": { "token": "fcm-token-1", "platform": "android", "push_provider": "firebase" } } + }, + { + "name": "setPushToken HMS на Android", + "platform": "android", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "hms-token-1", "provider": "hms" } }, + "request": { "method": "POST", "path": "mobile_push_tokens", + "body": { "token": "hms-token-1", "platform": "android", "push_provider": "huawei" } } + }, + { + "name": "setPushToken APNs на iOS", + "platform": "ios", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "apns-token-1", "provider": "apns" } }, + "request": { "method": "POST", "path": "mobile_push_tokens", "body": { "token": "apns-token-1", "platform": "ios" } } + }, + { + "name": "setPushToken FCM на iOS", + "platform": "ios", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "fcm-token-2", "provider": "fcm" } }, + "request": { "method": "POST", "path": "mobile_push_tokens", "body": { "token": "fcm-token-2", "platform": "ios_firebase" } } + }, + { + "name": "setPushToken APNs на Android", + "platform": "android", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "apns-token-2", "provider": "apns" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "setPushToken HMS на iOS", + "platform": "ios", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "hms-token-2", "provider": "hms" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "setPushToken с пустым токеном", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "", "provider": "fcm" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "setPushToken: 200 success", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-200", "provider": "fcm" } }, + "response": { "status": 200, "body": { "status": "success" } }, + "expect": { "result": null } + }, + { + "name": "setPushToken: 2xx без тела — успех", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-empty", "provider": "fcm" } }, + "response": { "status": 200, "body": null }, + "expect": { "result": null } + }, + { + "name": "setPushToken: 400 — клиент не найден", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-400", "provider": "fcm" } }, + "response": { "status": 400, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "setPushToken: 403 — неизвестный или отключённый магазин, пустое тело", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-403", "provider": "fcm" } }, + "response": { "status": 403, "body": null }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "setPushToken: 404 — нет shop_id, пустое тело", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-404", "provider": "fcm" } }, + "response": { "status": 404, "body": null }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "setPushToken: 2xx со status error", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-2xx-error", "provider": "fcm" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "setPushToken: нет ответа", + "call": { "namespace": "notifications", "method": "setPushToken", "args": { "token": "token-no-answer", "provider": "fcm" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/predict.json b/Tests/REES46CoreTests/Fixtures/proposed/predict.json new file mode 100644 index 00000000..e659116e --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/predict.json @@ -0,0 +1,82 @@ +{ + "contract": "0", + "cases": [ + { + "name": "getProbabilityToPurchase — API v3 на appDomain (В42)", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "request": { "method": "GET", "path": "api/v3/cdp/users/probability-to-purchase", "query": {} } + }, + { + "name": "покупатель найден", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "probability": 0.42, "client_id": 12345 } } }, + "expect": { "result": { "probability": 0.42, "clientId": "12345" } } + }, + { + "name": "покупатель найден, событий нет; client_id больше 2^31", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "probability": 0.0, "client_id": 3000000001 } } }, + "expect": { "result": { "probability": 0, "clientId": "3000000001" } } + }, + { + "name": "покупатель не найден — успех с пустым clientId", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "probability": 0.0, "client_id": null } } }, + "expect": { "result": { "probability": 0, "clientId": null } } + }, + { + "name": "ответ без payload — форма старого пути", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "probability": 0.42, "client_id": 12345 } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет probability", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "client_id": 12345 } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "probability не число", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "probability": "high", "client_id": 12345 } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "400 — нет did", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 400, "body": { "status": "fail", "message": "Invalid request parameters" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "402 — у магазина не подключена услуга cdp или он не оплачен", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 402, "body": { "status": "fail", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "403 — магазин неактивен или ограничен", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 403, "body": { "status": "fail", "message": "Access denied" } }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "404 — неизвестный магазин", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 404, "body": { "status": "fail", "message": "Resource not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "predict", "method": "getProbabilityToPurchase", "args": {} }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/products.json b/Tests/REES46CoreTests/Fixtures/proposed/products.json new file mode 100644 index 00000000..01c492b4 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/products.json @@ -0,0 +1,276 @@ +{ + "contract": "0", + "cases": [ + { + "name": "getInfo", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "request": { "method": "GET", "path": "products/get", "query": { "item_id": "37" } } + }, + { + "name": "getInfo с пустым itemId", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList без запроса — первая страница всего каталога", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "request": { "method": "GET", "path": "products", "query": {} } + }, + { + "name": "getList со всеми полями: списки через запятую без пробелов, числа без лишних нулей, filters JSON-строкой", + "call": { "namespace": "products", "method": "getList", + "args": { "request": { "categoryIds": [ "1", "2" ], "brands": [ "Nike", "Adidas" ], "merchants": [ "m1" ], + "locations": [ "msk", "spb" ], "priceMin": 100, "priceMax": 999.5, + "filters": { "color": [ "red", "blue" ] }, + "sortBy": "price", "sortDir": "asc", "limit": 20, "page": 2 } } }, + "request": { "method": "GET", "path": "products", + "query": { "categories": "1,2", "brands": "Nike,Adidas", "merchants": "m1", "locations": "msk,spb", + "price_min": "100", "price_max": "999.5", "filters": "{\"color\":[\"red\",\"blue\"]}", + "sort_by": "price", "sort_dir": "asc", "limit": "20", "page": "2" } } + }, + { + "name": "getList: пустые списки и словарь не уходят", + "call": { "namespace": "products", "method": "getList", + "args": { "request": { "categoryIds": [], "brands": [], "filters": {} } } }, + "request": { "method": "GET", "path": "products", "query": {} } + }, + { + "name": "getList: ключ сортировки не из списка констант уходит как есть", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "sortBy": "popular" } } }, + "request": { "method": "GET", "path": "products", "query": { "sort_by": "popular" } } + }, + { + "name": "getList с limit 0", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "limit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList с page 0", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "page": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList с отрицательной ценой", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "priceMin": -1 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList с priceMin больше priceMax", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "priceMin": 500, "priceMax": 100 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getList с сортировкой relevance — только для search.full", + "call": { "namespace": "products", "method": "getList", "args": { "request": { "sortBy": "relevance" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getCounters", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "37" } }, + "request": { "method": "GET", "path": "products/counters", "query": { "item": "37" } } + }, + { + "name": "getCounters с пустым itemId", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getCategory — делегат getList с categories", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "12" } }, + "request": { "method": "GET", "path": "products", "query": { "categories": "12" } } + }, + { + "name": "getCategory с запросом", + "call": { "namespace": "products", "method": "getCategory", + "args": { "categoryId": "12", + "request": { "brands": [ "Nike" ], "locations": [ "msk" ], "filters": { "size": [ "42" ] }, + "priceMin": 0, "priceMax": 5000, "sortBy": "sales_rate", "sortDir": "desc", + "limit": 30, "page": 1 } } }, + "request": { "method": "GET", "path": "products", + "query": { "categories": "12", "brands": "Nike", "locations": "msk", "filters": "{\"size\":[\"42\"]}", + "price_min": "0", "price_max": "5000", "sort_by": "sales_rate", "sort_dir": "desc", + "limit": "30", "page": "1" } } + }, + { + "name": "getCategory с пустым categoryId", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getCategory с сортировкой relevance", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "12", "request": { "sortBy": "relevance" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getInfo: карточка товара — id из uniqid, цены строками, discount логическое, level строкой и числом, пустое описание — null, params словарём в порядке ответа", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "9922" } }, + "response": { "status": 200, + "body": { "name": "Скамья Жасмин", "is_available": true, "description": "", + "price": "10760", "price_full": 10760, "price_formatted": "10 760 ₽", "price_full_formatted": "10 760.00 ₽", + "currency": "₽", "url": "https://shop.example/p/9922", "url_handle": "/p/9922", + "picture": "https://shop.example/i/9922-180.webp", "image_url": "https://shop.example/i/9922.webp", + "image_url_handle": "/i/9922.webp", "image_url_resized": {}, "category_ids": [], "brand": "БРВ Мебель", + "sales_rate": null, "relative_sales_rate": null, + "categories": [ { "id": "23", "name": "Прихожие", "url": "https://shop.example/c/23", "branch": 1, "level": 1 }, + { "parent_id": "23", "id": "12023", "name": "Скамьи", "url": "https://shop.example/c/12023", "level": "2" } ], + "params": { "Цвет": { "value": [ "графит" ], "searchable": true }, "Ширина": { "value": [ 100, 120.5 ], "searchable": false } }, + "group_id": "9921", "id": "9922", "uniqid": "9922", "widgetable": true, "ignored": false, "locations": {}, + "model": "LAK", "barcode": "УТ-70041501", "oldprice": "13450", "discount": true, "discount_percent": 20 } }, + "expect": { "result": { "id": "9922", "groupId": "9921", "name": "Скамья Жасмин", "brand": "БРВ Мебель", "model": "LAK", + "barcode": "УТ-70041501", "url": "https://shop.example/p/9922", + "imageUrl": "https://shop.example/i/9922.webp", "picture": "https://shop.example/i/9922-180.webp", + "resizedImages": {}, "price": 10760, "priceFormatted": "10 760 ₽", "priceFull": 10760, + "priceFullFormatted": "10 760.00 ₽", "oldPrice": 13450, "currency": "₽", "discountPercent": 20, + "isNew": false, "categoryIds": [], + "categories": [ { "id": "23", "name": "Прихожие", "url": "https://shop.example/c/23", "level": 1 }, + { "id": "12023", "name": "Скамьи", "url": "https://shop.example/c/12023", "parentId": "23", "level": 2 } ], + "params": [ { "key": "Цвет", "values": [ "графит" ] }, { "key": "Ширина", "values": [ "100", "120.5" ] } ] } } + }, + { + "name": "getInfo: id только в uniqid", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "uniqid": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽" } }, + "expect": { "result": { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽", "isNew": false } } + }, + { + "name": "getInfo: неизвестный товар — 200 {}, результат пустой", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "404" } }, + "response": { "status": 200, "body": {} }, + "expect": { "result": null } + }, + { + "name": "getInfo: непустой ответ без uniqid и id", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": { "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getInfo: 2xx со status error", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getInfo: 500", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": 500, "body": null }, + "expect": { "error": { "type": "http", "code": 500 } } + }, + { + "name": "getInfo: нет ответа", + "call": { "namespace": "products", "method": "getInfo", "args": { "itemId": "37" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + }, + { + "name": "getList: страница с фасетами; params списком; товар без обязательного поля пропускается, бренд без количества пропускается", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "response": { "status": 200, + "body": { "products_total": "2", + "products": [ { "id": "37", "group_id": "_37_", "name": "Кроссовки", "url": "https://shop.example/p/37", + "price": 4990, "price_formatted": "4 990 ₽", "oldprice": 0, "oldprice_full": 0, + "currency": "₽", "discount": 15, "is_new": true, "rating": 4, "stock_quantity": "7", + "deeplink_android": "shop://p/37", "deeplink_ios": "shop://p/37", + "image_url_resized": { "120": "https://shop.example/i/37-120.webp", "original": "https://shop.example/i/37.webp" }, + "sales_rate": 120, "relative_sales_rate": 0.5, + "category_ids": [ "5", 6 ], "params": [ { "key": "Размер", "values": [ 42, "43" ] } ] }, + { "id": "38", "name": "Без валюты", "url": "https://shop.example/p/38", "price": 100 } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "parent": "1", "count": 2, "alias": "obuv" } ], + "brands": [ { "name": "Nike", "count": 3, "picture": "https://shop.example/b/nike.png" }, { "name": "Без количества" } ], + "locations": [ { "id": "msk", "name": "Москва", "type": "city" } ], + "filters": { "Цвет": { "count": 3, "priority": 1, "values": { "красный": 2, "синий": "1" } }, + "Вес": { "count": 2, "ranges": { "min": 0.5, "max": "10" } } }, + "price_range": { "min": 100, "max": "9990" }, + "price_ranges": [ { "to": 1000, "count": 2 }, { "from": 1000, "count": 1 } ], + "price_median": "1500" } }, + "expect": { "result": { "productsTotal": 2, + "products": [ { "id": "37", "groupId": "_37_", "name": "Кроссовки", "url": "https://shop.example/p/37", + "price": 4990, "priceFormatted": "4 990 ₽", "currency": "₽", "discountPercent": 15, + "isNew": true, "rating": 4, "stockQuantity": 7, + "deeplinkAndroid": "shop://p/37", "deeplinkIos": "shop://p/37", + "resizedImages": { "120": "https://shop.example/i/37-120.webp", "original": "https://shop.example/i/37.webp" }, + "salesRate": 120, "relativeSalesRate": 0.5, "categoryIds": [ "5", "6" ], + "params": [ { "key": "Размер", "values": [ "42", "43" ] } ] } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "parentId": "1", "count": 2, "alias": "obuv" } ], + "brands": [ { "name": "Nike", "count": 3 } ], + "locations": [ { "id": "msk", "name": "Москва", "type": "city" } ], + "filters": { "Цвет": { "count": 3, "priority": 1, "values": { "красный": 2, "синий": 1 } }, + "Вес": { "count": 2, "min": 0.5, "max": 10 } }, + "priceRange": { "min": 100, "max": 9990 }, + "priceRanges": [ { "from": 0, "to": 1000, "count": 2 }, { "from": 1000, "count": 1 } ], + "priceMedian": 1500 } } + }, + { + "name": "getList: пустая страница", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "response": { "status": 200, "body": { "products_total": 0, "products": [] } }, + "expect": { "result": { "productsTotal": 0, "products": [] } } + }, + { + "name": "getList: ответ без products", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "response": { "status": 200, "body": { "products_total": 0 } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getList: 403", + "call": { "namespace": "products", "method": "getList", "args": {} }, + "response": { "status": 403, "body": null }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "getCounters: числа строкой", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "daily": { "view": 10, "cart": "2", "purchase": 1 }, "now": { "view": 1, "cart": 0, "purchase": 0 }, + "triggers": { "back_in_stock": 3, "price_drop": 4 } } }, + "expect": { "result": { "daily": { "view": 10, "cart": 2, "purchase": 1 }, "now": { "view": 1, "cart": 0, "purchase": 0 }, + "triggers": { "backInStock": 3, "priceDrop": 4 } } } + }, + { + "name": "getCounters: пустой ответ", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": {} }, + "expect": { "result": {} } + }, + { + "name": "getCounters: ответ не объект", + "call": { "namespace": "products", "method": "getCounters", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": [] }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getCategory: товары и фасеты категории; поля вне CategoryResponse не попадают в результат", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "5" } }, + "response": { "status": 200, + "body": { "products_total": 1, + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": "4990.50", "currency": "₽", + "oldprice": 5990, "oldprice_formatted": "5 990 ₽", "oldprice_full": 5990.5, "oldprice_full_formatted": "5 990.50 ₽" } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "count": 1 } ], + "brands": [ { "name": "Nike", "count": 1 } ], + "locations": [ { "id": "msk", "name": "Москва" } ], + "industrial_filters": { "colors": [ { "color": "red", "count": 1 } ] }, + "filters": [], + "price_range": { "min": 4990, "max": 4990 }, + "price_ranges": [], + "price_median": 4990 } }, + "expect": { "result": { "productsTotal": 1, + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990.5, "currency": "₽", + "oldPrice": 5990, "oldPriceFormatted": "5 990 ₽", "oldPriceFull": 5990.5, + "oldPriceFullFormatted": "5 990.50 ₽", "isNew": false } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "count": 1 } ], + "brands": [ { "name": "Nike", "count": 1 } ], + "filters": {}, + "priceRange": { "min": 4990, "max": 4990 }, + "priceRanges": [], + "priceMedian": 4990 } } + }, + { + "name": "getCategory: ответ без products", + "call": { "namespace": "products", "method": "getCategory", "args": { "categoryId": "5" } }, + "response": { "status": 200, "body": { "status": "success" } }, + "expect": { "error": { "type": "decoding" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/profile.json b/Tests/REES46CoreTests/Fixtures/proposed/profile.json new file mode 100644 index 00000000..c0cf4ce6 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/profile.json @@ -0,0 +1,212 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "request": { "method": "GET", "path": "profile", "query": {} } + }, + { + "name": "set со всеми полями: externalId уходит полями id и external_id, cars — полем auto, свои свойства — на верхнем уровне", + "call": { "namespace": "profile", "method": "set", + "args": { "request": { "email": "jane@example.com", "phone": "+79990000000", "externalId": "u-1", "loyaltyId": "l-1", + "telegramId": "t-1", "fbId": "fb-1", "vkId": "vk-1", "firstName": "Jane", "lastName": "Doe", + "gender": "female", "birthday": "1990-02-28", "age": 36, "location": "msk", + "kids": [ { "gender": "male", "birthday": "2016-02-29" }, { "gender": "female" } ], + "cars": [ { "brand": "Lada", "model": "Vesta", "vds": "XTA000000000" } ], + "customProperties": { "favorite_color": "green", "points": 120, "vip": true, "visited_at": null, + "tags": [ "a", "b" ], "address": { "city": "Moscow" } } } } }, + "request": { "method": "POST", "path": "profile/set", + "body": { "email": "jane@example.com", "phone": "+79990000000", "id": "u-1", "external_id": "u-1", "loyalty_id": "l-1", + "telegram_id": "t-1", "fb_id": "fb-1", "vk_id": "vk-1", "first_name": "Jane", "last_name": "Doe", + "gender": "f", "birthday": "1990-02-28", "age": 36, "location": "msk", + "kids": [ { "gender": "m", "birthday": "2016-02-29" }, { "gender": "f" } ], + "auto": [ { "brand": "Lada", "model": "Vesta", "vds": "XTA000000000" } ], + "favorite_color": "green", "points": 120, "vip": true, "visited_at": null, + "tags": [ "a", "b" ], "address": { "city": "Moscow" } } } + }, + { + "name": "set: пустая строка стирает location", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "location": "" } } }, + "request": { "method": "POST", "path": "profile/set", "body": { "location": "" } } + }, + { + "name": "set: пустые списки не уходят — менять нечего", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "kids": [], "cars": [] } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set без полей", + "call": { "namespace": "profile", "method": "set", "args": { "request": {} } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set с пустым email", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set с пустым phone", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "phone": "" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set с пустым loyaltyId — сервер его не стирает", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "loyaltyId": "" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: пустая строка стирает externalId, telegramId и birthday — они уходят пустыми строками", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "externalId": "", "telegramId": "", "birthday": "" } } }, + "request": { "method": "POST", "path": "profile/set", "body": { "id": "", "external_id": "", "telegram_id": "", "birthday": "" } } + }, + { + "name": "set: age 0 стирает возраст", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "age": 0 } } }, + "request": { "method": "POST", "path": "profile/set", "body": { "age": 0 } } + }, + { + "name": "set: birthday не в формате YYYY-MM-DD", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "birthday": "28.02.1990" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday — несуществующая дата", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "birthday": "2026-02-29" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday с годом до 1000", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "birthday": "0999-12-31" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday с годом после 2999", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "birthday": "3000-01-01" } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday ребёнка — несуществующая дата", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "kids": [ { "birthday": "2015-02-29" } ] } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: birthday ребёнка не в формате", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "kids": [ { "birthday": "2016-2-1" } ] } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: отрицательный age", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "age": -1 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: ключ customProperties не из [a-z0-9_]", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "customProperties": { "Favorite-Color": "green" } } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: ключ customProperties совпадает с полем запроса", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "customProperties": { "first_name": "Jane" } } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "set: ключ customProperties совпадает со служебным полем", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "customProperties": { "did": "x" } } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getLastOrder", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "request": { "method": "GET", "path": "orders/last_for_user", "query": {} } + }, + { + "name": "get: профиль; незнакомый пол — пустое поле, поля вне Profile не попадают в результат", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "response": { "status": 200, + "body": { "id": 123, "has_email": true, "email_registered_at": "2026-11-01 10:00:00", "gender": "f", + "computed_gender": "x", "bought_something": false, "email": "hidden@example.com", + "custom_properties": { "favorite_color": "green", "points": 120, "tags": [ "a", "b" ], "address": { "city": "Moscow" } } } }, + "expect": { "result": { "id": "123", "hasEmail": true, "emailRegisteredAt": "2026-11-01 10:00:00", "gender": "female", + "boughtSomething": false, + "customProperties": { "favorite_color": "green", "points": 120, "tags": [ "a", "b" ], "address": { "city": "Moscow" } } } } + }, + { + "name": "get: пустой профиль", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "response": { "status": 200, "body": {} }, + "expect": { "result": {} } + }, + { + "name": "get: 404 — неизвестный did", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "response": { "status": 404, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "get: ответ не объект", + "call": { "namespace": "profile", "method": "get", "args": {} }, + "response": { "status": 200, "body": [] }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "set: успех", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "jane@example.com" } } }, + "response": { "status": 200, "body": { "status": "success" } }, + "expect": { "result": null } + }, + { + "name": "set: успех без тела", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "jane@example.com" } } }, + "response": { "status": 204, "body": null }, + "expect": { "result": null } + }, + { + "name": "set: 400 — сервер не принял email", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "not-an-email" } } }, + "response": { "status": 400, "body": { "status": "error", "message": "Invalid email" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "set: 2xx со status error", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "jane@example.com" } } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "set: нет ответа", + "call": { "namespace": "profile", "method": "set", "args": { "request": { "email": "jane@example.com" } } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + }, + { + "name": "getLastOrder: товары последнего заказа", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "response": { "status": 200, + "body": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽", + "oldprice": 5990, "is_new": true, "stock_quantity": 1000, "rating": 4, "leftovers": "lots", + "categories": [ { "id": "5", "parent": null, "name": "Обувь", "url": "https://shop.example/c/5" } ] } ] }, + "expect": { "result": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽", + "oldPrice": 5990, "isNew": true, "stockQuantity": 1000, "rating": 4, + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5" } ] } ] } + }, + { + "name": "getLastOrder: заказов нет", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "response": { "status": 200, "body": [] }, + "expect": { "result": [] } + }, + { + "name": "getLastOrder: 400 — неизвестный did", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "response": { "status": 400, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "getLastOrder: ответ не массив", + "call": { "namespace": "profile", "method": "getLastOrder", "args": {} }, + "response": { "status": 200, "body": { "products": [] } }, + "expect": { "error": { "type": "decoding" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/recommendations.json b/Tests/REES46CoreTests/Fixtures/proposed/recommendations.json new file mode 100644 index 00000000..d0b087bc --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/recommendations.json @@ -0,0 +1,105 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get без запроса — товары целиком", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "request": { "method": "GET", "path": "recommend/block-1", "query": { "extended": "true" } } + }, + { + "name": "get со всеми полями", + "call": { "namespace": "recommendations", "method": "get", + "args": { "code": "block-1", + "request": { "itemId": "37", "categoryId": "5", "searchQuery": "кроссовки", "excludedItemIds": [ "1", "2" ], + "brands": [ "Nike", "Adidas" ], "locations": [ "msk" ], "limit": 10, + "extended": true, "withLocations": true } } }, + "request": { "method": "GET", "path": "recommend/block-1", + "query": { "item_id": "37", "category": "5", "search_query": "кроссовки", "exclude": "1,2", + "brands": "Nike,Adidas", "locations": "msk", "limit": "10", "extended": "true", "with_locations": "true" } } + }, + { + "name": "get только артикулы: extended не уходит", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1", "request": { "extended": false } } }, + "request": { "method": "GET", "path": "recommend/block-1", "query": {} } + }, + { + "name": "get: код блока в пути URL-кодирован", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "a/b" } }, + "request": { "method": "GET", "path": "recommend/a%2Fb", "query": { "extended": "true" } } + }, + { + "name": "get с пустым кодом", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "get с limit 0", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1", "request": { "limit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "get: withLocations без extended", + "call": { "namespace": "recommendations", "method": "get", + "args": { "code": "block-1", "request": { "extended": false, "withLocations": true } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "расширенный ответ: товары целиком, itemIds — их id", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 200, + "body": { "id": 12, "title": "Похожие товары", "link": "https://shop.example/similar", + "recommends": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37?recommended_by=dynamic", + "price": 4990, "currency": "₽", "location_ids": [ "global" ] }, + { "id": "38", "name": "Кеды", "url": "https://shop.example/p/38", "price": "2990", "currency": "₽", + "location_ids": [ "msk", "spb" ] } ] } }, + "expect": { "result": { "id": 12, "title": "Похожие товары", "link": "https://shop.example/similar", + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37?recommended_by=dynamic", + "price": 4990, "currency": "₽", "isNew": false, "locationIds": [ "global" ] }, + { "id": "38", "name": "Кеды", "url": "https://shop.example/p/38", "price": 2990, "currency": "₽", + "isNew": false, "locationIds": [ "msk", "spb" ] } ], + "itemIds": [ "37", "38" ] } } + }, + { + "name": "простой ответ: только артикулы", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1", "request": { "extended": false } } }, + "response": { "status": 200, "body": { "id": 12, "title": "Похожие товары", "recommends": [ "37", "38" ] } }, + "expect": { "result": { "id": 12, "title": "Похожие товары", "products": [], "itemIds": [ "37", "38" ] } } + }, + { + "name": "блок на паузе — пусто, а не decoding", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 200, "body": { "state": "paused" } }, + "expect": { "result": { "products": [], "itemIds": [] } } + }, + { + "name": "ответ без recommends и не на паузе", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 200, "body": { "id": 12, "title": "Похожие товары" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "404 — неизвестный код блока", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "unknown" } }, + "response": { "status": 404, "body": { "status": "error", "message": "Recommender block not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "402 — услуга не оплачена", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 402, "body": { "status": "error", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "recommendations", "method": "get", "args": { "code": "block-1" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/reviews.json b/Tests/REES46CoreTests/Fixtures/proposed/reviews.json new file mode 100644 index 00000000..29ba0f32 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/reviews.json @@ -0,0 +1,430 @@ +{ + "contract": "0", + "cases": [ + { + "name": "createNps", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "request": { "method": "POST", "path": "api/v3/polls/nps/reviews", + "body": { "rate": 9, "channel": "ios_app", "category": "delivery" } } + }, + { + "name": "createNps с оценкой 0, заказом, комментарием и меткой", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 0, "channel": "ios_app", "category": "delivery", + "orderId": "A-1001", "comment": "Долго везли", "label": "checkout" } }, + "request": { "method": "POST", "path": "api/v3/polls/nps/reviews", + "body": { "rate": 0, "channel": "ios_app", "category": "delivery", + "order_id": "A-1001", "comment": "Долго везли", "label": "checkout" } } + }, + { + "name": "createNps с пустыми необязательными полями — они не уходят", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 10, "channel": "ios_app", "category": "delivery", + "orderId": "", "comment": "", "label": "" } }, + "request": { "method": "POST", "path": "api/v3/polls/nps/reviews", + "body": { "rate": 10, "channel": "ios_app", "category": "delivery" } } + }, + { + "name": "createNps с оценкой 11", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 11, "channel": "ios_app", "category": "delivery" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createNps с оценкой -1", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": -1, "channel": "ios_app", "category": "delivery" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createNps с пустым каналом", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "", "category": "delivery" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createNps с пустой категорией", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": " " } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCsat", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 5, "channel": "ios_app", "campaign": "support" } }, + "request": { "method": "POST", "path": "api/v3/polls/csat/reviews", + "body": { "rate": 5, "channel": "ios_app", "campaign": "support" } } + }, + { + "name": "createCsat с оценкой 0", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 0, "channel": "ios_app", "campaign": "support" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCsat с оценкой 6", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 6, "channel": "ios_app", "campaign": "support" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCsat с пустой кампанией", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 4, "channel": "ios_app", "campaign": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCes с заказом", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 7, "channel": "ios_app", "campaign": "checkout", "orderId": "A-1001" } }, + "request": { "method": "POST", "path": "api/v3/polls/ces/reviews", + "body": { "rate": 7, "channel": "ios_app", "campaign": "checkout", "order_id": "A-1001" } } + }, + { + "name": "createCes с оценкой 0", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 0, "channel": "ios_app", "campaign": "checkout" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCes с оценкой 8", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 8, "channel": "ios_app", "campaign": "checkout" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createCes с пустым каналом", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 3, "channel": "", "campaign": "checkout" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getNpsCategories", + "call": { "namespace": "reviews", "method": "getNpsCategories", "args": {} }, + "request": { "method": "GET", "path": "api/v3/polls/nps/categories", "query": {} } + }, + { + "name": "getNpsChannels", + "call": { "namespace": "reviews", "method": "getNpsChannels", "args": {} }, + "request": { "method": "GET", "path": "api/v3/polls/nps/channels", "query": {} } + }, + { + "name": "getCsatCampaigns", + "call": { "namespace": "reviews", "method": "getCsatCampaigns", "args": {} }, + "request": { "method": "GET", "path": "api/v3/polls/csat/campaigns", "query": {} } + }, + { + "name": "getCesCampaigns", + "call": { "namespace": "reviews", "method": "getCesCampaigns", "args": {} }, + "request": { "method": "GET", "path": "api/v3/polls/ces/campaigns", "query": {} } + }, + { + "name": "getProductReviews", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "request": { "method": "GET", "path": "reviews/product", "query": { "product": "37" } } + }, + { + "name": "getProductReviews со страницей", + "call": { "namespace": "reviews", "method": "getProductReviews", + "args": { "itemId": "37", "limit": 10, "offset": 20 } }, + "request": { "method": "GET", "path": "reviews/product", + "query": { "product": "37", "limit": "10", "offset": "20" } } + }, + { + "name": "getProductReviews с пустым itemId", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getProductReviews с limit 0", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37", "limit": 0 } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getProductReviews с limit 101", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37", "limit": 101 } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getProductReviews с отрицательным offset", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37", "offset": -1 } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "getClientReviews", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "request": { "method": "GET", "path": "reviews/client", "query": { "order": "A-1001" } } + }, + { + "name": "getClientReviews с пустым orderId", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "createNps — сохранённый отзыв", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "review": { "id": 512 } } } }, + "expect": { "result": { "id": 512 } } + }, + { + "name": "createNps — id больше 2^31", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 10, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "review": { "id": 3000000512, "rate": 10, "comment": null } } } }, + "expect": { "result": { "id": 3000000512 } } + }, + { + "name": "createCsat — id строкой", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 5, "channel": "ios_app", "campaign": "support" } }, + "response": { "status": 201, "body": { "status": "success", "payload": { "review": { "id": "77" } } } }, + "expect": { "result": { "id": 77 } } + }, + { + "name": "createCes — ответ без payload.review.id", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 7, "channel": "ios_app", "campaign": "checkout" } }, + "response": { "status": 200, "body": { "status": "success", "payload": {} } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "createNps — пустой ответ", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 200, "body": null }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "createNps — 400, оценка не прошла проверку", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 400, "body": { "status": "fail", "message": "Comment is too long" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "createNps — 404, нет канала", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 404, "body": { "status": "fail", "message": "Channel not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "createCsat — 402, проект не оплачен", + "call": { "namespace": "reviews", "method": "createCsat", + "args": { "rate": 5, "channel": "ios_app", "campaign": "support" } }, + "response": { "status": 402, "body": { "status": "fail", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "createCes — 429, больше 30 оценок в минуту", + "call": { "namespace": "reviews", "method": "createCes", + "args": { "rate": 7, "channel": "ios_app", "campaign": "checkout" } }, + "response": { "status": 429, "body": { "status": "fail", "message": "Too many requests" } }, + "expect": { "error": { "type": "http", "code": 429 } } + }, + { + "name": "createNps — 2xx со status error", + "call": { "namespace": "reviews", "method": "createNps", + "args": { "rate": 9, "channel": "ios_app", "category": "delivery" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getNpsCategories — элемент без code пропускается, пустые тексты — пусто", + "call": { "namespace": "reviews", "method": "getNpsCategories", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "categories": [ + { "code": "delivery", "name": "Доставка", + "detractor_question": "Что пошло не так?", "passive_question": "Что улучшить?", + "promoter_question": "Что понравилось?", + "detractor_success": "Разберёмся", "passive_success": "Спасибо", + "promoter_success": "Спасибо!", "button_label": "Готово", "position": 1 }, + { "code": "support", "name": "Поддержка", + "detractor_question": null, "passive_question": "", + "promoter_question": "Что понравилось?" }, + { "name": "Без кода" } + ] } } }, + "expect": { "result": [ + { "code": "delivery", "name": "Доставка", + "detractorQuestion": "Что пошло не так?", "passiveQuestion": "Что улучшить?", + "promoterQuestion": "Что понравилось?", + "detractorSuccess": "Разберёмся", "passiveSuccess": "Спасибо", + "promoterSuccess": "Спасибо!", "buttonLabel": "Готово" }, + { "code": "support", "name": "Поддержка", "promoterQuestion": "Что понравилось?" } + ] } + }, + { + "name": "getNpsChannels — справочник", + "call": { "namespace": "reviews", "method": "getNpsChannels", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "channels": [ { "code": "ios_app", "name": "Приложение iOS" }, + { "code": "web", "name": "Сайт" } ] } } }, + "expect": { "result": [ { "code": "ios_app", "name": "Приложение iOS" }, { "code": "web", "name": "Сайт" } ] } + }, + { + "name": "getCsatCampaigns — справочник", + "call": { "namespace": "reviews", "method": "getCsatCampaigns", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "campaigns": [ + { "code": "support", "name": "Поддержка", + "dissatisfied_question": "Что не так?", "neutral_question": "Что улучшить?", + "satisfied_question": "Что понравилось?", + "dissatisfied_success": "Разберёмся", "neutral_success": "Спасибо", + "satisfied_success": "Спасибо!", "button_label": "Готово" } + ] } } }, + "expect": { "result": [ + { "code": "support", "name": "Поддержка", + "dissatisfiedQuestion": "Что не так?", "neutralQuestion": "Что улучшить?", + "satisfiedQuestion": "Что понравилось?", + "dissatisfiedSuccess": "Разберёмся", "neutralSuccess": "Спасибо", + "satisfiedSuccess": "Спасибо!", "buttonLabel": "Готово" } + ] } + }, + { + "name": "getCesCampaigns — справочник", + "call": { "namespace": "reviews", "method": "getCesCampaigns", "args": {} }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "campaigns": [ + { "code": "checkout", "name": "Оформление заказа", + "difficult_question": "Что мешало?", "neutral_question": "Что улучшить?", + "easy_question": "Что помогло?", + "difficult_success": "Разберёмся", "neutral_success": "Спасибо", + "easy_success": "Спасибо!", "button_label": null } + ] } } }, + "expect": { "result": [ + { "code": "checkout", "name": "Оформление заказа", + "difficultQuestion": "Что мешало?", "neutralQuestion": "Что улучшить?", + "easyQuestion": "Что помогло?", + "difficultSuccess": "Разберёмся", "neutralSuccess": "Спасибо", "easySuccess": "Спасибо!" } + ] } + }, + { + "name": "getCsatCampaigns — нет кампаний", + "call": { "namespace": "reviews", "method": "getCsatCampaigns", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "payload": { "campaigns": [] } } }, + "expect": { "result": [] } + }, + { + "name": "getNpsChannels — ответ без payload.channels", + "call": { "namespace": "reviews", "method": "getNpsChannels", "args": {} }, + "response": { "status": 200, "body": { "status": "success", "channels": [ { "code": "web", "name": "Сайт" } ] } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getCesCampaigns — 403, проект неактивен", + "call": { "namespace": "reviews", "method": "getCesCampaigns", "args": {} }, + "response": { "status": 403, "body": { "status": "fail", "message": "Access denied" } }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "getProductReviews — сводка и отзывы, числа строкой, отзыв без created_at пропускается", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "summary": { "count": 3, "average_rating": 4.3, + "ratings": { "1": 0, "2": 0, "3": 1, "4": 0, "5": "2" } }, + "reviews": [ + { "id": 11, "rating": 5, "comment": "Отлично", "author": "Анна", + "created_at": "2026-11-10T12:00:00+03:00" }, + { "id": "10", "rating": "3", "comment": null, "author": null, + "created_at": "2026-11-09T08:30:00+03:00" }, + { "id": 9, "rating": 5 } + ] } } }, + "expect": { "result": { + "summary": { "count": 3, "averageRating": 4.3, "ratings": { "1": 0, "2": 0, "3": 1, "4": 0, "5": 2 } }, + "reviews": [ + { "id": 11, "rating": 5, "comment": "Отлично", "author": "Анна", "createdAt": "2026-11-10T12:00:00+03:00" }, + { "id": 10, "rating": 3, "createdAt": "2026-11-09T08:30:00+03:00" } + ] } } + }, + { + "name": "getProductReviews — id отзыва больше 2^31", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "summary": { "count": 1, "average_rating": 5.0, "ratings": { "5": 1 } }, + "reviews": [ { "id": 3000000011, "rating": 5, "created_at": "2026-11-10T12:00:00+03:00" } ] } } }, + "expect": { "result": { + "summary": { "count": 1, "averageRating": 5, "ratings": { "5": 1 } }, + "reviews": [ { "id": 3000000011, "rating": 5, "createdAt": "2026-11-10T12:00:00+03:00" } ] } } + }, + { + "name": "getProductReviews — нет отзывов", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "summary": { "count": 0, "average_rating": null, "ratings": {} }, + "reviews": [] } } }, + "expect": { "result": { "summary": { "count": 0, "ratings": {} }, "reviews": [] } } + }, + { + "name": "getProductReviews — 403, услуга не подключена", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 403, "body": { "status": "error", "payload": { "message": "Service is not enabled" } } }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "getProductReviews — ответ без summary", + "call": { "namespace": "reviews", "method": "getProductReviews", "args": { "itemId": "37" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "reviews": [] } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "getClientReviews — незнакомый state пустой", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "reviews": [ + { "id": 21, "product": "37", "order": "A-1001", "rating": 4, "comment": "Хорошо", + "state": "published", "created_at": "2026-11-10T12:00:00+03:00" }, + { "id": 22, "product": 38, "order": "A-1001", "rating": 2, + "state": "moderation", "created_at": "2026-11-10T12:05:00+03:00" }, + { "id": 23, "product": "39", "order": "A-1001", "rating": 1, + "state": "archived", "created_at": "2026-11-10T12:10:00+03:00" } + ] } } }, + "expect": { "result": [ + { "id": 21, "itemId": "37", "orderId": "A-1001", "rating": 4, "comment": "Хорошо", + "state": "published", "createdAt": "2026-11-10T12:00:00+03:00" }, + { "id": 22, "itemId": "38", "orderId": "A-1001", "rating": 2, + "state": "moderation", "createdAt": "2026-11-10T12:05:00+03:00" }, + { "id": 23, "itemId": "39", "orderId": "A-1001", "rating": 1, "createdAt": "2026-11-10T12:10:00+03:00" } + ] } + }, + { + "name": "getClientReviews — id отзыва больше 2^31", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "reviews": [ + { "id": 3000000021, "product": "37", "order": "A-1001", "rating": 4, + "state": "published", "created_at": "2026-11-10T12:00:00+03:00" } ] } } }, + "expect": { "result": [ + { "id": 3000000021, "itemId": "37", "orderId": "A-1001", "rating": 4, "state": "published", "createdAt": "2026-11-10T12:00:00+03:00" } + ] } + }, + { + "name": "getClientReviews — нет отзывов", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "response": { "status": 200, "body": { "status": "success", "payload": { "reviews": [] } } }, + "expect": { "result": [] } + }, + { + "name": "getClientReviews — 404, чужой заказ", + "call": { "namespace": "reviews", "method": "getClientReviews", "args": { "orderId": "A-1001" } }, + "response": { "status": 404, "body": { "status": "error", "payload": { "message": "Order not found" } } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "getNpsCategories — нет ответа", + "call": { "namespace": "reviews", "method": "getNpsCategories", "args": {} }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/search.json b/Tests/REES46CoreTests/Fixtures/proposed/search.json new file mode 100644 index 00000000..91ec39a9 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/search.json @@ -0,0 +1,376 @@ +{ + "contract": "0", + "cases": [ + { + "name": "blank", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "request": { "method": "GET", "path": "search/blank", "query": {} } + }, + { + "name": "instant", + "call": { "namespace": "search", "method": "instant", "args": { "query": "iphone" } }, + "request": { "method": "GET", "path": "search", "query": { "type": "instant_search", "search_query": "iphone" } } + }, + { + "name": "instant со списками через запятую без пробелов", + "call": { "namespace": "search", "method": "instant", + "args": { "query": "iphone", "locations": [ "msk", "spb" ], "excludedMerchants": [ "m1", "m2" ], "excludedBrands": [ "b1", "b2" ] } }, + "request": { "method": "GET", "path": "search", + "query": { "type": "instant_search", "search_query": "iphone", "locations": "msk,spb", + "excluded_merchants": "m1,m2", "excluded_brands": "b1,b2" } } + }, + { + "name": "instant: excludedMerchants без locations не уходит", + "call": { "namespace": "search", "method": "instant", "args": { "query": "iphone", "excludedMerchants": [ "m1" ] } }, + "request": { "method": "GET", "path": "search", "query": { "type": "instant_search", "search_query": "iphone" } } + }, + { + "name": "instant с пустым запросом", + "call": { "namespace": "search", "method": "instant", "args": { "query": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full без запроса", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone" } }, + "request": { "method": "GET", "path": "search", "query": { "type": "full_search", "search_query": "iphone" } } + }, + { + "name": "full со всеми полями: направление сортировки — order, уточнение — no_clarification", + "call": { "namespace": "search", "method": "full", + "args": { "query": "iphone", + "request": { "categoryIds": [ "1", "2" ], "brands": [ "Apple" ], "excludedBrands": [ "Noname" ], + "merchants": [ "m1" ], "excludedMerchants": [ "m2" ], "locations": [ "msk" ], + "priceMin": 1000, "priceMax": 99999.99, "colors": [ "black", "white" ], "fashionSizes": [ "42" ], + "excludedItemIds": [ "37" ], "filters": { "memory": [ "128", "256" ] }, + "sortBy": "relevance", "sortDir": "desc", "disableClarification": true, + "categoryLimit": 5, "brandLimit": 50, "limit": 24, "page": 3 } } }, + "request": { "method": "GET", "path": "search", + "query": { "type": "full_search", "search_query": "iphone", "categories": "1,2", "brands": "Apple", + "excluded_brands": "Noname", "merchants": "m1", "excluded_merchants": "m2", "locations": "msk", + "price_min": "1000", "price_max": "99999.99", "colors": "black,white", "fashion_sizes": "42", + "exclude": "37", "filters": "{\"memory\":[\"128\",\"256\"]}", "sort_by": "relevance", "order": "desc", + "no_clarification": "true", "category_limit": "5", "brand_limit": "50", "limit": "24", "page": "3" } } + }, + { + "name": "full: excludedMerchants без locations не уходит, disableClarification false не уходит", + "call": { "namespace": "search", "method": "full", + "args": { "query": "iphone", "request": { "excludedMerchants": [ "m2" ], "disableClarification": false } } }, + "request": { "method": "GET", "path": "search", "query": { "type": "full_search", "search_query": "iphone" } } + }, + { + "name": "full с пустым запросом", + "call": { "namespace": "search", "method": "full", "args": { "query": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с limit 0", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "limit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с page 0", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "page": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с categoryLimit 0", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "categoryLimit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с brandLimit 0", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "brandLimit": 0 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с отрицательной ценой", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "priceMax": -5 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "full с priceMin больше priceMax", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone", "request": { "priceMin": 500, "priceMax": 100 } } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "blank: недавние запросы и товары покупателя, подсказки, популярное; html не попадает в результат", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "response": { "status": 200, + "body": { "last_queries": [ { "name": "iphone", "url": "https://shop.example/search?q=iphone" } ], + "suggests": [ { "name": "iphone 15", "url": "https://shop.example/search?q=iphone+15" } ], + "last_products": true, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽" } ], + "popular_categories": [ { "name": "Смартфоны", "url": "https://shop.example/c/1" } ], + "popular_brands": [ { "name": "Apple", "url": "https://shop.example/b/apple" } ], + "popular_links": [ { "name": "Распродажа", "url": "https://shop.example/sale" }, { "name": "Без ссылки" } ], + "html": "
" } }, + "expect": { "result": { "lastQueries": [ { "name": "iphone", "url": "https://shop.example/search?q=iphone" } ], + "suggests": [ { "name": "iphone 15", "url": "https://shop.example/search?q=iphone+15" } ], + "lastProducts": true, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽", "isNew": false } ], + "popularCategories": [ { "name": "Смартфоны", "url": "https://shop.example/c/1" } ], + "popularBrands": [ { "name": "Apple", "url": "https://shop.example/b/apple" } ], + "popularLinks": [ { "name": "Распродажа", "url": "https://shop.example/sale" } ] } } + }, + { + "name": "blank: без last_products — популярные товары", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "response": { "status": 200, + "body": { "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽" } ] } }, + "expect": { "result": { "lastProducts": false, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽", "isNew": false } ] } } + }, + { + "name": "blank: совсем пустой ответ — []", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "response": { "status": 200, "body": [] }, + "expect": { "result": { "products": [], "lastProducts": false } } + }, + { + "name": "instant: результаты, категории-фасеты, подсказки с оценкой, локации, переход вместо результатов", + "call": { "namespace": "search", "method": "instant", "args": { "query": "ifone" } }, + "response": { "status": 200, + "body": { "search_query": "iphone", "search_query_original": "ifone", "clarification": false, "products_total": 1, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽", + "discount_percent": 10, "discount_formatted": "10%" } ], + "categories": [ { "id": "1", "name": "Смартфоны", "url": "https://shop.example/c/1", "parent": null, "count": 1, "alias": "phones" } ], + "queries": [ { "name": "iphone 15", "url": "https://shop.example/search?q=iphone+15", "score": "0.9" } ], + "locations": [ { "id": "msk", "name": "Москва", "type": null } ], + "search_query_redirects": { "query": "iphone", "redirect_link": "https://shop.example/apple", "deep_link": null }, + "html": "
", "requests_count": 3, "book_author": [], "collections": [] } }, + "expect": { "result": { "searchQuery": "iphone", "searchQueryOriginal": "ifone", "clarification": false, "productsTotal": 1, + "products": [ { "id": "37", "name": "iPhone 15", "url": "https://shop.example/p/37", "price": 79990, "currency": "₽", + "discountPercent": 10, "discountFormatted": "10%", "isNew": false } ], + "categories": [ { "id": "1", "name": "Смартфоны", "url": "https://shop.example/c/1", "count": 1, "alias": "phones" } ], + "queries": [ { "name": "iphone 15", "url": "https://shop.example/search?q=iphone+15", "score": 0.9 } ], + "locations": [ { "id": "msk", "name": "Москва" } ], + "redirect": { "query": "iphone", "url": "https://shop.example/apple" } } } + }, + { + "name": "instant: ничего не найдено", + "call": { "namespace": "search", "method": "instant", "args": { "query": "zzz" } }, + "response": { "status": 200, "body": { "search_query": "zzz", "products_total": 0, "products": [] } }, + "expect": { "result": { "searchQuery": "zzz", "productsTotal": 0, "products": [] } } + }, + { + "name": "full: результаты с фасетами", + "call": { "namespace": "search", "method": "full", "args": { "query": "кроссовки" } }, + "response": { "status": 200, + "body": { "search_query": "кроссовки", "clarification": true, "products_total": 120, + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽" } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "parent": "1", "count": 120 } ], + "brands": [ { "name": "Nike", "count": 80 }, { "name": "Adidas", "count": "40" } ], + "locations": [ { "id": "msk", "name": "Москва", "type": "city" } ], + "filters": { "Размер": { "count": 120, "priority": 2, "values": { "42": 30, "43": 25 } } }, + "industrial_filters": { "colors": [ { "color": "black", "count": 70 } ], "fashion_sizes": [ { "size": "42", "count": 30 }, { "count": 1 } ] }, + "price_range": { "min": 1990, "max": 19990 }, + "price_ranges": [ { "from": 0, "to": 5000, "count": 90 }, { "from": 5000, "count": 30 } ], + "price_median": 4990, "html": "", "requests_count": 1, "collections": [] } }, + "expect": { "result": { "searchQuery": "кроссовки", "clarification": true, "productsTotal": 120, + "products": [ { "id": "37", "name": "Кроссовки", "url": "https://shop.example/p/37", "price": 4990, "currency": "₽", "isNew": false } ], + "categories": [ { "id": "5", "name": "Обувь", "url": "https://shop.example/c/5", "parentId": "1", "count": 120 } ], + "brands": [ { "name": "Nike", "count": 80 }, { "name": "Adidas", "count": 40 } ], + "locations": [ { "id": "msk", "name": "Москва", "type": "city" } ], + "filters": { "Размер": { "count": 120, "priority": 2, "values": { "42": 30, "43": 25 } } }, + "industrialFilters": { "colors": [ { "color": "black", "count": 70 } ], "fashionSizes": [ { "size": "42", "count": 30 } ] }, + "priceRange": { "min": 1990, "max": 19990 }, + "priceRanges": [ { "from": 0, "to": 5000, "count": 90 }, { "from": 5000, "count": 30 } ], + "priceMedian": 4990 } } + }, + { + "name": "instant: ответ без products", + "call": { "namespace": "search", "method": "instant", "args": { "query": "iphone" } }, + "response": { "status": 200, "body": { "queries": [] } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "full: ответ без products", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone" } }, + "response": { "status": 200, "body": { "products_total": 0 } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "full: ответ не объект", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone" } }, + "response": { "status": 200, "body": [] }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "instant: 2xx со status error", + "call": { "namespace": "search", "method": "instant", "args": { "query": "iphone" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "full: 500", + "call": { "namespace": "search", "method": "full", "args": { "query": "iphone" } }, + "response": { "status": 500, "body": null }, + "expect": { "error": { "type": "http", "code": 500 } } + }, + { + "name": "blank: нет ответа", + "call": { "namespace": "search", "method": "blank", "args": {} }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + }, + { + "name": "agentDialog без параметров — последняя сессия, локация из профиля", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "request": {"method": "GET", "path": "api/v3/storefront/search/agent", "query": {}} + }, + { + "name": "agentDialog с сессией и локациями: location через запятую", + "call": {"namespace": "search", "method": "agentDialog", "args": {"sessionId": 12, "locations": ["msk", "spb"]}}, + "request": {"method": "GET", "path": "api/v3/storefront/search/agent", "query": {"session_id": "12", "location": "msk,spb"}} + }, + { + "name": "agent: новая сессия, тело — JSON", + "call": {"namespace": "search", "method": "agent", "args": {"message": "нужна флешка на 1тб"}}, + "request": {"method": "POST", "path": "api/v3/storefront/search/agent", "body": {"message": "нужна флешка на 1тб"}} + }, + { + "name": "agent в сессии с локацией", + "call": {"namespace": "search", "method": "agent", "args": {"message": "а есть подешевле?", "sessionId": 12, "locations": ["msk"]}}, + "request": {"method": "POST", "path": "api/v3/storefront/search/agent", "body": {"message": "а есть подешевле?", "session_id": 12, "location": "msk"}} + }, + { + "name": "agent: id сессии больше 2^31", + "call": {"namespace": "search", "method": "agent", "args": {"message": "ещё", "sessionId": 3000000012}}, + "request": {"method": "POST", "path": "api/v3/storefront/search/agent", "body": {"message": "ещё", "session_id": 3000000012}} + }, + { + "name": "agentDialog: id сессии больше 2^31 уходит строкой", + "call": {"namespace": "search", "method": "agentDialog", "args": {"sessionId": 3000000012}}, + "request": {"method": "GET", "path": "api/v3/storefront/search/agent", "query": {"session_id": "3000000012"}} + }, + { + "name": "agent: сообщение в 500 символов", + "call": {"namespace": "search", "method": "agent", "args": {"message": "яяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяя"}}, + "request": {"method": "POST", "path": "api/v3/storefront/search/agent", "body": {"message": "яяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяя"}} + }, + { + "name": "agent с пустым сообщением", + "call": {"namespace": "search", "method": "agent", "args": {"message": ""}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "agent: сообщение длиннее 500 символов", + "call": {"namespace": "search", "method": "agent", "args": {"message": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "agentDialog: сессии и сообщения выбранной; товар без id пропускается", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 200, "body": {"sessions": [{"id": 12, "title": "Флешка на 1 ТБ", "updated_at": "2026-11-01T12:00:00Z"}, {"id": 9, "title": "Наушники", "updated_at": "2026-10-30T08:15:00Z"}], "session": {"id": 12, "title": "Флешка на 1 ТБ", "updated_at": "2026-11-01T12:00:00Z", "messages": [{"id": 1, "role": "user", "content": "нужна флешка на 1тб", "products": [], "created_at": "2026-11-01T11:59:40Z"}, {"id": 2, "role": "assistant", "content": "Нашёл три флешки на 1 ТБ с USB 3.2...", "created_at": "2026-11-01T12:00:00Z", "products": [{"id": "123", "name": "Флешка Example 1 ТБ", "price": 1990.0, "oldprice": 2490.0, "price_formatted": "1 990 ₽", "oldprice_formatted": "2 490 ₽", "picture": "https://example.com/images/123.jpg", "url": "https://example.com/p/123?recommended_by=agent_search&recommended_code=12", "reason": "Объём 1 ТБ, USB 3.2"}, {"name": "Без id", "price": 100.0}]}]}}}, + "expect": {"result": {"sessions": [{"id": 12, "title": "Флешка на 1 ТБ", "updatedAt": "2026-11-01T12:00:00Z", "messages": []}, {"id": 9, "title": "Наушники", "updatedAt": "2026-10-30T08:15:00Z", "messages": []}], "session": {"id": 12, "title": "Флешка на 1 ТБ", "updatedAt": "2026-11-01T12:00:00Z", "messages": [{"id": 1, "role": "user", "content": "нужна флешка на 1тб", "createdAt": "2026-11-01T11:59:40Z", "products": []}, {"id": 2, "role": "assistant", "content": "Нашёл три флешки на 1 ТБ с USB 3.2...", "createdAt": "2026-11-01T12:00:00Z", "products": [{"id": "123", "name": "Флешка Example 1 ТБ", "price": 1990, "oldPrice": 2490, "priceFormatted": "1 990 ₽", "oldPriceFormatted": "2 490 ₽", "picture": "https://example.com/images/123.jpg", "url": "https://example.com/p/123?recommended_by=agent_search&recommended_code=12", "reason": "Объём 1 ТБ, USB 3.2"}]}]}}} + }, + { + "name": "agentDialog: сессий ещё нет", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 200, "body": {"sessions": [], "session": null}}, + "expect": {"result": {"sessions": []}} + }, + { + "name": "agent: ответ агента; старая цена 0.0 — пусто", + "call": {"namespace": "search", "method": "agent", "args": {"message": "а есть подешевле?", "sessionId": 12}}, + "response": {"status": 200, "body": {"session": {"id": 12, "title": "Флешка на 1 ТБ", "updated_at": "2026-11-01T12:01:10Z"}, "message": {"id": 4, "role": "assistant", "content": "Вот варианты дешевле 1 500 ₽...", "created_at": "2026-11-01T12:01:10Z", "products": [{"id": "456", "name": "Флешка Example Lite 1 ТБ", "price": 1390.0, "oldprice": 0.0, "price_formatted": "1 390 ₽", "oldprice_formatted": null, "picture": null, "url": null, "reason": ""}]}}}, + "expect": {"result": {"session": {"id": 12, "title": "Флешка на 1 ТБ", "updatedAt": "2026-11-01T12:01:10Z", "messages": []}, "message": {"id": 4, "role": "assistant", "content": "Вот варианты дешевле 1 500 ₽...", "createdAt": "2026-11-01T12:01:10Z", "products": [{"id": "456", "name": "Флешка Example Lite 1 ТБ", "price": 1390, "priceFormatted": "1 390 ₽", "reason": ""}]}}} + }, + { + "name": "agent: незнакомая роль читается как есть — открытый набор", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 200, "body": {"session": {"id": 13}, "message": {"id": 1, "role": "system", "content": "Агент обновлён"}}}, + "expect": {"result": {"session": {"id": 13, "messages": []}, "message": {"id": 1, "role": "system", "content": "Агент обновлён", "products": []}}} + }, + { + "name": "agent: id сессии и сообщения больше 2^31", + "call": {"namespace": "search", "method": "agent", "args": {"message": "ещё", "sessionId": 3000000012}}, + "response": {"status": 200, "body": {"session": {"id": 3000000012, "title": "Флешка"}, "message": {"id": 3000000099, "role": "assistant", "content": "Вот ещё", "products": []}}}, + "expect": {"result": {"session": {"id": 3000000012, "title": "Флешка", "messages": []}, "message": {"id": 3000000099, "role": "assistant", "content": "Вот ещё", "products": []}}} + }, + { + "name": "agent: ответ без message", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 200, "body": {"session": {"id": 13}}}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "agentDialog: ответ не объект", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 200, "body": []}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "agent: 400 — нет did", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 400, "body": {"error": "did is required"}}, + "expect": {"error": {"type": "http", "code": 400}} + }, + { + "name": "agent: 402 — услуга поиска не подключена", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 402, "body": {"status": "fail", "message": "Search is not paid"}}, + "expect": {"error": {"type": "http", "code": 402}} + }, + { + "name": "agent: 403 — магазин неактивен или неверный секрет", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 403, "body": {"status": "fail", "message": "Access denied"}}, + "expect": {"error": {"type": "http", "code": 403}} + }, + { + "name": "agentDialog: 403 — магазин неактивен", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 403, "body": {"status": "fail", "message": "Access denied"}}, + "expect": {"error": {"type": "http", "code": 403}} + }, + { + "name": "agentDialog: 404 — сессия не найдена или чужая", + "call": {"namespace": "search", "method": "agentDialog", "args": {"sessionId": 99}}, + "response": {"status": 404, "body": {"error": "Session not found"}}, + "expect": {"error": {"type": "http", "code": 404}} + }, + { + "name": "agent: 422 — сообщение длиннее 500 символов по счёту сервера", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 422, "body": {"error": "Message is too long"}}, + "expect": {"error": {"type": "http", "code": 422}} + }, + { + "name": "agent: 429 — превышен лимит", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 429, "body": {"error": "Too many requests"}}, + "expect": {"error": {"type": "http", "code": 429}} + }, + { + "name": "agentDialog: 503 — агент недоступен, показать blank", + "call": {"namespace": "search", "method": "agentDialog", "args": {}}, + "response": {"status": 503, "body": {"error": "Agent is unavailable"}}, + "expect": {"error": {"type": "http", "code": 503}} + }, + { + "name": "agent: 503 — агент не ответил", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 503, "body": {"error": "Agent is unavailable"}}, + "expect": {"error": {"type": "http", "code": 503}} + }, + { + "name": "agent: 503 — посетитель в контрольной группе поиска, показать blank", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": 503, "body": {"error": "agent is unavailable"}}, + "expect": {"error": {"type": "http", "code": 503}} + }, + { + "name": "agentDialog: 503 — посетитель в контрольной группе поиска, показать blank", + "call": {"namespace": "search", "method": "agentDialog", "args": {"sessionId": 3000000012}}, + "response": {"status": 503, "body": {"error": "agent is unavailable"}}, + "expect": {"error": {"type": "http", "code": 503}} + }, + { + "name": "agent: нет ответа", + "call": {"namespace": "search", "method": "agent", "args": {"message": "привет"}}, + "response": {"status": null}, + "expect": {"error": {"type": "network"}} + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/segments.json b/Tests/REES46CoreTests/Fixtures/proposed/segments.json new file mode 100644 index 00000000..256d09a0 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/segments.json @@ -0,0 +1,82 @@ +{ + "contract": "0", + "cases": [ + { + "name": "add", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12}}, + "request": {"method": "POST", "path": "segments/add", "body": {"segment_id": 12}} + }, + { + "name": "add с контактами", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12, "email": "jane@example.com", "phone": "+79990000000"}}, + "request": {"method": "POST", "path": "segments/add", "body": {"segment_id": 12, "email": "jane@example.com", "phone": "+79990000000"}} + }, + { + "name": "remove", + "call": {"namespace": "segments", "method": "remove", "args": {"segmentId": 12}}, + "request": {"method": "POST", "path": "segments/remove", "body": {"segment_id": 12}} + }, + { + "name": "add с segmentId 0", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 0}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "remove с отрицательным segmentId", + "call": {"namespace": "segments", "method": "remove", "args": {"segmentId": -3}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "add с пустым email", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12, "email": ""}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "get — GET, не POST из документации", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "request": {"method": "GET", "path": "segments/get", "query": {}} + }, + { + "name": "get: сегменты клиента; незнакомый тип читается как есть, сегмент без id пропускается", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "response": {"status": 200, "body": [{"id": 1, "type": "dynamic"}, {"id": "2", "type": "static"}, {"id": 3, "type": "brand_new_kind"}, {"type": "rfm"}]}, + "expect": {"result": [{"id": 1, "type": "dynamic"}, {"id": 2, "type": "static"}, {"id": 3, "type": "brand_new_kind"}]} + }, + { + "name": "get: сегментов нет", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "response": {"status": 200, "body": []}, + "expect": {"result": []} + }, + { + "name": "get: 404 — неизвестный did", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "response": {"status": 404, "body": {"status": "error", "message": "User not found"}}, + "expect": {"error": {"type": "http", "code": 404}} + }, + { + "name": "get: ответ не массив", + "call": {"namespace": "segments", "method": "get", "args": {}}, + "response": {"status": 200, "body": {"segments": []}}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "add: успех", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12}}, + "response": {"status": 200, "body": {"status": "success"}}, + "expect": {"result": null} + }, + { + "name": "remove: 2xx со status error", + "call": {"namespace": "segments", "method": "remove", "args": {"segmentId": 12}}, + "response": {"status": 200, "body": {"status": "error", "message": "Something went wrong"}}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "add: нет ответа", + "call": {"namespace": "segments", "method": "add", "args": {"segmentId": 12}}, + "response": {"status": null}, + "expect": {"error": {"type": "network"}} + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/sliders.json b/Tests/REES46CoreTests/Fixtures/proposed/sliders.json new file mode 100644 index 00000000..1bb370d5 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/sliders.json @@ -0,0 +1,123 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "request": { "method": "GET", "path": "slider", "query": { "code": "homepage_mobile" } } + }, + { + "name": "get с тегами и локацией: теги через запятую", + "call": { "namespace": "sliders", "method": "get", + "args": { "code": "homepage_mobile", "tags": [ "sale", "new" ], "locationId": "msk-1" } }, + "request": { "method": "GET", "path": "slider", "query": { "code": "homepage_mobile", "tags": "sale,new", "location": "msk-1" } } + }, + { + "name": "get с пустым code", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "get с запятой в теге", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile", "tags": [ "sale,new" ] } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "get с пустым тегом", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile", "tags": [ "sale", "" ] } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "слайдер с баннерами: список — payload.slides, id из banner_id строкой (В54, В55)", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "properties": { "code": "homepage_mobile", "width": 1000, "height": 160 }, + "slides": [ + { "banner_id": 12, "recommended_code": "homepage_mobile", + "image_url": "https://cdn.example/b12.jpg", "url": "https://shop.example/sale", + "deeplink_ios": "app://sale", "deeplink_android": "app://sale", + "content_type": "image", "content": "x", "html": null }, + { "banner_id": "13", "recommended_code": "homepage_mobile", + "image_url": null, "url": null, "html": "
Sale
" } ] } } }, + "expect": { "result": { + "code": "homepage_mobile", "width": 1000, "height": 160, + "banners": [ + { "id": "12", "code": "homepage_mobile", "imageUrl": "https://cdn.example/b12.jpg", "url": "https://shop.example/sale", + "deeplinkIos": "app://sale", "deeplinkAndroid": "app://sale", "html": null }, + { "id": "13", "code": "homepage_mobile", "imageUrl": null, "url": null, "deeplinkIos": null, "deeplinkAndroid": null, + "html": "
Sale
" } ] } } + }, + { + "name": "пустой слайдер", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 200, + "body": { "status": "success", + "payload": { "properties": { "code": "homepage_mobile", "width": "1000", "height": "160" }, "slides": [] } } }, + "expect": { "result": { "code": "homepage_mobile", "width": 1000, "height": 160, "banners": [] } } + }, + { + "name": "404 — неизвестный или неактивный слайдер (В53)", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "nope" } }, + "response": { "status": 404, "body": { "status": "error", "message": "Slider not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "403 с пустым телом — неизвестный или отключённый магазин", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 403, "body": null }, + "expect": { "error": { "type": "http", "code": 403 } } + }, + { + "name": "402 — услуга слайдеров не оплачена", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 402, "body": { "status": "error", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "2xx со status error из документации", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 200, "body": { "status": "error", "payload": { "message": "Invalid slider code" } } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "ответ без payload", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": 200, "body": { "status": "success" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "sliders", "method": "get", "args": { "code": "homepage_mobile" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + }, + { + "name": "bannerView", + "call": { "namespace": "tracking", "method": "bannerView", "args": { "bannerId": "12", "code": "homepage_mobile" } }, + "request": { "method": "POST", "path": "track/slider", + "body": { "event": "view", "banner_id": 12, "recommended_code": "homepage_mobile" } } + }, + { + "name": "bannerClick", + "call": { "namespace": "tracking", "method": "bannerClick", "args": { "bannerId": "12", "code": "homepage_mobile" } }, + "request": { "method": "POST", "path": "track/slider", + "body": { "event": "click", "banner_id": 12, "recommended_code": "homepage_mobile" } } + }, + { + "name": "bannerView с пустым bannerId", + "call": { "namespace": "tracking", "method": "bannerView", "args": { "bannerId": "", "code": "homepage_mobile" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "bannerClick с bannerId не целым числом", + "call": { "namespace": "tracking", "method": "bannerClick", "args": { "bannerId": "b-12", "code": "homepage_mobile" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "bannerView с пустым code", + "call": { "namespace": "tracking", "method": "bannerView", "args": { "bannerId": "12", "code": "" } }, + "error": { "type": "invalidArgument" } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/stories.json b/Tests/REES46CoreTests/Fixtures/proposed/stories.json new file mode 100644 index 00000000..057fc316 --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/stories.json @@ -0,0 +1,154 @@ +{ + "contract": "0", + "cases": [ + { + "name": "get", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "request": { "method": "GET", "path": "stories/115bd0b67cf5989a1b60c841790b2af6", "query": {} } + }, + { + "name": "get с пустым code", + "call": { "namespace": "stories", "method": "get", "args": { "code": "" } }, + "error": { "type": "invalidArgument" } + }, + { + "name": "блок: товарный слайд, видео, картинка с кнопкой, товарами и текстом; header пропускается", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, + "body": { "id": 35, + "settings": { "color": "#212529" }, + "stories": [ + { "id": 39, "name": "Test story", "avatar": "https://cdn.example/avatar.jpg", + "viewed": false, "start_position": 0, "pinned": false, + "slides": [ + { "id": "39_0", "duration": 10, "background": "https://cdn.example/bg.jpg", "preview": "", "type": "", + "elements": [ + { "type": "button", "title": "Buy", "link": "https://shop.example/p/1?recommended_by=dynamic", + "link_ios": "https://shop.example/p/1", "link_android": "https://shop.example/p/1", + "background": "#3b82f6", "color": "#ffffff" }, + { "type": "product", "title": "Pool", + "item": { "id": "216908", "name": "Pool INTEX", "brand": "INTEX", + "picture": "https://pictures.example/180/135478.jpg", + "image_url": "https://api.example/216908_1.jpg", + "price": 19990, "price_formatted": "19 990 ₽", + "oldprice": 27990, "oldprice_formatted": "27 990 ₽", + "discount_percent": 28, "currency": "₽", + "url": "https://shop.example/p/1?recommended_by=stories", + "deeplink_android": "app://p/1", "deeplink_ios": "app://p/1" } } ] } ] }, + { "id": "40", "name": "Gaming", "avatar": "https://cdn.example/avatar2.jpg", + "viewed": true, "start_position": "1", "pinned": true, + "slides": [ + { "id": 36, "duration": "15", "background": "https://cdn.example/clip.mp4", + "preview": "https://cdn.example/poster.jpg", "type": "video" }, + { "id": 37, "duration": 0, "background": "https://cdn.example/slide.jpg", + "background_color": "#000000", "preview": "", "type": "image", + "elements": [ + { "type": "button", "title": "Go gaming!", "link": "https://demo.example/", "link_ios": "", + "link_android": "https://demo.example/", "text_bold": true, + "background": "#3b82f6", "color": "#ffffff" }, + { "type": "products", + "labels": { "show_carousel": "Show products", "hide_carousel": "Hide products" }, + "products": [ { "id": 1, "name": "Mouse", "price": "1990.0", "price_formatted": "1 990 ₽", + "oldprice": 1990, "promocode": "GAME5", "price_with_promocode": 1890, + "price_with_promocode_formatted": "1 890 ₽" } ] }, + { "type": "text_block", "text_input": "Up to 10% off", "font_size": "24", "font_type": "serif", + "bold": true, "italic": false, "text_align": "center", "text_color": "#FFFFFF", + "text_background_color": "#16AE13", "text_background_color_opacity": "40%", + "text_line_spacing": "1.2", "y_offset": 12, "promocode": "SALE10" }, + { "type": "header", "title": "left out" }, + { "type": "poll", "question": "left out" } ] }, + { "id": 38, "background": "https://cdn.example/plain.jpg", "type": "image" } ] } ] } }, + "expect": { "result": { + "id": "35", + "stories": [ + { "id": "39", "name": "Test story", "avatar": "https://cdn.example/avatar.jpg", + "viewed": false, "pinned": false, "startPosition": 0, + "slides": [ + { "id": "39_0", "type": "product", "background": "https://cdn.example/bg.jpg", "backgroundColor": "", "preview": "", + "duration": 10, + "elements": [ + { "type": "button", "title": "Buy", "link": "https://shop.example/p/1?recommended_by=dynamic", + "linkAndroid": "https://shop.example/p/1", "linkIos": "https://shop.example/p/1", + "background": "#3b82f6", "color": "#ffffff", "textBold": false }, + { "type": "product", "title": "Pool", + "item": { "id": "216908", "name": "Pool INTEX", "brand": "INTEX", + "picture": "https://pictures.example/180/135478.jpg", "imageUrl": "https://api.example/216908_1.jpg", + "price": 19990, "priceFormatted": "19 990 ₽", "oldPrice": 27990, "oldPriceFormatted": "27 990 ₽", + "discountPercent": 28, "promocode": "", "priceWithPromocode": 0, "priceWithPromocodeFormatted": "", + "currency": "₽", "url": "https://shop.example/p/1?recommended_by=stories", + "deeplinkAndroid": "app://p/1", "deeplinkIos": "app://p/1" } } ] } ] }, + { "id": "40", "name": "Gaming", "avatar": "https://cdn.example/avatar2.jpg", + "viewed": true, "pinned": true, "startPosition": 1, + "slides": [ + { "id": "36", "type": "video", "background": "https://cdn.example/clip.mp4", + "preview": "https://cdn.example/poster.jpg", "duration": 15, "elements": [] }, + { "id": "37", "type": "image", "background": "https://cdn.example/slide.jpg", "backgroundColor": "#000000", + "duration": 10, + "elements": [ + { "type": "button", "title": "Go gaming!", "linkIos": "", "textBold": true }, + { "type": "products", "showLabel": "Show products", "hideLabel": "Hide products", + "products": [ { "id": "1", "name": "Mouse", "brand": "", "price": 1990, "oldPrice": null, + "discountPercent": 0, "promocode": "GAME5", "priceWithPromocode": 1890, + "priceWithPromocodeFormatted": "1 890 ₽" } ] }, + { "type": "textBlock", "text": "Up to 10% off", "fontSize": 24, "fontType": "serif", "bold": true, + "italic": false, "textAlign": "center", "textColor": "#FFFFFF", "backgroundColor": "#16AE13", + "backgroundOpacity": 0.4, "lineSpacing": 1.2, "yOffset": 12, "promocode": "SALE10" } ] }, + { "id": "38", "type": "image", "duration": 10, "backgroundColor": "", "preview": "", "elements": [] } ] } ] } } + }, + { + "name": "текстовый блок без полей — значения по умолчанию, товар без item", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, + "body": { "id": "35", "stories": [ { "id": 1, "slides": [ { "id": 2, "type": "image", + "elements": [ { "type": "text_block" }, { "type": "product", "item": {} }, { "type": "something_new" } ] } ] } ] } }, + "expect": { "result": { "id": "35", "stories": [ { "id": "1", "name": "", "avatar": "", "viewed": false, "pinned": false, + "startPosition": 0, + "slides": [ { "id": "2", "type": "image", "elements": [ + { "type": "textBlock", "text": "", "fontSize": 14, "fontType": "", "bold": false, "backgroundOpacity": 0, + "lineSpacing": 0, "yOffset": 0, "promocode": null }, + { "type": "product", "title": "", "item": null } ] } ] } ] } } + }, + { + "name": "блок на паузе — успех с пустым stories", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, "body": { "id": 35, "stories": [], "state": "paused" } }, + "expect": { "result": { "id": "35", "stories": [] } } + }, + { + "name": "404 — неизвестный блок", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 404, "body": { "status": "error", "message": "Stories not found" } }, + "expect": { "error": { "type": "http", "code": 404 } } + }, + { + "name": "402 — услуга сторис не оплачена", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 402, "body": { "status": "error", "message": "Payment required" } }, + "expect": { "error": { "type": "http", "code": 402 } } + }, + { + "name": "400 — неизвестный покупатель", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 400, "body": { "status": "error", "message": "Client not found" } }, + "expect": { "error": { "type": "http", "code": 400 } } + }, + { + "name": "ответ не JSON-объект", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, "body": [ { "id": 35 } ] }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "2xx со status error", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": 200, "body": { "status": "error", "message": "Something went wrong" } }, + "expect": { "error": { "type": "decoding" } } + }, + { + "name": "нет ответа", + "call": { "namespace": "stories", "method": "get", "args": { "code": "115bd0b67cf5989a1b60c841790b2af6" } }, + "response": { "status": null }, + "expect": { "error": { "type": "network" } } + } + ] +} diff --git a/Tests/REES46CoreTests/Fixtures/proposed/subscriptions.json b/Tests/REES46CoreTests/Fixtures/proposed/subscriptions.json new file mode 100644 index 00000000..6b7c4e4b --- /dev/null +++ b/Tests/REES46CoreTests/Fixtures/proposed/subscriptions.json @@ -0,0 +1,144 @@ +{ + "contract": "0", + "cases": [ + { + "name": "manage: контакты и флаги; null не уходит", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"email": "jane@example.com", "phone": "+79990000000", "externalId": "u-1", "loyaltyId": "l-1", "telegramId": "t-1", "emailBulk": true, "smsChain": false, "walletTransactional": true}}}, + "request": {"method": "POST", "path": "subscriptions/manage", "body": {"email": "jane@example.com", "phone": "+79990000000", "external_id": "u-1", "loyalty_id": "l-1", "telegram_id": "t-1", "email_bulk": true, "sms_chain": false, "wallet_transactional": true}} + }, + { + "name": "manage: все 24 флага", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"emailBulk": true, "emailChain": true, "emailTransactional": true, "smsBulk": true, "smsChain": true, "smsTransactional": true, "webPushBulk": true, "webPushChain": true, "webPushTransactional": true, "mobilePushBulk": true, "mobilePushChain": true, "mobilePushTransactional": true, "telegramBulk": true, "telegramChain": true, "telegramTransactional": true, "whatsappBulk": true, "whatsappChain": true, "whatsappTransactional": true, "maxBulk": true, "maxChain": true, "maxTransactional": true, "walletBulk": true, "walletChain": true, "walletTransactional": true}}}, + "request": {"method": "POST", "path": "subscriptions/manage", "body": {"email_bulk": true, "email_chain": true, "email_transactional": true, "sms_bulk": true, "sms_chain": true, "sms_transactional": true, "web_push_bulk": true, "web_push_chain": true, "web_push_transactional": true, "mobile_push_bulk": true, "mobile_push_chain": true, "mobile_push_transactional": true, "telegram_bulk": true, "telegram_chain": true, "telegram_transactional": true, "whatsapp_bulk": true, "whatsapp_chain": true, "whatsapp_transactional": true, "max_bulk": true, "max_chain": true, "max_transactional": true, "wallet_bulk": true, "wallet_chain": true, "wallet_transactional": true}} + }, + { + "name": "manage без флагов", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"email": "jane@example.com"}}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "manage с пустым email", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"email": "", "emailBulk": true}}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "check", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "request": {"method": "GET", "path": "subscriptions/check", "query": {}} + }, + { + "name": "subscribeForPriceDrop: товар полем item_id, цена полем price", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "37", "currentPrice": 4990.5, "email": "jane@example.com"}}, + "request": {"method": "POST", "path": "subscriptions/subscribe_for_product_price", "body": {"item_id": "37", "price": 4990.5, "email": "jane@example.com"}} + }, + { + "name": "subscribeForPriceDrop с пустым itemId", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "", "currentPrice": 4990}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "subscribeForPriceDrop с ценой 0", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "37", "currentPrice": 0}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "subscribeForPriceDrop с пустым phone", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "37", "currentPrice": 4990, "phone": ""}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "unsubscribeFromPriceDrop: item_ids строкой через запятую без пробелов", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromPriceDrop", "args": {"itemIds": ["37", "38"], "phone": "+79990000000"}}, + "request": {"method": "POST", "path": "subscriptions/unsubscribe_from_product_price", "body": {"item_ids": "37,38", "phone": "+79990000000"}} + }, + { + "name": "unsubscribeFromPriceDrop: пустой список — от всех товаров", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromPriceDrop", "args": {"itemIds": []}}, + "request": {"method": "POST", "path": "subscriptions/unsubscribe_from_product_price", "body": {"item_ids": ""}} + }, + { + "name": "unsubscribeFromPriceDrop: пустая строка в списке", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromPriceDrop", "args": {"itemIds": ["37", ""]}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "subscribeForBackInStock со свойствами варианта", + "call": {"namespace": "subscriptions", "method": "subscribeForBackInStock", "args": {"itemId": "37", "properties": {"fashionSize": "42", "fashionColor": "red", "barcode": "4600000000000"}, "phone": "+79990000000"}}, + "request": {"method": "POST", "path": "subscriptions/subscribe_for_product_available", "body": {"item_id": "37", "properties": {"fashion_size": "42", "fashion_color": "red", "barcode": "4600000000000"}, "phone": "+79990000000"}} + }, + { + "name": "subscribeForBackInStock: свойства без полей не уходят", + "call": {"namespace": "subscriptions", "method": "subscribeForBackInStock", "args": {"itemId": "37", "properties": {}}}, + "request": {"method": "POST", "path": "subscriptions/subscribe_for_product_available", "body": {"item_id": "37"}} + }, + { + "name": "subscribeForBackInStock с пустым itemId", + "call": {"namespace": "subscriptions", "method": "subscribeForBackInStock", "args": {"itemId": ""}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "unsubscribeFromBackInStock", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromBackInStock", "args": {"itemIds": ["37"], "email": "jane@example.com"}}, + "request": {"method": "POST", "path": "subscriptions/unsubscribe_from_product_available", "body": {"item_ids": "37", "email": "jane@example.com"}} + }, + { + "name": "unsubscribeFromBackInStock: пустая строка в списке", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromBackInStock", "args": {"itemIds": [""]}}, + "error": {"type": "invalidArgument"} + }, + { + "name": "check: все 24 флага, пуш-токены и состояние email; незнакомые поля не мешают", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 200, "body": {"exists": true, "email_bulk": true, "email_chain": false, "email_transactional": false, "sms_bulk": true, "sms_chain": false, "sms_transactional": false, "web_push_bulk": true, "web_push_chain": false, "web_push_transactional": false, "mobile_push_bulk": true, "mobile_push_chain": false, "mobile_push_transactional": false, "telegram_bulk": true, "telegram_chain": false, "telegram_transactional": false, "whatsapp_bulk": true, "whatsapp_chain": false, "whatsapp_transactional": false, "max_bulk": true, "max_chain": false, "max_transactional": false, "wallet_bulk": true, "wallet_chain": false, "wallet_transactional": false, "web_push": false, "mobile_push": true, "email_invalid": false, "email_blacklisted": false, "email_bounced": false, "email_suppressed": false, "email_confirmed": true, "unknown_flag": true}}, + "expect": {"result": {"exists": true, "emailBulk": true, "emailChain": false, "emailTransactional": false, "smsBulk": true, "smsChain": false, "smsTransactional": false, "webPushBulk": true, "webPushChain": false, "webPushTransactional": false, "mobilePushBulk": true, "mobilePushChain": false, "mobilePushTransactional": false, "telegramBulk": true, "telegramChain": false, "telegramTransactional": false, "whatsappBulk": true, "whatsappChain": false, "whatsappTransactional": false, "maxBulk": true, "maxChain": false, "maxTransactional": false, "walletBulk": true, "walletChain": false, "walletTransactional": false, "hasWebPush": false, "hasMobilePush": true, "emailInvalid": false, "emailBlacklisted": false, "emailBounced": false, "emailSuppressed": false, "emailConfirmed": true}} + }, + { + "name": "check: нет поля — false; логическое строкой и числом", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 200, "body": {"exists": "1", "email_bulk": "true", "sms_bulk": 1}}, + "expect": {"result": {"exists": true, "emailBulk": true, "emailChain": false, "emailTransactional": false, "smsBulk": true, "smsChain": false, "smsTransactional": false, "webPushBulk": false, "webPushChain": false, "webPushTransactional": false, "mobilePushBulk": false, "mobilePushChain": false, "mobilePushTransactional": false, "telegramBulk": false, "telegramChain": false, "telegramTransactional": false, "whatsappBulk": false, "whatsappChain": false, "whatsappTransactional": false, "maxBulk": false, "maxChain": false, "maxTransactional": false, "walletBulk": false, "walletChain": false, "walletTransactional": false, "hasWebPush": false, "hasMobilePush": false, "emailInvalid": false, "emailBlacklisted": false, "emailBounced": false, "emailSuppressed": false, "emailConfirmed": false}} + }, + { + "name": "check: пустой ответ — всё false", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 200, "body": {}}, + "expect": {"result": {"exists": false, "emailBulk": false, "emailChain": false, "emailTransactional": false, "smsBulk": false, "smsChain": false, "smsTransactional": false, "webPushBulk": false, "webPushChain": false, "webPushTransactional": false, "mobilePushBulk": false, "mobilePushChain": false, "mobilePushTransactional": false, "telegramBulk": false, "telegramChain": false, "telegramTransactional": false, "whatsappBulk": false, "whatsappChain": false, "whatsappTransactional": false, "maxBulk": false, "maxChain": false, "maxTransactional": false, "walletBulk": false, "walletChain": false, "walletTransactional": false, "hasWebPush": false, "hasMobilePush": false, "emailInvalid": false, "emailBlacklisted": false, "emailBounced": false, "emailSuppressed": false, "emailConfirmed": false}} + }, + { + "name": "check: 400 — неизвестный did", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 400, "body": {"status": "error", "message": "Client not found"}}, + "expect": {"error": {"type": "http", "code": 400}} + }, + { + "name": "check: ответ не объект", + "call": {"namespace": "subscriptions", "method": "check", "args": {}}, + "response": {"status": 200, "body": []}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "manage: успех", + "call": {"namespace": "subscriptions", "method": "manage", "args": {"request": {"emailBulk": true}}}, + "response": {"status": 200, "body": {"status": "success"}}, + "expect": {"result": null} + }, + { + "name": "subscribeForBackInStock: 400 — свойство не из списка сервера", + "call": {"namespace": "subscriptions", "method": "subscribeForBackInStock", "args": {"itemId": "37", "properties": {"fashionSize": "42"}}}, + "response": {"status": 400, "body": {"status": "error", "message": "Incorrect product property"}}, + "expect": {"error": {"type": "http", "code": 400}} + }, + { + "name": "unsubscribeFromPriceDrop: 2xx со status error", + "call": {"namespace": "subscriptions", "method": "unsubscribeFromPriceDrop", "args": {"itemIds": ["37"]}}, + "response": {"status": 200, "body": {"status": "error", "message": "Something went wrong"}}, + "expect": {"error": {"type": "decoding"}} + }, + { + "name": "subscribeForPriceDrop: нет ответа", + "call": {"namespace": "subscriptions", "method": "subscribeForPriceDrop", "args": {"itemId": "37", "currentPrice": 4990}}, + "response": {"status": null}, + "expect": {"error": {"type": "network"}} + } + ] +} diff --git a/Tests/REES46CoreTests/InitPackageTests.swift b/Tests/REES46CoreTests/InitPackageTests.swift index 8cef3c00..2e860a79 100644 --- a/Tests/REES46CoreTests/InitPackageTests.swift +++ b/Tests/REES46CoreTests/InitPackageTests.swift @@ -119,6 +119,15 @@ final class InitPackageTests: XCTestCase { XCTAssertTrue(Rees46Config(shopId: "a", enableLogs: true).hasSameSettings(as: Rees46Config(shopId: "a", logLevel: .debug))) } + func test_the_app_domain_is_app_rees46_ru_unless_the_config_gives_another() { + XCTAssertEqual(Rees46Config(shopId: "a").appDomain, "app.rees46.ru") + XCTAssertEqual(Rees46Config(shopId: "a", appDomain: " app.cluster.example \n").appDomain, "app.cluster.example") + XCTAssertEqual(Rees46Config(shopId: "a", appDomain: "").appDomain, "app.rees46.ru", "empty is the default") + XCTAssertEqual(Rees46Config(shopId: "a", appDomain: "app.cluster.example").onNewCore().appDomain, "app.cluster.example") + XCTAssertFalse(Rees46Config(shopId: "a").hasSameSettings(as: Rees46Config(shopId: "a", appDomain: "app.cluster.example"))) + XCTAssertTrue(Rees46Config(shopId: "a").hasSameSettings(as: Rees46Config(shopId: "a", appDomain: "app.rees46.ru"))) + } + // MARK: - The machine over a transport the test answers func test_the_machine_retries_with_a_pause_and_lets_waiting_calls_through_once_ready() async throws { diff --git a/Tests/REES46CoreTests/LoyaltyPackageTests.swift b/Tests/REES46CoreTests/LoyaltyPackageTests.swift new file mode 100644 index 00000000..62229ccc --- /dev/null +++ b/Tests/REES46CoreTests/LoyaltyPackageTests.swift @@ -0,0 +1,168 @@ +// +// LoyaltyPackageTests.swift +// REES46CoreTests +// +// `loyalty.join`, `getStatus` and `getPromotions` without a server: the requests they build, the +// arguments they refuse, and what they make of each answer of the proposed fixture. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class LoyaltyPackageTests: XCTestCase { + + func test_the_requests_of_the_loyalty_fixture_and_its_refusals() throws { + let cases = try FixtureCase.load("loyalty").filter { $0.item.response == nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let make = { try Self.request(for: item) } + if item.item.request != nil { + FixtureMatching.assert(try make(), is: item) + } else { + FixtureMatching.assertRefused(item, make) + } + } + } + + func test_the_answers_of_the_loyalty_fixture_end_as_it_says() throws { + let cases = try FixtureCase.load("loyalty").filter { $0.item.response?.status != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + switch item.method { + case "join": + let request = try LoyaltyAPIImpl.joinRequest(phone: "+7", firstName: nil, lastName: nil, gender: nil, birthday: nil) + FixtureMatching.assert(try FixtureMatching.outcome(of: item, for: request, call: "loyalty.join"), as: item) { + ["identifier": $0.identifier] as [String: Any] + } + case "getStatus": + let request = try LoyaltyAPIImpl.statusRequest(phone: "+7") + FixtureMatching.assert(try FixtureMatching.outcome(of: item, for: request, call: "loyalty.getStatus"), as: item, json: Self.json(status:)) + case "getPromotions": + let request = try LoyaltyAPIImpl.promotionsRequest(locationId: nil, promoCodes: nil, chargeBonuses: nil, currentTime: nil) + FixtureMatching.assert(try FixtureMatching.outcome(of: item, for: request, call: "loyalty.getPromotions"), as: item) { + $0.map(Self.json(promotion:)) + } + default: + XCTFail("\(item.name): a method the test does not know") + } + } + } + + // MARK: - Arguments + + func test_a_birthday_is_an_existing_day_of_the_calendar_as_yyyy_mm_dd() { + for date in ["1990-05-17", "2024-02-29", "2000-12-31", "0999-12-31", "3000-01-01"] { + XCTAssertTrue(ApiArguments.isCalendarDate(date), date) + } + for date in ["2023-02-29", "1900-02-29", "1990-02-30", "1990-13-01", "1990-00-10", "1990-05-00", "1990-5-17", + "17.05.1990", "1990-05-17T00:00:00Z", " 1990-05-17", "", "1990-05-17"] { + XCTAssertFalse(ApiArguments.isCalendarDate(date), date) + } + } + + func test_the_current_time_is_hh_mm_of_a_day() { + for time in ["00:00", "09:30", "23:59"] { + XCTAssertTrue(LoyaltyAPIImpl.isTime(time), time) + } + for time in ["24:00", "9:30", "18:60", "18-30", "18:30:00", ""] { + XCTAssertFalse(LoyaltyAPIImpl.isTime(time), time) + } + } + + func test_what_is_not_given_is_not_sent() throws { + let join = try LoyaltyAPIImpl.joinRequest(phone: "+79991234567", firstName: " ", lastName: "", gender: nil, birthday: nil) + XCTAssertEqual(Set(join.body.keys), ["phone"], "a blank name is none, and no email: the server reads it only with the secret") + XCTAssertEqual(join.method, .post) + + let promotions = try LoyaltyAPIImpl.promotionsRequest(locationId: "", promoCodes: [], chargeBonuses: false, currentTime: nil) + XCTAssertEqual(promotions.query, ["charge_bonuses": "false"]) + XCTAssertTrue(promotions.queryLists.isEmpty, "an empty list is not sent") + XCTAssertThrowsError(try LoyaltyAPIImpl.promotionsRequest(locationId: nil, promoCodes: [" "], chargeBonuses: nil, currentTime: nil)) + XCTAssertThrowsError(try LoyaltyAPIImpl.statusRequest(phone: " ")) + XCTAssertThrowsError(try LoyaltyAPIImpl.joinRequest(phone: "+7", firstName: nil, lastName: nil, gender: nil, birthday: "")) + } + + // MARK: - Answers + + func test_a_promotion_without_an_id_is_left_out_and_an_answer_without_promotions_is_not_one() throws { + let request = try LoyaltyAPIImpl.promotionsRequest(locationId: nil, promoCodes: nil, chargeBonuses: nil, currentTime: nil) + let read = try request.decode(Data(#"{"payload":{"promotions":[{"name":"no id"},{"id":"x"},{"id":3}]}}"#.utf8)) + XCTAssertEqual(read.map(\.id), [3]) + XCTAssertEqual(read.first?.name, "", "a name it does not have is empty") + XCTAssertEqual(try request.decode(Data()).count, 0, "an answer without a body is no promotion") + XCTAssertThrowsError(try request.decode(Data(#"{"status":"success"}"#.utf8))) + XCTAssertThrowsError(try request.decode(Data(#"{"payload":{"promotions":{}}}"#.utf8))) + } + + func test_a_status_needs_payload_member_and_a_level_needs_its_code() throws { + let request = try LoyaltyAPIImpl.statusRequest(phone: "+7") + XCTAssertThrowsError(try request.decode(Data(#"{"status":"success","payload":{"level":null}}"#.utf8))) + XCTAssertThrowsError(try request.decode(Data())) + let member = try request.decode(Data(#"{"payload":{"member":"true","level":{"code":"gold"}}}"#.utf8)) + XCTAssertTrue(member.isMember) + XCTAssertEqual(member.level?.code, "gold") + XCTAssertNil(member.level?.name) + XCTAssertNil(member.level?.expirationDate) + XCTAssertNil(try request.decode(Data(#"{"payload":{"member":true}}"#.utf8)).level) + XCTAssertNil(try request.decode(Data(#"{"payload":{"member":true,"level":{"code":""}}}"#.utf8)).level) + } + + func test_the_loyalty_fixture_is_proposed_until_the_contract_has_one() { + XCTAssertFalse( + FileManager.default.fileExists(atPath: ContractFixtures.url("loyalty").path), + "the contract has loyalty.json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one" + ) + } + + // MARK: - Helpers + + /// The request of the case's call, built from its arguments. + private static func request(for item: FixtureCase) throws -> CoreRequest { + let args = item.args + switch item.method { + case "join": + let gender = (args["gender"] as? String).map { $0 == "male" ? Gender.male : Gender.female } + return try LoyaltyAPIImpl.joinRequest( + phone: args["phone"] as? String ?? "", firstName: args["firstName"] as? String, + lastName: args["lastName"] as? String, gender: gender, birthday: args["birthday"] as? String + ).coreRequest + case "getStatus": + return try LoyaltyAPIImpl.statusRequest(phone: args["phone"] as? String ?? "").coreRequest + case "getPromotions": + return try LoyaltyAPIImpl.promotionsRequest( + locationId: args["locationId"] as? String, promoCodes: args["promoCodes"] as? [String], + chargeBonuses: args["chargeBonuses"] as? Bool, currentTime: args["currentTime"] as? String + ).coreRequest + default: + throw Rees46.SdkError.invalidArgument("a method the test does not know: \(item.method)") + } + } + + static func json(status: LoyaltyStatus) -> [String: Any] { + [ + "isMember": status.isMember, + "level": FixtureMatching.field(status.level.map { level -> [String: Any] in + [ + "code": FixtureMatching.field(level.code), "name": FixtureMatching.field(level.name), + "expirationDate": FixtureMatching.field(level.expirationDate), + ] + }), + ] + } + + static func json(promotion: LoyaltyPromotion) -> [String: Any] { + let rewardType: String? + switch promotion.rewardType { + case .discount?: rewardType = "discount" + case .bonusesEarn?: rewardType = "bonusesEarn" + case .bonusesUsage?: rewardType = "bonusesUsage" + case nil: rewardType = nil + } + return [ + "id": promotion.id, "name": promotion.name, "description": FixtureMatching.field(promotion.description), + "startDate": FixtureMatching.field(promotion.startDate), "finishDate": FixtureMatching.field(promotion.finishDate), + "stream": FixtureMatching.field(promotion.stream), "badgeLabel": FixtureMatching.field(promotion.badgeLabel), + "badgeColor": FixtureMatching.field(promotion.badgeColor), "rewardType": FixtureMatching.field(rewardType), + ] + } +} diff --git a/Tests/REES46CoreTests/NamespaceFixtures.swift b/Tests/REES46CoreTests/NamespaceFixtures.swift new file mode 100644 index 00000000..74e4457b --- /dev/null +++ b/Tests/REES46CoreTests/NamespaceFixtures.swift @@ -0,0 +1,269 @@ +// +// NamespaceFixtures.swift +// REES46CoreTests +// +// Runs a namespace's fixture without a server: the request each call builds, the error a refused one +// ends with before anything is sent, and what the request path makes of each answer. A fixture's +// `result` is the method's value by the contract's field names, and `request.query` or `request.body` +// the request's own fields; both are compared whole, as the Android SDK compares them: a field without +// a value is left out on either side. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +/// A namespace's request, built from a fixture's call, its value's type erased. +struct ErasedRequest { + let method: String + let path: String + let query: [String: String] + let body: [String: Any] + let timeout: TimeInterval? + /// What the request path makes of `response`: the value as JSON by the contract's names, or the + /// error. + let answer: (NetworkClient.Response, SdkLogger) -> Result + + init(_ request: ApiRequest, call: String) { + method = request.method.rawValue + path = request.path + query = request.query + body = request.body + timeout = request.timeout + answer = { response, logger in + NamespaceRequests.value(of: response, for: request, call: call, logger: logger).map { ContractJSON.of($0) } + } + } +} + +enum NamespaceFixtures { + + /// Builds the request of a fixture's call; throws what the method refuses. + typealias Build = (ContractCase.Call) throws -> ErasedRequest + + /// Every case of `name` with a request or an error instead of one: the call builds that request, or + /// throws that error. + static func checkRequests(_ name: String, file: StaticString = #filePath, line: UInt = #line, build: Build) throws { + let raw = try ContractFixtures.cases(name, from: .proposed) + let cases = raw.map(ContractCase.init) + var checked = 0 + for (json, item) in zip(raw, cases) { + guard let call = item.call, item.response == nil else { continue } + if let expected = json["request"] as? [String: Any] { + checked += 1 + let request: ErasedRequest + do { + request = try build(call) + } catch { + XCTFail("\(item.name): \(error)", file: file, line: line) + continue + } + XCTAssertEqual(request.method, expected["method"] as? String, item.name, file: file, line: line) + XCTAssertEqual(request.path, expected["path"] as? String, item.name, file: file, line: line) + // The request's own fields, all of them: the core adds the common ones. + let own: [String: Any] = request.method == "GET" ? request.query : request.body + let wanted = expected[request.method == "GET" ? "query" : "body"] as? [String: Any] ?? [:] + for problem in ContractJSON.mismatches(ContractJSON.of(own), wanted, at: "request") { + XCTFail("\(item.name): \(problem)", file: file, line: line) + } + } else if let error = item.expectedError { + checked += 1 + do { + let request = try build(call) + XCTFail("\(item.name): built \(request.method) \(request.path), expected \(error)", file: file, line: line) + } catch let refusal as Rees46.SdkError { + XCTAssertTrue(error.matches(refusal), "\(item.name): \(refusal), expected \(error)", file: file, line: line) + } + } + } + XCTAssertGreaterThan(checked, 0, "\(name) has calls", file: file, line: line) + } + + /// Every case of `name` with an answer: the request of its call ends with the case's result or error, + /// as the client classifies the answer and the request path reads it. + static func checkAnswers(_ name: String, file: StaticString = #filePath, line: UInt = #line, build: Build) throws { + let logger = SdkLogger(shopId: "package-\(UUID().uuidString)", level: .none) + let cases = try ContractFixtures.fixture(name, from: .proposed).filter { $0.response != nil } + XCTAssertFalse(cases.isEmpty, "\(name) has answers", file: file, line: line) + for item in cases { + guard let call = item.call, let response = item.response else { continue } + let request: ErasedRequest + do { + request = try build(call) + } catch { + XCTFail("\(item.name): \(error)", file: file, line: line) + continue + } + let answer = NetworkClient.Response( + status: response.status, + body: response.body, + retryAfter: nil, + // No status: no answer, a connection never made. + result: response.status.map { NetworkClient.classify(status: $0, body: response.body, path: request.path) } ?? .failure(.network) + ) + switch request.answer(answer, logger) { + case .success(let value): + XCTAssertNil(item.expectedError, "\(item.name): \(value)", file: file, line: line) + guard item.expectedError == nil else { continue } + guard let expected = item.expect["result"] else { + XCTFail("\(item.name): the case has no result", file: file, line: line) + continue + } + for problem in ContractJSON.mismatches(value, expected, at: "result") { + XCTFail("\(item.name): \(problem)", file: file, line: line) + } + case .failure(let error): + XCTAssertTrue(item.expectedError?.matches(error) == true, "\(item.name): \(error), expected \(String(describing: item.expectedError))", file: file, line: line) + } + } + } + + // MARK: - Arguments + + static func string(_ value: Any?) -> String? { + value as? String + } + + static func strings(_ value: Any?) -> [String]? { + (value as? [Any])?.map { "\($0)" } + } + + static func int(_ value: Any?) -> Int? { + (value as? NSNumber)?.intValue + } + + static func double(_ value: Any?) -> Double? { + (value as? NSNumber)?.doubleValue + } + + static func bool(_ value: Any?) -> Bool? { + (value as? NSNumber)?.boolValue + } + + static func filters(_ value: Any?) -> [String: [String]]? { + (value as? [String: Any])?.mapValues { strings($0) ?? [] } + } + + /// A key of sorting by its name in the contract's code: `salesRate`. + static func sortBy(_ value: Any?) -> Rees46.SortBy? { + guard let name = value as? String else { return nil } + let known: [String: Rees46.SortBy] = [ + "price": .price, "discount": .discount, "salesRate": .salesRate, "date": .date, + "priceMargin": .priceMargin, "rating": .rating, "relevance": .relevance + ] + return known[name] ?? Rees46.SortBy(rawValue: name) + } + + static func sortDir(_ value: Any?) -> Rees46.SortDirection? { + (value as? String).flatMap(Rees46.SortDirection.init(rawValue:)) + } +} + +/// A value of the SDK as the JSON a fixture writes it by the contract's names, and the comparison of +/// the two. +enum ContractJSON { + + /// `value` as JSON: a model is an object of its properties — named as the contract names its + /// fields —, a list a list, a map an object, `nil` `NSNull`, a value of an open or closed set its + /// raw value. + static func of(_ value: Any) -> Any { + if let text = value as? String { + return text + } + // A boolean, Swift's or JSON's, is one; any other number — `Int`, `Double`, `NSNumber` — its value. + if let number = value as? NSNumber { + return CFGetTypeID(number) == CFBooleanGetTypeID() ? number.boolValue as Any : number.doubleValue + } + if value is NSNull { + return NSNull() + } + // Lists and maps, Swift's or JSON's. + if let list = value as? [Any] { + return list.map(of) + } + if let map = value as? [String: Any] { + return map.mapValues(of) + } + let mirror = Mirror(reflecting: value) + switch mirror.displayStyle { + case .tuple where mirror.children.isEmpty: + // `Void`: a method without a value. + return NSNull() + case .optional: + return mirror.children.first.map { of($0.value) } ?? NSNull() + case .collection, .set: + return mirror.children.map { of($0.value) } + case .dictionary: + var object: [String: Any] = [:] + for entry in mirror.children { + let pair = Mirror(reflecting: entry.value).children.map(\.value) + if pair.count == 2 { + object["\(pair[0])"] = of(pair[1]) + } + } + return object + default: + if let raw = value as? any RawRepresentable { + return of(raw.rawValue) + } + var object: [String: Any] = [:] + for child in mirror.children { + if let label = child.label { + object[label] = of(child.value) + } + } + return object + } + } + + /// Where `actual` differs from `expected`, as the Android SDK compares them: an object has the same + /// fields with a value — a field whose value is `null` counts as missing on either side —, each the + /// same; a list the same elements in order; a number the same value, `19990` as `19990.0`. + static func mismatches(_ actual: Any, _ expected: Any, at path: String) -> [String] { + switch expected { + case is NSNull: + return actual is NSNull ? [] : ["\(path): \(actual), expected null"] + case let object as [String: Any]: + guard let actualObject = actual as? [String: Any] else { + return ["\(path): \(actual), expected an object"] + } + let wanted = Set(object.filter { !($0.value is NSNull) }.keys) + let got = Set(actualObject.filter { !($0.value is NSNull) }.keys) + var problems: [String] = [] + if wanted != got { + problems.append("\(path): fields \(got.sorted()), expected \(wanted.sorted())") + } + for key in wanted.intersection(got).sorted() { + problems += mismatches(actualObject[key] ?? NSNull(), object[key] ?? NSNull(), at: "\(path).\(key)") + } + return problems + case let list as [Any]: + guard let actualList = actual as? [Any] else { + return ["\(path): \(actual), expected a list"] + } + guard actualList.count == list.count else { + return ["\(path): \(actualList.count) elements, expected \(list.count): \(actualList)"] + } + return zip(actualList, list).enumerated().flatMap { index, pair in + mismatches(pair.0, pair.1, at: "\(path)[\(index)]") + } + case let text as String: + return actual as? String == text ? [] : ["\(path): \(actual), expected \"\(text)\""] + case let number as NSNumber: + if CFGetTypeID(number) == CFBooleanGetTypeID() { + return actual as? Bool == number.boolValue ? [] : ["\(path): \(actual), expected \(number.boolValue)"] + } + let value: Double? + switch actual { + case let int as Int: value = Double(int) + case let double as Double: value = double + default: value = nil + } + guard let found = value, abs(found - number.doubleValue) < 1e-9 else { + return ["\(path): \(actual), expected \(number)"] + } + return [] + default: + return ["\(path): cannot compare \(expected)"] + } + } +} diff --git a/Tests/REES46CoreTests/NamespacePackageTests.swift b/Tests/REES46CoreTests/NamespacePackageTests.swift new file mode 100644 index 00000000..102202df --- /dev/null +++ b/Tests/REES46CoreTests/NamespacePackageTests.swift @@ -0,0 +1,145 @@ +// +// NamespacePackageTests.swift +// REES46CoreTests +// +// The base of the namespaces that needs no server: how an answer is read (`LenientDecoding`) and the +// loader of the contract's fixtures. +// + +import XCTest +@testable import REES46 + +final class NamespacePackageTests: XCTestCase { + + // MARK: - Reading an answer + + /// Every field of an answer, read leniently. + private struct Sample: Decodable { + let string: String? + let int: Int? + let double: Double? + let bool: Bool? + let kind: Kind? + let nested: Nested? + let list: [Nested]? + + enum Kind: String { + case one, two + } + + struct Nested: Decodable { + let id: String + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: AnswerKey.self) + guard let id = container.lenientString("id") else { + throw DecodingError.keyNotFound(AnswerKey("id"), DecodingError.Context(codingPath: container.codingPath, debugDescription: "no id")) + } + self.id = id + } + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: AnswerKey.self) + string = container.lenientString("string") + int = container.lenientInt("int") + double = container.lenientDouble("double") + bool = container.lenientBool("bool") + kind = container.lenientEnum(Kind.self, "kind") + nested = container.lenient(Nested.self, "nested") + list = container.lenientList(Nested.self, "list") + } + } + + private func sample(_ json: String) throws -> Sample { + try JSONDecoder().decode(Sample.self, from: Data(json.utf8)) + } + + func test_numbers_come_as_strings_and_strings_as_numbers() throws { + let read = try sample(#"{"string": 37, "int": "4", "double": "12.5", "bool": "true"}"#) + XCTAssertEqual(read.string, "37") + XCTAssertEqual(read.int, 4) + XCTAssertEqual(read.double, 12.5) + XCTAssertEqual(read.bool, true) + + let numbers = try sample(#"{"string": 12.5, "int": 3.0, "double": 7, "bool": 0}"#) + XCTAssertEqual(numbers.string, "12.5") + XCTAssertEqual(numbers.int, 3, "a number without a fraction is an integer") + XCTAssertEqual(numbers.double, 7) + XCTAssertEqual(numbers.bool, false) + + let integral = try sample(#"{"string": 37.0, "int": " 5 ", "bool": 1}"#) + XCTAssertEqual(integral.string, "37", "an integral number is its digits") + XCTAssertEqual(integral.int, 5) + XCTAssertEqual(integral.bool, true) + } + + func test_a_missing_null_or_unfit_field_is_empty_not_a_failure() throws { + let missing = try sample("{}") + XCTAssertNil(missing.string) + XCTAssertNil(missing.int) + XCTAssertNil(missing.double) + XCTAssertNil(missing.bool) + XCTAssertNil(missing.kind) + XCTAssertNil(missing.nested) + XCTAssertNil(missing.list) + + let null = try sample(#"{"string": null, "int": null, "double": null, "bool": null, "kind": null, "nested": null, "list": null}"#) + XCTAssertNil(null.string) + XCTAssertNil(null.int) + XCTAssertNil(null.nested) + XCTAssertNil(null.list) + + let unfit = try sample(#"{"string": {"a": 1}, "int": 2.5, "double": "abc", "bool": "maybe", "nested": [1], "list": {"id": "1"}}"#) + XCTAssertNil(unfit.string) + XCTAssertNil(unfit.int, "a number with a fraction is not an integer") + XCTAssertNil(unfit.double) + XCTAssertNil(unfit.bool) + XCTAssertNil(unfit.nested) + XCTAssertNil(unfit.list) + + XCTAssertNil(try sample(#"{"string": ""}"#).string, "an empty string is no value") + XCTAssertNil(try sample(#"{"string": " \n"}"#).string, "nor is a blank one") + XCTAssertEqual(try sample(#"{"string": " a "}"#).string, " a ", "a string is kept as it came") + XCTAssertNil(try sample(#"{"int": "", "double": "1e999"}"#).int) + XCTAssertNil(try sample(#"{"double": "1e999"}"#).double, "not a finite number") + } + + func test_an_unknown_value_of_an_enumeration_is_empty_and_unknown_fields_are_ignored() throws { + XCTAssertEqual(try sample(#"{"kind": "two"}"#).kind, .two) + let read = try sample(#"{"kind": "three", "string": "s", "added_by_the_server": {"x": [1, 2]}}"#) + XCTAssertNil(read.kind) + XCTAssertEqual(read.string, "s") + } + + func test_a_list_leaves_out_the_elements_that_do_not_read() throws { + let read = try sample(#"{"list": [{"id": "1"}, {"name": "no id"}, null, 7, {"id": 2}], "nested": {"id": 3}}"#) + XCTAssertEqual(read.list?.map(\.id), ["1", "2"]) + XCTAssertEqual(read.nested?.id, "3") + XCTAssertEqual(try sample(#"{"list": []}"#).list?.count, 0) + } + + // MARK: - Fixtures + + func test_the_loader_reads_the_contracts_fixtures() throws { + for name in ["init", "tracking"] { + XCTAssertEqual(try ContractFixtures.load(name)["contract"] as? String, ContractFixtures.version) + let cases = try ContractFixtures.fixture(name) + XCTAssertFalse(cases.isEmpty, name) + XCTAssertTrue(cases.allSatisfy { $0.call != nil || $0.response != nil }, name) + } + let tracking = try ContractFixtures.fixture("tracking") + let view = try XCTUnwrap(tracking.first { $0.name == "productView" }) + XCTAssertEqual(view.call?.name, "tracking.productView") + XCTAssertEqual(view.request?.method, "POST") + XCTAssertEqual(view.request?.path, "push") + XCTAssertEqual(view.request?.body["event"] as? String, "view") + XCTAssertTrue(tracking.contains { $0.expectedError?.matches(.invalidArgument("any")) == true }) + + let initRefused = try XCTUnwrap(ContractFixtures.fixture("init").first { $0.response?.status == 402 }) + XCTAssertEqual(initRefused.expect["state"] as? String, "refused") + XCTAssertNil(try ContractFixtures.fixture("init").first { $0.name.hasPrefix("нет ответа") }?.response?.status) + XCTAssertTrue(ContractCase.ErrorSpec(type: "http", code: 404).matches(.http(code: 404, serverCode: "x"))) + XCTAssertFalse(ContractCase.ErrorSpec(type: "http", code: 404).matches(.http(code: 500, serverCode: nil))) + XCTAssertTrue(ContractCase.ErrorSpec(type: "timeout", code: nil).matches(.timeout)) + } +} diff --git a/Tests/REES46CoreTests/NotificationsPackageTests.swift b/Tests/REES46CoreTests/NotificationsPackageTests.swift new file mode 100644 index 00000000..1ee7a6bd --- /dev/null +++ b/Tests/REES46CoreTests/NotificationsPackageTests.swift @@ -0,0 +1,184 @@ +// +// NotificationsPackageTests.swift +// REES46CoreTests +// +// `notifications` without a server: which calls of the proposed fixture are refused before anything +// goes and where the others go, and the `async` form of a method with `completion`. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class NotificationsPackageTests: XCTestCase { + + /// The cases of the proposed `notifications` fixture for iOS: those of no platform and of iOS. + static func iosCases() throws -> [ContractCase] { + try ContractFixtures.cases("notifications", from: .proposed) + .filter { ($0["platform"] as? String ?? "ios") == "ios" } + .map(ContractCase.init) + } + + static func event(of method: String) -> Rees46.PushEvent? { + guard method.hasPrefix("track") else { return nil } + return Rees46.PushEvent(rawValue: method.dropFirst("track".count).lowercased()) + } + + func test_the_fixture_is_proposed_until_the_contract_has_one() throws { + XCTAssertEqual(try ContractFixtures.load("notifications", from: .proposed)["contract"] as? String, ContractFixtures.version) + let cases = try Self.iosCases() + XCTAssertEqual(Set(cases.compactMap { $0.call?.name }), [ + "notifications.trackDelivered", "notifications.trackOpened", "notifications.trackClicked", + "notifications.trackClosed", "notifications.setPushToken", + ]) + XCTAssertFalse( + FileManager.default.fileExists(atPath: ContractFixtures.url("notifications").path), + "the contract has notifications.json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one" + ) + } + + func test_every_event_of_the_fixture_goes_to_its_path_or_is_refused_before_anything_goes() throws { + let cases = try Self.iosCases().filter { $0.call?.method.hasPrefix("track") == true && $0.response == nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let call = try XCTUnwrap(item.call, item.name) + let event = try XCTUnwrap(Self.event(of: call.method), item.name) + XCTAssertEqual(NotificationsAPIImpl.callName(of: event), call.name, item.name) + let refusal = NotificationsAPIImpl.refusal(code: call.args["code"] as? String ?? "", type: call.args["type"] as? String ?? "") + if let expected = item.expectedError { + XCTAssertTrue(refusal.map(expected.matches) == true, "\(item.name): \(String(describing: refusal))") + continue + } + XCTAssertNil(refusal, item.name) + let request = try XCTUnwrap(item.request, item.name) + XCTAssertEqual(request.method, "POST", item.name) + XCTAssertEqual(request.path, event.path, item.name) + XCTAssertEqual(request.body["code"] as? String, call.args["code"] as? String, item.name) + XCTAssertEqual(request.body["type"] as? String, call.args["type"] as? String, item.name) + XCTAssertTrue(EventQueue.sessionlessPaths.contains(request.path), "\(item.name): an event of a push, without a session") + } + } + + func test_every_token_of_the_fixture_goes_with_its_ios_platform_or_is_refused_before_anything_goes() throws { + let cases = try Self.iosCases().filter { $0.call?.method == "setPushToken" && $0.response == nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let call = try XCTUnwrap(item.call, item.name) + let provider = try XCTUnwrap(Rees46.PushProvider(rawValue: call.args["provider"] as? String ?? ""), item.name) + let token = call.args["token"] as? String ?? "" + let refusal = NotificationsAPIImpl.refusal(token: token, provider: provider) + if let expected = item.expectedError { + XCTAssertTrue(refusal.map(expected.matches) == true, "\(item.name): \(String(describing: refusal))") + continue + } + XCTAssertNil(refusal, item.name) + let request = try XCTUnwrap(item.request, item.name) + XCTAssertEqual(request.path, "mobile_push_tokens", item.name) + XCTAssertEqual(request.body["token"] as? String, token, item.name) + XCTAssertEqual(request.body["platform"] as? String, provider.iosPlatform, item.name) + XCTAssertNil(request.body["push_provider"], "\(item.name): iOS sends none") + } + } + + // MARK: - completion and async + + func test_the_async_form_returns_or_throws_the_result_of_the_completion() async { + do { + try await NotificationsAPIImpl.awaiting { done in DispatchQueue.global().async { done(.success(())) } } + } catch { + XCTFail("\(error)") + } + do { + try await NotificationsAPIImpl.awaiting { $0(.failure(.shopBlocked)) } + XCTFail("it throws") + } catch { + XCTAssertEqual(error as? Rees46.SdkError, .shopBlocked) + } + } + + func test_a_cancelled_task_throws_cancelled_and_starts_nothing() async { + let started = Guarded(false) + let task = _Concurrency.Task { + withUnsafeCurrentTask { $0?.cancel() } + try await NotificationsAPIImpl.awaiting { done in + started.current = true + done(.success(())) + } + } + do { + try await task.value + XCTFail("it throws") + } catch { + XCTAssertEqual(error as? Rees46.SdkError, .cancelled) + } + XCTAssertFalse(started.current) + } + + func test_cancelling_a_long_wait_ends_it_as_cancelled_only_where_it_says_so() async throws { + let pending = Guarded<((Result) -> Void)?>(nil) + let task = _Concurrency.Task { + try await NotificationsAPIImpl.awaiting(endsOnCancel: true) { pending.current = $0 } + } + while pending.current == nil { + await _Concurrency.Task.yield() + } + task.cancel() + do { + try await task.value + XCTFail("it throws") + } catch { + XCTAssertEqual(error as? Rees46.SdkError, .cancelled) + } + // The call's own result later changes nothing. + pending.current?(.success(())) + + // Without `endsOnCancel` the wait is for the call's result. + let call = Guarded<((Result) -> Void)?>(nil) + let event = _Concurrency.Task { + try await NotificationsAPIImpl.awaiting { call.current = $0 } + } + while call.current == nil { + await _Concurrency.Task.yield() + } + event.cancel() + call.current?(.success(())) + try await event.value + } + + func test_a_completion_is_called_once_on_the_main_thread() { + let done = expectation(description: "completion") + let again = expectation(description: "a second completion") + again.isInverted = true + let calls = Guarded(0) + let finish = NotificationsAPIImpl.onMain { _ in + XCTAssertTrue(Thread.isMainThread) + calls.mutate { $0 += 1 } + if calls.current == 1 { done.fulfill() } else { again.fulfill() } + } + DispatchQueue.global().async { + finish(.success(())) + finish(.failure(.network)) + } + wait(for: [done], timeout: 5) + wait(for: [again], timeout: 0.3) + } +} + +/// A value under a lock, for the closures of these tests. +private final class Guarded { + private let lock = NSLock() + private var value: Value + + init(_ value: Value) { + self.value = value + } + + var current: Value { + get { lock.lock(); defer { lock.unlock() }; return value } + set { lock.lock(); value = newValue; lock.unlock() } + } + + func mutate(_ change: (inout Value) -> Void) { + lock.lock(); defer { lock.unlock() } + change(&value) + } +} diff --git a/Tests/REES46CoreTests/PredictPackageTests.swift b/Tests/REES46CoreTests/PredictPackageTests.swift new file mode 100644 index 00000000..d9001909 --- /dev/null +++ b/Tests/REES46CoreTests/PredictPackageTests.swift @@ -0,0 +1,55 @@ +// +// PredictPackageTests.swift +// REES46CoreTests +// +// `predict.getProbabilityToPurchase` without a server: the request it builds, and what it makes of each +// answer of the proposed fixture. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class PredictPackageTests: XCTestCase { + + func test_the_request_of_the_predict_fixture_goes_to_api_v3_with_no_contact_and_the_general_timeout() throws { + let cases = try FixtureCase.load("predict").filter { $0.item.request != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + FixtureMatching.assert(PredictAPIImpl.probabilityRequest.coreRequest, is: item) + } + let request = PredictAPIImpl.probabilityRequest + XCTAssertTrue(request.query.isEmpty, "the device id is the customer: no email, phone or other contact") + XCTAssertNil(request.timeout, "the general read timeout, not 15 seconds of its own") + XCTAssertEqual(request.host, .app, "the host of API v3: the API host's old path answers 503") + } + + func test_the_answers_of_the_predict_fixture_end_as_it_says() throws { + let cases = try FixtureCase.load("predict").filter { $0.item.response?.status != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let result = try FixtureMatching.outcome(of: item, for: PredictAPIImpl.probabilityRequest, call: "predict.getProbabilityToPurchase") + FixtureMatching.assert(result, as: item) { value in + ["probability": value.probability, "clientId": FixtureMatching.field(value.clientId)] as [String: Any] + } + } + } + + func test_numbers_may_come_as_strings_and_an_answer_without_a_payload_is_no_forecast() throws { + let request = PredictAPIImpl.probabilityRequest + let read = try request.decode(Data(#"{"status": "success", "payload": {"probability": "0.73", "client_id": 12345678901}}"#.utf8)) + XCTAssertEqual(read.probability, 0.73, accuracy: 1e-9) + XCTAssertEqual(read.clientId, "12345678901", "a number is its digits") + XCTAssertNil(try request.decode(Data(#"{"payload": {"probability": 0.1}}"#.utf8)).clientId, "no client_id: no customer") + XCTAssertNil(try request.decode(Data(#"{"payload": {"probability": 0.1, "client_id": ""}}"#.utf8)).clientId) + XCTAssertThrowsError(try request.decode(Data())) + XCTAssertThrowsError(try request.decode(Data(#"{"payload": {"probability": null}}"#.utf8))) + XCTAssertThrowsError(try request.decode(Data(#"{"probability": 0.42, "client_id": 1}"#.utf8)), "the old path's answer") + } + + func test_the_predict_fixture_is_proposed_until_the_contract_has_one() { + XCTAssertFalse( + FileManager.default.fileExists(atPath: ContractFixtures.url("predict").path), + "the contract has predict.json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one" + ) + } +} diff --git a/Tests/REES46CoreTests/ReviewsFixtureCalls.swift b/Tests/REES46CoreTests/ReviewsFixtureCalls.swift new file mode 100644 index 00000000..75eedbd4 --- /dev/null +++ b/Tests/REES46CoreTests/ReviewsFixtureCalls.swift @@ -0,0 +1,225 @@ +// +// ReviewsFixtureCalls.swift +// REES46CoreTests, REES46Tests +// +// The calls of the `reviews` fixture (`Fixtures/proposed/reviews.json`) made from their arguments, and the +// methods' values written by the contract's field names, so a value is compared with a case's `result`. +// The package tests and the demo app's tests compile this one file. +// + +import Foundation +@_spi(Bridge) @testable import REES46 + +enum ReviewsFixtureCalls { + + // MARK: - The request of a call + + /// A request of `reviews` without its type: what it sends, and how an answer becomes its value. + struct Request { + let method: CoreRequest.Method + let path: String + let host: ApiHost + let query: [String: String] + let body: [String: Any] + /// The method's value of `response`, or its error. + let value: (NetworkClient.Response, SdkLogger) -> Result + } + + /// The request `call` builds; throws what the method refuses before it sends anything. + static func request(for call: ContractCase.Call) throws -> Request { + let args = Arguments(call.args) + let name = call.name + switch call.method { + case "createNps": + return erase(name, try ReviewsAPIImpl.scoreRequest( + .nps, rate: args.int("rate"), channel: args.string("channel"), subject: args.string("category"), + orderId: args.optional("orderId"), comment: args.optional("comment"), label: args.optional("label") + )) + case "createCsat": + return erase(name, try ReviewsAPIImpl.scoreRequest( + .csat, rate: args.int("rate"), channel: args.string("channel"), subject: args.string("campaign"), + orderId: args.optional("orderId"), comment: args.optional("comment"), label: args.optional("label") + )) + case "createCes": + return erase(name, try ReviewsAPIImpl.scoreRequest( + .ces, rate: args.int("rate"), channel: args.string("channel"), subject: args.string("campaign"), + orderId: args.optional("orderId"), comment: args.optional("comment"), label: args.optional("label") + )) + case "getNpsCategories": + return erase(name, ReviewsAPIImpl.npsCategoriesRequest) + case "getNpsChannels": + return erase(name, ReviewsAPIImpl.npsChannelsRequest) + case "getCsatCampaigns": + return erase(name, ReviewsAPIImpl.csatCampaignsRequest) + case "getCesCampaigns": + return erase(name, ReviewsAPIImpl.cesCampaignsRequest) + case "getProductReviews": + return erase(name, try ReviewsAPIImpl.productReviewsRequest( + itemId: args.string("itemId"), limit: args.optionalInt("limit"), offset: args.optionalInt("offset") + )) + case "getClientReviews": + return erase(name, try ReviewsAPIImpl.clientReviewsRequest(orderId: args.string("orderId"))) + default: + throw Unknown(method: call.method) + } + } + + struct Unknown: Error { + let method: String + } + + private static func erase(_ name: String, _ request: ApiRequest) -> Request { + Request(method: request.method, path: request.path, host: request.host, query: request.query, body: request.body) { response, logger in + NamespaceRequests.value(of: response, for: request, call: name, logger: logger).map { $0 as Any } + } + } + + // MARK: - The call through the namespace + + /// Calls the method of `call` on `reviews` with its `completion`; `completion` gets the value as `Any`. + static func run(_ call: ContractCase.Call, on reviews: ReviewsAPI, completion: @escaping (Result) -> Void) { + let args = Arguments(call.args) + func done(_ result: Result) { + completion(result.map { $0 as Any }) + } + switch call.method { + case "createNps": + reviews.createNps( + rate: args.int("rate"), channel: args.string("channel"), category: args.string("category"), + orderId: args.optional("orderId"), comment: args.optional("comment"), label: args.optional("label"), completion: done + ) + case "createCsat": + reviews.createCsat( + rate: args.int("rate"), channel: args.string("channel"), campaign: args.string("campaign"), + orderId: args.optional("orderId"), comment: args.optional("comment"), label: args.optional("label"), completion: done + ) + case "createCes": + reviews.createCes( + rate: args.int("rate"), channel: args.string("channel"), campaign: args.string("campaign"), + orderId: args.optional("orderId"), comment: args.optional("comment"), label: args.optional("label"), completion: done + ) + case "getNpsCategories": + reviews.getNpsCategories(completion: done) + case "getNpsChannels": + reviews.getNpsChannels(completion: done) + case "getCsatCampaigns": + reviews.getCsatCampaigns(completion: done) + case "getCesCampaigns": + reviews.getCesCampaigns(completion: done) + case "getProductReviews": + reviews.getProductReviews( + itemId: args.string("itemId"), limit: args.optionalInt("limit"), offset: args.optionalInt("offset"), completion: done + ) + case "getClientReviews": + reviews.getClientReviews(orderId: args.string("orderId"), completion: done) + default: + completion(.failure(.invalidArgument("the fixture calls an unknown method \(call.method)"))) + } + } + + /// The arguments of a call by the contract's names. + private struct Arguments { + let values: [String: Any] + + init(_ values: [String: Any]) { + self.values = values + } + + func string(_ name: String) -> String { + values[name] as? String ?? "" + } + + func optional(_ name: String) -> String? { + values[name] as? String + } + + func int(_ name: String) -> Int { + (values[name] as? NSNumber)?.intValue ?? 0 + } + + func optionalInt(_ name: String) -> Int? { + (values[name] as? NSNumber)?.intValue + } + } + + /// The host the contract puts `path` on: API v3 — the polls — on `appDomain`, the rest on the API. + static func host(of path: String) -> ApiHost { + path.hasPrefix("api/v3/") ? .app : .api + } + + // MARK: - Values by the contract's names + + /// `value` — a model of `reviews` or a list of them — as JSON with the contract's field names; an + /// empty field is left out, as a case's `result` leaves it out. + static func json(_ value: Any) -> Any { + switch value { + case let list as [Any]: + return list.map(json) + case let review as PollReview: + return ["id": review.id] + case let category as NpsCategory: + return compact([ + "code": category.code, "name": category.name, + "detractorQuestion": category.detractorQuestion, "passiveQuestion": category.passiveQuestion, + "promoterQuestion": category.promoterQuestion, "detractorSuccess": category.detractorSuccess, + "passiveSuccess": category.passiveSuccess, "promoterSuccess": category.promoterSuccess, + "buttonLabel": category.buttonLabel, + ]) + case let campaign as CsatCampaign: + return compact([ + "code": campaign.code, "name": campaign.name, + "dissatisfiedQuestion": campaign.dissatisfiedQuestion, "neutralQuestion": campaign.neutralQuestion, + "satisfiedQuestion": campaign.satisfiedQuestion, "dissatisfiedSuccess": campaign.dissatisfiedSuccess, + "neutralSuccess": campaign.neutralSuccess, "satisfiedSuccess": campaign.satisfiedSuccess, + "buttonLabel": campaign.buttonLabel, + ]) + case let campaign as CesCampaign: + return compact([ + "code": campaign.code, "name": campaign.name, + "difficultQuestion": campaign.difficultQuestion, "neutralQuestion": campaign.neutralQuestion, + "easyQuestion": campaign.easyQuestion, "difficultSuccess": campaign.difficultSuccess, + "neutralSuccess": campaign.neutralSuccess, "easySuccess": campaign.easySuccess, + "buttonLabel": campaign.buttonLabel, + ]) + case let channel as PollChannel: + return ["code": channel.code, "name": channel.name] + case let response as ProductReviewsResponse: + var ratings: [String: Any] = [:] + response.summary.ratings.forEach { ratings[String($0.key)] = $0.value } + return [ + "summary": compact(["count": response.summary.count, "averageRating": response.summary.averageRating, "ratings": ratings]), + "reviews": response.reviews.map(json), + ] + case let review as ProductReview: + return compact([ + "id": review.id, "rating": review.rating, "comment": review.comment, "author": review.author, + "createdAt": review.createdAt, + ]) + case let review as ClientReview: + return compact([ + "id": review.id, "itemId": review.itemId, "orderId": review.orderId, "rating": review.rating, + "comment": review.comment, "state": review.state?.rawValue, "createdAt": review.createdAt, + ]) + default: + return "\(value)" + } + } + + /// Whether `value` is the case's `expected` result. + static func matches(_ value: Any, _ expected: Any?) -> Bool { + guard let expected = expected else { return false } + return canonical(json(value)) == canonical(expected) + } + + /// JSON with sorted keys: two values are the same JSON when their texts are. + static func canonical(_ value: Any) -> String { + guard let data = try? JSONSerialization.data(withJSONObject: value, options: [.sortedKeys, .fragmentsAllowed]) else { + return "not JSON: \(value)" + } + return String(decoding: data, as: UTF8.self) + } + + private static func compact(_ fields: [String: Any?]) -> [String: Any] { + fields.compactMapValues { $0 } + } +} diff --git a/Tests/REES46CoreTests/ReviewsPackageTests.swift b/Tests/REES46CoreTests/ReviewsPackageTests.swift new file mode 100644 index 00000000..4d0f55ce --- /dev/null +++ b/Tests/REES46CoreTests/ReviewsPackageTests.swift @@ -0,0 +1,218 @@ +// +// ReviewsPackageTests.swift +// REES46CoreTests +// +// `reviews` without a server: the request each call of the proposed fixture builds — its host too — +// or the argument it refuses, what the request path makes of each answer, and the host of API v3 in the +// client's URL. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class ReviewsPackageTests: XCTestCase { + + private let logger = SdkLogger(shopId: "package-\(UUID().uuidString)", level: .none) + + // MARK: - The fixture + + func test_each_call_of_the_fixture_builds_its_request_on_its_host_or_refuses_its_argument() throws { + let cases = try ContractFixtures.fixture("reviews", from: .proposed).filter { $0.response == nil } + XCTAssertGreaterThanOrEqual(cases.count, 20) + var methods: Set = [] + for item in cases { + let call = try XCTUnwrap(item.call, item.name) + methods.insert(call.method) + if let error = item.expectedError { + XCTAssertThrowsError(try ReviewsFixtureCalls.request(for: call), item.name) { thrown in + let refusal = thrown as? Rees46.SdkError + XCTAssertTrue(refusal.map(error.matches) == true, "\(item.name): \(thrown)") + } + continue + } + let expected = try XCTUnwrap(item.request, item.name) + let request = try ReviewsFixtureCalls.request(for: call) + XCTAssertEqual(request.method.rawValue, expected.method, item.name) + XCTAssertEqual(request.path, expected.path, item.name) + XCTAssertEqual(request.host, ReviewsFixtureCalls.host(of: expected.path), item.name) + // Only the fields the case lists: the common ones the core adds later. + XCTAssertEqual(request.query, expected.query, item.name) + XCTAssertEqual(ReviewsFixtureCalls.canonical(request.body), ReviewsFixtureCalls.canonical(expected.body), item.name) + } + XCTAssertEqual(methods.count, 9, "every method of the namespace: \(methods.sorted())") + } + + func test_each_answer_of_the_fixture_ends_as_the_fixture_says() throws { + // A case without an answer runs over the stub server (`ReviewsRequestTests`). + let cases = try ContractFixtures.fixture("reviews", from: .proposed).filter { $0.response?.status != nil } + XCTAssertGreaterThanOrEqual(cases.count, 20) + for item in cases { + let call = try XCTUnwrap(item.call, item.name) + let response = try XCTUnwrap(item.response, item.name) + let status = try XCTUnwrap(response.status, item.name) + let request = try ReviewsFixtureCalls.request(for: call) + let answer = NetworkClient.Response( + status: status, body: response.body, retryAfter: nil, + result: NetworkClient.classify(status: status, body: response.body, path: request.path) + ) + switch request.value(answer, logger) { + case .success(let value): + XCTAssertNil(item.expectedError, "\(item.name): \(value)") + XCTAssertTrue( + ReviewsFixtureCalls.matches(value, item.expect["result"]), + "\(item.name): \(ReviewsFixtureCalls.canonical(ReviewsFixtureCalls.json(value)))" + ) + case .failure(let error): + XCTAssertTrue(item.expectedError?.matches(error) == true, "\(item.name): \(error), expected \(String(describing: item.expectedError))") + } + } + } + + func test_the_reviews_fixture_is_proposed_until_the_contract_has_one() throws { + XCTAssertEqual(try ContractFixtures.load("reviews", from: .proposed)["contract"] as? String, ContractFixtures.version) + XCTAssertFalse( + FileManager.default.fileExists(atPath: ContractFixtures.url("reviews").path), + "the contract has reviews.json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one" + ) + } + + // MARK: - Answers beside the fixture + + /// The value of `body`, a `200`, for `request`. + private func value(_ request: ReviewsFixtureCalls.Request, _ body: String) -> Result { + let data = Data(body.utf8) + let answer = NetworkClient.Response(status: 200, body: data, retryAfter: nil, result: NetworkClient.classify(status: 200, body: data)) + return request.value(answer, logger) + } + + private func call(_ method: String, _ args: [String: Any] = [:]) throws -> ReviewsFixtureCalls.Request { + try ReviewsFixtureCalls.request(for: ContractCase.Call(namespace: "reviews", method: method, args: args)) + } + + func test_an_answer_without_a_body_is_an_empty_list_or_no_reviews_but_no_score() throws { + for method in ["getNpsCategories", "getNpsChannels", "getCsatCampaigns", "getCesCampaigns"] { + XCTAssertEqual((try? value(try call(method), "").get() as? [Any])?.count, 0, method) + } + XCTAssertEqual((try? value(try call("getClientReviews", ["orderId": "A-1"]), "").get() as? [ClientReview])?.count, 0) + let none = try? value(try call("getProductReviews", ["itemId": "37"]), "").get() as? ProductReviewsResponse + XCTAssertEqual(none, ProductReviewsResponse(summary: ProductRatingSummary(count: 0), reviews: [])) + for method in ["createNps", "createCsat", "createCes"] { + let score = try call(method, ["rate": 5, "channel": "c", "category": "x", "campaign": "x"]) + XCTAssertEqual(value(score, "").error, .decoding, "\(method): a score without its id") + XCTAssertEqual(value(score, "{}").error, .decoding) + XCTAssertEqual(value(score, #"{"payload": {"review": {"id": 2.5}}}"#).error, .decoding) + } + } + + func test_a_dictionary_needs_its_list_in_the_payload() throws { + let categories = try call("getNpsCategories") + XCTAssertEqual(value(categories, "{}").error, .decoding) + XCTAssertEqual(value(categories, #"{"payload": {"categories": null}}"#).error, .decoding) + XCTAssertEqual(value(categories, #"{"payload": {"categories": {"code": "a"}}}"#).error, .decoding) + XCTAssertEqual(value(categories, #"{"payload": []}"#).error, .decoding) + XCTAssertEqual(value(categories, "[]").error, .decoding) + let read = try? value(categories, #"{"payload": {"categories": [{"code": 7, "name": "Seven"}, {"code": "x", "name": " "}, null, 3]}}"#).get() as? [NpsCategory] + XCTAssertEqual(read, [NpsCategory(code: "7", name: "Seven")], "a code as a number is its digits; a blank name is none") + } + + func test_the_rating_of_a_product_reads_its_scores_leniently() throws { + let reviews = try call("getProductReviews", ["itemId": "37"]) + let body = #"{"payload": {"summary": {"count": "2", "average_rating": "4.5", "ratings": {"4": 1, "5": "1", "x": 3, "3": null}}, "reviews": []}}"# + let read = try? value(reviews, body).get() as? ProductReviewsResponse + XCTAssertEqual(read?.summary, ProductRatingSummary(count: 2, averageRating: 4.5, ratings: [4: 1, 5: 1])) + XCTAssertEqual(value(reviews, #"{"payload": {"summary": {"average_rating": 4}, "reviews": []}}"#).error, .decoding, "no count") + XCTAssertEqual(value(reviews, #"{"payload": {"summary": {"count": 0}}}"#).error, .decoding, "no list") + let noRatings = try? value(reviews, #"{"payload": {"summary": {"count": 0, "ratings": [1, 2]}, "reviews": []}}"#).get() as? ProductReviewsResponse + XCTAssertEqual(noRatings?.summary.ratings, [:]) + } + + func test_optional_arguments_go_only_when_they_are_given() throws { + let blank = try call("createNps", ["rate": 9, "channel": "c", "category": "x", "orderId": " ", "comment": "\n", "label": ""]) + XCTAssertEqual(blank.body.keys.sorted(), ["category", "channel", "rate"]) + let given = try call("createCsat", ["rate": 3, "channel": "c", "campaign": "x", "comment": " ok "]) + XCTAssertEqual(given.body["comment"] as? String, " ok ", "a comment goes as it is") + XCTAssertEqual(given.body["rate"] as? Int, 3, "the score is a number of JSON") + XCTAssertEqual(try call("getProductReviews", ["itemId": "37", "limit": 100, "offset": 0]).query, ["product": "37", "limit": "100", "offset": "0"]) + XCTAssertThrowsError(try call("getClientReviews", ["orderId": " \n"])) + XCTAssertThrowsError(try call("createNps", ["rate": 9, "channel": "\t", "category": "x"])) + } + + func test_the_answer_of_a_score_with_an_error_in_a_2xx_is_decoding() throws { + let score = try call("createNps", ["rate": 9, "channel": "c", "category": "x"]) + XCTAssertEqual(value(score, #"{"status": "error", "payload": {"review": {"id": 1}}}"#).error, .decoding) + XCTAssertEqual((try? value(score, #"{"status": "success", "payload": {"review": {"id": " 41 "}}}"#).get()) as? PollReview, PollReview(id: 41)) + } + + // MARK: - The host of API v3 in the client + + func test_a_request_with_a_host_of_its_own_goes_there_and_the_others_to_the_api() async throws { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [HostCapture.self] + let client = NetworkClient( + baseURL: "https://api.example.test/", configuration: configuration, connectivity: AlwaysOnline(), logger: logger + ) { + CommonFields(shopId: "shop", deviceId: "did", sessionId: "sid", stream: "ios", segment: "A") + } + HostCapture.reset() + _ = await client.send(NetworkClient.Request(method: .get, path: "api/v3/polls/nps/channels", host: "app.cluster.test")) + _ = await client.send(NetworkClient.Request(method: .post, path: "api/v3/polls/nps/reviews", body: ["rate": 9], host: "app.cluster.test")) + _ = await client.send(NetworkClient.Request(method: .get, path: "reviews/product", query: ["product": "37"])) + let urls = HostCapture.urls + XCTAssertEqual(urls.map(\.host), ["app.cluster.test", "app.cluster.test", "api.example.test"]) + XCTAssertEqual(urls.map(\.scheme), ["https", "https", "https"]) + XCTAssertEqual(urls.map(\.path), ["/api/v3/polls/nps/channels", "/api/v3/polls/nps/reviews", "/reviews/product"]) + XCTAssertTrue(urls.first?.query?.contains("did=did") == true, "the common fields go to API v3 too") + await client.release() + } +} + +private extension Result { + var error: Failure? { + if case .failure(let error) = self { return error } + return nil + } +} + +/// Online, always. +private final class AlwaysOnline: ConnectivityMonitor { + var isOnline: Bool { true } + + func observe(_ handler: @escaping (Bool) -> Void) -> Cancellable { + handler(true) + return Cancellable {} + } +} + +/// Answers every request with `200 {}` and keeps its URL. +private final class HostCapture: URLProtocol { + + private static let lock = NSLock() + private static var seen: [URL] = [] + + static var urls: [URL] { + lock.lock(); defer { lock.unlock() } + return seen + } + + static func reset() { + lock.lock(); seen = []; lock.unlock() + } + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + if let url = request.url { + Self.lock.lock(); Self.seen.append(url); Self.lock.unlock() + } + guard let url = request.url, let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else { + client?.urlProtocol(self, didFailWithError: URLError(.badURL)) + return + } + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Data("{}".utf8)) + client?.urlProtocolDidFinishLoading(self) + } + + override func stopLoading() {} +} diff --git a/Tests/REES46CoreTests/SlidersPackageTests.swift b/Tests/REES46CoreTests/SlidersPackageTests.swift new file mode 100644 index 00000000..58e3c07c --- /dev/null +++ b/Tests/REES46CoreTests/SlidersPackageTests.swift @@ -0,0 +1,103 @@ +// +// SlidersPackageTests.swift +// REES46CoreTests +// +// `sliders.get` and the banner events of `tracking` without a server: the requests and the events they +// build, the arguments they refuse, and what `sliders.get` makes of each answer of the proposed fixture. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class SlidersPackageTests: XCTestCase { + + func test_the_requests_of_the_sliders_fixture_and_its_refusals() throws { + let cases = try FixtureCase.load("sliders").filter { $0.item.response == nil && $0.item.call?.namespace == "sliders" } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let make = { + try SlidersAPIImpl.getRequest( + code: item.args["code"] as? String ?? "", tags: item.args["tags"] as? [String], locationId: item.args["locationId"] as? String + ) + } + if item.item.request != nil { + FixtureMatching.assert(try make().coreRequest, is: item) + } else { + FixtureMatching.assertRefused(item, make) + } + } + } + + func test_the_answers_of_the_sliders_fixture_end_as_it_says() throws { + let cases = try FixtureCase.load("sliders").filter { $0.item.response?.status != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let request = try SlidersAPIImpl.getRequest(code: item.args["code"] as? String ?? "", tags: nil, locationId: nil) + FixtureMatching.assert(try FixtureMatching.outcome(of: item, for: request, call: "sliders.get"), as: item, json: Self.json(slider:)) + } + } + + func test_the_banner_events_of_the_fixture_and_their_refusals() throws { + let cases = try FixtureCase.load("sliders").filter { $0.item.call?.namespace == "tracking" } + XCTAssertEqual(Set(cases.map(\.method)), ["bannerView", "bannerClick"]) + for item in cases { + let event = try XCTUnwrap(BannerEvent(rawValue: item.method == "bannerView" ? "view" : "click")) + let make = { try event.body(bannerId: item.args["bannerId"] as? String ?? "", code: item.args["code"] as? String ?? "") } + if item.item.request != nil { + FixtureMatching.assert(CoreRequest(method: .post, path: BannerEvent.path, body: try make()), is: item) + } else { + FixtureMatching.assertRefused(item, make) + } + } + } + + func test_a_banner_event_sends_a_whole_number_and_no_recommended_by() throws { + let body = try BannerEvent.view.body(bannerId: "12", code: "homepage_mobile") + XCTAssertEqual(body["banner_id"] as? Int, 12) + XCTAssertNil(body["recommended_by"], "the address does not read it") + XCTAssertEqual(Set(body.keys), ["event", "banner_id", "recommended_code"], "the queue adds the shop, the device and the session") + XCTAssertEqual(try BannerEvent.view.body(bannerId: "4294967295", code: "c")["banner_id"] as? Int, 4_294_967_295) + for id in ["0", "-3", "+12", " 12", "12.5", "1e3", " ", "4294967296", "١٢"] { + XCTAssertThrowsError(try BannerEvent.click.body(bannerId: id, code: "c"), id) + } + XCTAssertThrowsError(try BannerEvent.click.body(bannerId: "12", code: " ")) + } + + func test_tags_are_refused_when_blank_and_lists_left_empty_are_not_sent() throws { + XCTAssertThrowsError(try SlidersAPIImpl.getRequest(code: "c", tags: [" "], locationId: nil)) + XCTAssertThrowsError(try SlidersAPIImpl.getRequest(code: " ", tags: nil, locationId: nil)) + let request = try SlidersAPIImpl.getRequest(code: "c", tags: [], locationId: " ") + XCTAssertEqual(request.query, ["code": "c"], "no contacts, no empty tags or location") + } + + func test_a_banner_needs_its_id_and_takes_the_sliders_code_when_it_has_none() throws { + let request = try SlidersAPIImpl.getRequest(code: "main", tags: nil, locationId: nil) + let json = #"{"payload":{"properties":{"code":"main"},"slides":[{"image_url":"a.jpg"},{"banner_id":5},{"banner_id":6,"recommended_code":"other"}]}}"# + let slider = try request.decode(Data(json.utf8)) + XCTAssertEqual(slider.banners.map(\.id), ["5", "6"], "a banner without banner_id cannot be tracked") + XCTAssertEqual(slider.banners.map(\.code), ["main", "other"]) + XCTAssertEqual(slider.width, 0) + XCTAssertThrowsError(try request.decode(Data()), "an answer without a body is not a slider") + XCTAssertEqual(try request.decode(Data(#"{"payload":{}}"#.utf8)).banners.count, 0) + } + + func test_the_sliders_fixture_is_proposed_until_the_contract_has_one() { + XCTAssertFalse( + FileManager.default.fileExists(atPath: ContractFixtures.url("sliders").path), + "the contract has sliders.json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one" + ) + } + + static func json(slider: Slider) -> [String: Any] { + [ + "code": slider.code, "width": slider.width, "height": slider.height, + "banners": slider.banners.map { banner -> [String: Any] in + [ + "id": banner.id, "code": banner.code, "imageUrl": FixtureMatching.field(banner.imageUrl), + "url": FixtureMatching.field(banner.url), "deeplinkIos": FixtureMatching.field(banner.deeplinkIos), + "deeplinkAndroid": FixtureMatching.field(banner.deeplinkAndroid), "html": FixtureMatching.field(banner.html), + ] + }, + ] + } +} diff --git a/Tests/REES46CoreTests/StoriesPackageTests.swift b/Tests/REES46CoreTests/StoriesPackageTests.swift new file mode 100644 index 00000000..f7695975 --- /dev/null +++ b/Tests/REES46CoreTests/StoriesPackageTests.swift @@ -0,0 +1,153 @@ +// +// StoriesPackageTests.swift +// REES46CoreTests +// +// `stories.get` without a server: the request it builds, and what it makes of each answer of the +// proposed fixture. +// + +import XCTest +@_spi(Bridge) @testable import REES46 + +final class StoriesPackageTests: XCTestCase { + + func test_the_requests_of_the_stories_fixture_and_its_refusals() throws { + let cases = try FixtureCase.load("stories").filter { $0.item.response == nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let make = { try StoriesAPIImpl.getRequest(code: item.args["code"] as? String ?? "") } + if item.item.request != nil { + FixtureMatching.assert(try make().coreRequest, is: item) + } else { + FixtureMatching.assertRefused(item, make) + } + } + } + + func test_the_answers_of_the_stories_fixture_end_as_it_says() throws { + // A case without an answer runs over the stub server (`StoriesPredictLoyaltySlidersTests`). + let cases = try FixtureCase.load("stories").filter { $0.item.response?.status != nil } + XCTAssertFalse(cases.isEmpty) + for item in cases { + let request = try StoriesAPIImpl.getRequest(code: item.args["code"] as? String ?? "") + let result = try FixtureMatching.outcome(of: item, for: request, call: "stories.get") + FixtureMatching.assert(result, as: item, json: Self.json(_:)) + } + } + + func test_the_code_is_one_segment_of_the_path_and_a_blank_one_is_refused() throws { + XCTAssertEqual(try StoriesAPIImpl.getRequest(code: "a/b c?d#e%").path, "stories/a%2Fb%20c%3Fd%23e%25") + XCTAssertEqual(try StoriesAPIImpl.getRequest(code: "115bd0b6").path, "stories/115bd0b6") + XCTAssertTrue(try StoriesAPIImpl.getRequest(code: "115bd0b6").query.isEmpty, "the core adds shop_id and did") + XCTAssertThrowsError(try StoriesAPIImpl.getRequest(code: " \n")) { error in + guard case .invalidArgument? = error as? Rees46.SdkError else { return XCTFail("\(error)") } + } + } + + func test_an_answer_without_a_body_is_not_a_block() throws { + let request = try StoriesAPIImpl.getRequest(code: "115bd0b6") + XCTAssertThrowsError(try request.decode(Data())) + XCTAssertEqual(try request.decode(Data("{}".utf8)).stories.count, 0, "an object without stories is a block without them") + } + + func test_the_opacity_of_a_text_block_reads_percents_and_fractions() throws { + func opacity(_ value: String) throws -> Double { + let json = #"{"stories":[{"slides":[{"elements":[{"type":"text_block","text_background_color_opacity":\#(value)}]}]}]}"# + let block = try StoriesAPIImpl.getRequest(code: "c").decode(Data(json.utf8)) + guard case .textBlock(let text)? = block.stories.first?.slides.first?.elements.first else { + XCTFail("no text block") + return -1 + } + return text.backgroundOpacity + } + XCTAssertEqual(try opacity(#""0%""#), 0) + XCTAssertEqual(try opacity(#""100%""#), 1) + XCTAssertEqual(try opacity(#""50""#), 0.5, accuracy: 1e-9) + XCTAssertEqual(try opacity(#"" 25% ""#), 0.25, accuracy: 1e-9) + XCTAssertEqual(try opacity("0.3"), 0.3, accuracy: 1e-9) + XCTAssertEqual(try opacity("80"), 0.8, accuracy: 1e-9) + XCTAssertEqual(try opacity("150"), 1, "at most 1") + XCTAssertEqual(try opacity("null"), 0) + XCTAssertEqual(try opacity(#""bad""#), 0) + XCTAssertEqual(try opacity("-5"), 0) + } + + func test_ids_come_as_numbers_and_a_slide_without_media_is_one_of_products() throws { + let json = #"{"id":7,"stories":[{"id":39,"slides":[{"id":"39_0","type":"","duration":-3},{"id":40,"type":"gif"},{"id":41,"type":"video","duration":"7"}]}]}"# + let block = try StoriesAPIImpl.getRequest(code: "c").decode(Data(json.utf8)) + XCTAssertEqual(block.id, "7") + let slides = try XCTUnwrap(block.stories.first?.slides) + XCTAssertEqual(slides.map(\.id), ["39_0", "40", "41"]) + XCTAssertEqual(slides.map(\.type), [.product, .product, .video]) + XCTAssertEqual(slides.map(\.duration), [10, 10, 7]) + } + + func test_the_stories_fixture_is_proposed_until_the_contract_has_one() { + XCTAssertFalse( + FileManager.default.fileExists(atPath: ContractFixtures.url("stories").path), + "the contract has stories.json now: copy it into contract-\(ContractFixtures.version) and remove the proposed one" + ) + } + + // MARK: - The block by the contract's names + + static func json(_ block: StoriesBlock) -> [String: Any] { + ["id": block.id, "stories": block.stories.map(json(story:))] + } + + private static func json(story: Story) -> [String: Any] { + [ + "id": story.id, "name": story.name, "avatar": story.avatar, "viewed": story.viewed, "pinned": story.pinned, + "startPosition": story.startPosition, "slides": story.slides.map(json(slide:)), + ] + } + + private static func json(slide: StorySlide) -> [String: Any] { + let type: String + switch slide.type { + case .image: type = "image" + case .video: type = "video" + case .product: type = "product" + } + return [ + "id": slide.id, "type": type, "background": slide.background, "backgroundColor": slide.backgroundColor, + "preview": slide.preview, "duration": slide.duration, "elements": slide.elements.map(json(element:)), + ] + } + + private static func json(element: StoryElement) -> [String: Any] { + switch element { + case .button(let button): + return [ + "type": "button", "title": button.title, "link": button.link, "linkAndroid": button.linkAndroid, + "linkIos": button.linkIos, "background": button.background, "color": button.color, "textBold": button.textBold, + ] + case .product(let product): + return ["type": "product", "title": product.title, "item": FixtureMatching.field(product.item.map(json(product:)))] + case .products(let products): + return [ + "type": "products", "showLabel": products.showLabel, "hideLabel": products.hideLabel, + "products": products.products.map(json(product:)), + ] + case .textBlock(let text): + return [ + "type": "textBlock", "text": text.text, "fontSize": text.fontSize, "fontType": text.fontType, + "bold": text.bold, "italic": text.italic, "textAlign": text.textAlign, "textColor": text.textColor, + "backgroundColor": text.backgroundColor, "backgroundOpacity": text.backgroundOpacity, + "lineSpacing": text.lineSpacing, "yOffset": text.yOffset, "promocode": FixtureMatching.field(text.promocode), + ] + } + } + + private static func json(product: StoryProduct) -> [String: Any] { + [ + "id": product.id, "name": product.name, "brand": product.brand, "picture": product.picture, + "imageUrl": product.imageUrl, "price": product.price, "priceFormatted": product.priceFormatted, + "oldPrice": FixtureMatching.field(product.oldPrice), "oldPriceFormatted": product.oldPriceFormatted, + "discountPercent": product.discountPercent, "promocode": product.promocode, + "priceWithPromocode": product.priceWithPromocode, "priceWithPromocodeFormatted": product.priceWithPromocodeFormatted, + "currency": product.currency, "url": product.url, "deeplinkAndroid": product.deeplinkAndroid, + "deeplinkIos": product.deeplinkIos, + ] + } +}