Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removing full forms code #260

Merged
merged 4 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Sources/KlaviyoCore/KlaviyoEnvironment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,6 @@ public func createNetworkSession() -> NetworkSession {

public enum KlaviyoDecodingError: Error {
case invalidType
case invalidJson
}

public struct DataDecoder {
Expand Down
38 changes: 0 additions & 38 deletions Sources/KlaviyoCore/Models/APIModels/FullFormsResponse.swift

This file was deleted.

7 changes: 0 additions & 7 deletions Sources/KlaviyoCore/Networking/KlaviyoEndpoint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,13 @@ public enum KlaviyoEndpoint: Equatable, Codable {
case createEvent(CreateEventPayload)
case registerPushToken(PushTokenPayload)
case unregisterPushToken(UnregisterPushTokenPayload)
case fetchForms

var httpScheme: String { "https" }

var httpMethod: RequestMethod {
switch self {
case .createProfile, .createEvent, .registerPushToken, .unregisterPushToken:
return .post
case .fetchForms:
return .get
}
}

Expand All @@ -37,8 +34,6 @@ public enum KlaviyoEndpoint: Equatable, Codable {
return "/client/push-tokens/"
case .unregisterPushToken:
return "/client/push-token-unregister/"
case .fetchForms:
return "/forms/api/v7/full-forms"
}
}

Expand All @@ -52,8 +47,6 @@ public enum KlaviyoEndpoint: Equatable, Codable {
return try environment.encodeJSON(AnyEncodable(payload))
case let .unregisterPushToken(payload):
return try environment.encodeJSON(AnyEncodable(payload))
case .fetchForms:
return nil
}
}
}
3 changes: 0 additions & 3 deletions Sources/KlaviyoCore/Networking/SDKRequestIterator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ public struct SDKRequest: Identifiable, Equatable {
case createProfile(ProfileInfo)
case saveToken(token: String, info: ProfileInfo)
case unregisterToken(token: String, info: ProfileInfo)
case fetchForms

static func fromEndpoint(request: KlaviyoRequest) -> RequestType {
switch request.endpoint {
Expand Down Expand Up @@ -74,8 +73,6 @@ public struct SDKRequest: Identifiable, Equatable {
phoneNumber: payload.data.attributes.profile.data.attributes.phoneNumber,
externalId: payload.data.attributes.profile.data.attributes.externalId,
anonymousId: payload.data.attributes.profile.data.attributes.anonymousId))
case .fetchForms:
return .fetchForms
}
}
}
Expand Down
15 changes: 0 additions & 15 deletions Sources/KlaviyoSwift/Klaviyo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -184,18 +184,3 @@ public struct KlaviyoSDK {
return false
}
}

// MARK: - SPI Private methods

// for internal use only

@_spi(KlaviyoPrivate)
extension KlaviyoSDK {
/// Fetch the active forms for the current user.
///
/// - warning: For internal use only. The host app should not manually call this method, as
/// the logic for fetching and displaying forms will be handled internally within the SDK.
public func fetchForms() {
dispatchOnMainThread(action: .fetchForms)
}
}
58 changes: 2 additions & 56 deletions Sources/KlaviyoSwift/StateManagement/StateManagement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,6 @@ enum KlaviyoAction: Equatable {
/// when setting individual profile props
case setProfileProperty(Profile.ProfileKey, AnyEncodable)

// fetches any active in-app forms that should be shown to the user
case fetchForms

// handles the full forms response from the server
case handleFormsResponse(FullFormsResponse)

/// resets the state for profile properties before dequeing the request
/// this is done in the case where there is http request failure due to
/// the data that was passed to the client endpoint
Expand All @@ -111,7 +105,7 @@ enum KlaviyoAction: Equatable {
case let .enqueueEvent(event) where event.metric.name == ._openedPush:
return false

case .enqueueEvent, .enqueueProfile, .fetchForms, .handleFormsResponse, .resetProfile, .resetStateAndDequeue, .setBadgeCount, .setEmail, .setExternalId, .setPhoneNumber, .setProfileProperty, .setPushEnablement, .setPushToken:
case .enqueueEvent, .enqueueProfile, .resetProfile, .resetStateAndDequeue, .setBadgeCount, .setEmail, .setExternalId, .setPhoneNumber, .setProfileProperty, .setPushEnablement, .setPushToken:
return true

case .cancelInFlightRequests, .completeInitialization, .deQueueCompletedResults, .flushQueue, .initialize, .networkConnectivityChanged, .requestFailed, .sendRequest, .start, .stop, .syncBadgeCount:
Expand Down Expand Up @@ -364,21 +358,7 @@ struct KlaviyoReducer: ReducerProtocol {
return .run { [numAttempts] send in
let result = await environment.klaviyoAPI.send(request, numAttempts)
switch result {
case let .success(data):
do {
switch request.endpoint {
case .fetchForms:
let formsResponse = try JSONDecoder().decode(FullFormsResponse.self, from: data)
await send(.handleFormsResponse(formsResponse))
default:
break
}
} catch let error as DecodingError {
environment.emitDeveloperWarning("Error decoding JSON response: \(error.localizedDescription)")
} catch {
environment.emitDeveloperWarning("An unexpected error occurred: \(error.localizedDescription)")
}

case .success:
await send(.deQueueCompletedResults(request))
case let .failure(error):
await send(handleRequestError(request: request, error: error, retryInfo: retryInfo))
Expand Down Expand Up @@ -557,40 +537,6 @@ struct KlaviyoReducer: ReducerProtocol {
}

return .task { .deQueueCompletedResults(request) }

case .fetchForms:
guard case .initialized = state.initalizationState,
let apiKey = state.apiKey
else {
return .none
}

let request = KlaviyoRequest(apiKey: apiKey, endpoint: .fetchForms)
state.enqueueRequest(request: request)

return .none

case let .handleFormsResponse(fullFormsResponse):
guard let firstForm = fullFormsResponse.fullForms.first else { return .none }

// TODO: handle the form data
// example: Update the state to display the form
// state.firstForm = firstForm
//
// for now, prettyprint to console
// (TODO: remove this debug code after we've handled the response appropriately!)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted]
do {
let data = try encoder.encode(fullFormsResponse)
if let jsonString = String(data: data, encoding: .utf8) {
print(jsonString)
}
} catch {
print("Failed to encode and pretty-print JSON: \(error)")
}

return .none
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/KlaviyoUI/KlaviyoUI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import Foundation

struct KlaviyoUI {
public struct KlaviyoUI {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be public anyways so keeping it in.

func helloWorld() {
print("Hello world!")
}
Expand Down
63 changes: 0 additions & 63 deletions Tests/KlaviyoSwiftTests/StateManagementTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -619,67 +619,4 @@ class StateManagementTests: XCTestCase {
await store.receive(.setPushEnablement(PushEnablement.authorized), timeout: TIMEOUT_NANOSECONDS)
await store.receive(.setBadgeCount(0))
}

@MainActor
func testFetchForms() async throws {
var initialState = INITIALIZED_TEST_STATE()
initialState.flushing = false
let store = TestStore(initialState: initialState, reducer: KlaviyoReducer())

environment.klaviyoAPI.send = { _, _ in .success(TEST_FULL_FORMS_SUCCESS.data(using: .utf8)!) }

let request = KlaviyoRequest(apiKey: initialState.apiKey!, endpoint: .fetchForms)

_ = await store.send(.fetchForms) {
$0.queue = [request]
}

_ = await store.send(.flushQueue) {
$0.flushing = true
$0.requestsInFlight = $0.queue
$0.queue = []
}

await store.receive(.sendRequest)

let expectedResponse = FullFormsResponse(
fullForms: [.init()],
formSettings: .init(),
dynamicInfoConfig: .init())

_ = await store.receive(.handleFormsResponse(expectedResponse))

_ = await store.receive(.deQueueCompletedResults(request)) {
$0.flushing = false
$0.requestsInFlight = []
}
}

@MainActor
func testFetchFormsDecodingError() async throws {
var initialState = INITIALIZED_TEST_STATE()
initialState.flushing = false
let store = TestStore(initialState: initialState, reducer: KlaviyoReducer())

environment.klaviyoAPI.send = { _, _ in .success(TEST_FULL_FORMS_INVALID_KEY.data(using: .utf8)!) }

let request = KlaviyoRequest(apiKey: initialState.apiKey!, endpoint: .fetchForms)

_ = await store.send(.fetchForms) {
$0.queue = [request]
}

_ = await store.send(.flushQueue) {
$0.flushing = true
$0.requestsInFlight = $0.queue
$0.queue = []
}

await store.receive(.sendRequest)

_ = await store.receive(.deQueueCompletedResults(request)) {
$0.flushing = false
$0.requestsInFlight = []
}
}
}
45 changes: 0 additions & 45 deletions Tests/KlaviyoSwiftTests/TestData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -185,51 +185,6 @@ let TEST_FAILURE_JSON_INVALID_EMAIL = """
}
"""

let TEST_FULL_FORMS_SUCCESS = """
{
"full_forms": [
{
"form_id": "KqQUEM",
"live_form_versions": [
{
"form_id": "KqQUEM",
"name": "phone-number-testing"
}
],
"name": "phone-number-testing",
"show_klaviyo_branding": false,
"dismissed_alerts": []
}
],
"form_settings": {
"shopify_visitor_api": {
"sync_SMS_consent": false,
"sync_email_consent": false
},
"attribution_settings": {
"attribution_metric_name": "Form submitted by profile",
"attribution_window_seconds": 7200
},
"enabled": true,
"per_session": false,
"time_delay_milliseconds": 300000
},
"dynamic_info_config": {}
}
"""

let TEST_FULL_FORMS_INVALID_KEY = """
{
"full_forms_bad_key": [
{
"form_id": "KqQUEM"
}
],
"form_setting": {},
"dynamic_info_config": {}
}
"""

extension KlaviyoSwiftEnvironment {
static let testStore = Store(initialState: KlaviyoState(queue: []), reducer: KlaviyoReducer())

Expand Down
Loading