lib/braze_ex/api/user_data.ex

# NOTE: This file is auto generated by OpenAPI Generator 6.2.0 (https://openapi-generator.tech).
# Do not edit this file manually.

defmodule BrazeEx.Api.UserData do
  @moduledoc """
  API calls for all endpoints tagged `UserData`.
  """

  alias BrazeEx.Connection
  import BrazeEx.RequestBuilder

  @doc """
  ## Create New User Aliases

  > Use this endpoint to add new user aliases for existing identified users, or to create new unidentified users. 


  Up to 50 user aliases may be specified per request. 

  **Adding a user alias for an existing user** requires an `external_id` to be included in the new user alias object. If the `external_id` is present in the object but there is no user with that `external_id`, the alias will not be added to any users. If an `external_id` is not present, a user will still be created but will need to be identified later. You can do this using the "Identifying Users" and the `users/identify` endpoint.

  **Creating a new alias-only user** requires the `external_id` to be omitted from the new user alias object. Once the user is created, use the `/users/track` endpoint to associate the alias-only user with attributes, events, and purchases, and the `/users/identify` endpoint to identify the user with an `external_id`.

  ## Prerequisites

  To use this endpoint, you'll need an [API key](https://braze.com/docs/api/api_key/) with the `users.alias.new` permission.

  ### Rate limit

  For customers who onboarded with Braze on or after September 16, 2021, we apply a shared rate limit of 20,000 requests per minute to this endpoint. This rate limit is shared with the `/users/delete`, `/users/identify`, `/users/merge`, and `/users/alias/update` endpoints, as documented in [API rate limits](https://www.braze.com/docs/api/api_limits/).

  ### Request parameters

  | Parameter | Required | Data Type | Description |
  | --- | --- | --- | --- |
  | `user_aliases` | Required | Array of new user alias objects | See [user alias object](https://www.braze.com/docs/api/objects_filters/user_alias_object/).  <br>  <br>For more information on `alias_name` and `alias_label`, check out our [User Aliases](https://www.braze.com/docs/user_guide/data_and_analytics/user_data_collection/user_profile_lifecycle/#user-aliases) documentation. |

  ### Parameters

  - `connection` (BrazeEx.Connection): Connection to server
  - `opts` (keyword): Optional parameters
    - `:"Content-Type"` (String.t): 
    - `:Authorization` (String.t): 
    - `:body` (String.t): 

  ### Returns

  - `{:ok, nil}` on success
  - `{:error, Tesla.Env.t}` on failure
  """
  @spec users_alias_new_post(Tesla.Env.client(), keyword()) ::
          {:ok, nil} | {:error, Tesla.Env.t()}
  def users_alias_new_post(connection, opts \\ []) do
    optional_params = %{
      :"Content-Type" => :headers,
      :Authorization => :headers,
      :body => :body
    }

    request =
      %{}
      |> method(:post)
      |> url("/users/alias/new")
      |> add_optional_params(optional_params, opts)
      |> ensure_body()
      |> Enum.into([])

    connection
    |> Connection.request(request)
    |> evaluate_response([
      {200, false}
    ])
  end

  @doc """
  ## Update User Alias

  > Use this endpoint to update existing user aliases. 


  Up to 50 user aliases may be specified per request.

  Updating a user alias requires `alias_label`, `old_alias_name`, and `new_alias_name` to be included in the update user alias object. If there is no user alias associated with the `alias_label` and `old_alias_name`, no alias will be updated. If the given `alias_label` and `old_alias_name` is found, then the `old_alias_name` will be updated to the `new_alias_name`.

  **Note:** This endpoint does not guarantee the sequence of `alias_updates` objects being updated.

  ## Prerequisites

  To use this endpoint, you'll need an [API key](https://braze.com/docs/api/api_key/) with the `users.alias.update` permission.

  ## Rate limit

  For customers who onboarded with Braze on or after September 16, 2021, we apply a shared rate limit of 20,000 requests per minute to this endpoint. This rate limit is shared with the `/users/delete`, `/users/identify`, `/users/merge`, and `/users/alias/update` endpoints, as documented in [API rate limits](https://www.braze.com/docs/api/api_limits/).

  ### Request parameters

  | Parameter | Required | Data Type | Description |
  | --- | --- | --- | --- |
  | `alias_updates` | Required | Array of update user alias objects | See [user alias object](https://www.braze.com/docs/api/objects_filters/user_alias_object/).  <br>  <br>For more information on `old_alias_name`, `new_alias_name`, and `alias_label`, refer to [User aliases](https://www.braze.com/docs/user_guide/data_and_analytics/user_data_collection/user_profile_lifecycle/#user-aliases). |

  ### Endpoint request body with update user alias object specification

  ``` json
  {
  "alias_label" : (required, string),
  "old_alias_name" : (required, string),
  "new_alias_name" : (required, string)
  }

  ```

  ### Parameters

  - `connection` (BrazeEx.Connection): Connection to server
  - `opts` (keyword): Optional parameters
    - `:"Content-Type"` (String.t): 
    - `:Authorization` (String.t): 
    - `:body` (String.t): 

  ### Returns

  - `{:ok, nil}` on success
  - `{:error, Tesla.Env.t}` on failure
  """
  @spec users_alias_update_post(Tesla.Env.client(), keyword()) ::
          {:ok, nil} | {:error, Tesla.Env.t()}
  def users_alias_update_post(connection, opts \\ []) do
    optional_params = %{
      :"Content-Type" => :headers,
      :Authorization => :headers,
      :body => :body
    }

    request =
      %{}
      |> method(:post)
      |> url("/users/alias/update")
      |> add_optional_params(optional_params, opts)
      |> ensure_body()
      |> Enum.into([])

    connection
    |> Connection.request(request)
    |> evaluate_response([
      {200, false}
    ])
  end

  @doc """
  ## Delete Users

  > Use this endpoint to delete any user profile by specifying a known user identifier. 


  Up to 50 `external_ids`, `user_aliases`, or `braze_ids` can be included in a single request. Only one of `external_ids`, `user_aliases`, or `braze_ids` can be included in a single request.

  > **Warning:** Deleting user profiles cannot be undone. It will permanently remove users which may cause discrepancies in your data. Learn more about what happens when you [delete a user profile via API](https://braze.com/docs/help/help_articles/api/delete_user/) in our Help documentation.  

  ## Prerequisites

  To use this endpoint, you'll need an [API key](https://braze.com/docs/api/api_key/) with the `users.delete` permission.


  ### Rate limit

  For customers who onboarded with Braze on or after September 16, 2021, we apply a shared rate limit of 20,000 requests per minute to this endpoint. This rate limit is shared with the `/users/delete`, `/users/identify`, `/users/merge`, and `/users/alias/update` endpoints, as documented in [API rate limits](https://www.braze.com/docs/api/api_limits/).

  ### Request parameter

  | Parameter | Required | Data Type | Description |
  | --- | --- | --- | --- |
  | `external_ids` | Optional | Array of strings | External identifiers for the users to delete. |
  | `user_aliases` | Optional | Array of user alias object | [User aliases](https://www.braze.com/docs/api/objects_filters/user_alias_object/) for the users to delete. |
  | `braze_ids` | Optional | Array of strings | Braze user identifiers for the users to delete. |

  ### Parameters

  - `connection` (BrazeEx.Connection): Connection to server
  - `opts` (keyword): Optional parameters
    - `:"Content-Type"` (String.t): 
    - `:Authorization` (String.t): 
    - `:body` (String.t): 

  ### Returns

  - `{:ok, nil}` on success
  - `{:error, Tesla.Env.t}` on failure
  """
  @spec users_delete_post(Tesla.Env.client(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t()}
  def users_delete_post(connection, opts \\ []) do
    optional_params = %{
      :"Content-Type" => :headers,
      :Authorization => :headers,
      :body => :body
    }

    request =
      %{}
      |> method(:post)
      |> url("/users/delete")
      |> add_optional_params(optional_params, opts)
      |> ensure_body()
      |> Enum.into([])

    connection
    |> Connection.request(request)
    |> evaluate_response([
      {200, false}
    ])
  end

  @doc """
  ## Identify Users

  > Use this endpoint to identify an unidentified (alias-only) user. 

  Calling `/users/identify` combines the alias-only profile with the identified profile and removes the alias-only profile.

  Identifying a user requires an `external_id` to be included in the `aliases_to_identify` object. If there is no user with that `external_id`, the `external_id` will simply be added to the aliased user's record, and the user will be considered identified. You can add up to 50 user aliases per request.

  Subsequently, you can associate multiple additional user aliases with a single `external_id`.

  - When these subsequent associations are made with the `merge_behavior` field set to `none`, only the push tokens and message history associated with the user alias are retained; any attributes, events, or purchases will be "orphaned" and not available on the identified user. One workaround is to export the aliased user's data before identification using the [<code>/users/export/ids</code> endpoint](https://www.braze.com/docs/api/endpoints/export/user_data/post_users_identifier/), then re-associate the attributes, events, and purchases with the identified user.
  - When associations are made with the `merge_behavior` field set to `merge`, this endpoint will merge specific fields found on the anonymous user to the identified user.
    

  > **Tip**: To prevent unexpected loss of data when identifying users, we highly recommend that you first refer to [data collection best practices](https://www.braze.com/docs/user_guide/data_and_analytics/user_data_collection/best_practices/#capturing-user-data-when-alias-only-user-info-is-already-present) to learn about capturing user data when alias-only user info is already present. 

  ## Prerequisites
  To use this endpoint, you'll need an [API key](https://braze.com/docs/api/api_key/) with the `users.identify` permission.


  ## Rate limit

  For customers who onboarded with Braze on or after September 16, 2021, we apply a shared rate limit of 20,000 requests per minute to this endpoint. This rate limit is shared with the `/users/delete`, `/users/identify`, `/users/merge`, and `/users/alias/update` endpoints, as documented in [API rate limits](https://www.braze.com/docs/api/api_limits/).

  ## Parameters

  | Parameter | Required | Data Type | Description |
  | --- | --- | --- | --- |
  | `aliases_to_identify` | Required | Array of aliases to identify object | See [alias to identify object](https://www.braze.com/docs/api/objects_filters/aliases_to_identify/) and [user alias object](https://www.braze.com/docs/api/objects_filters/user_alias_object/). |
  | `merge_behavior` | Optional | String | One of `none` or `merge` is expected. |

  > **Tip:** For more information on `alias_name` and `alias_label`, check out our [user aliases](https://www.braze.com/docs/user_guide/data_and_analytics/user_data_collection/user_profile_lifecycle#user-aliases) documentation. 


  ### Merge_behavior field

  Setting the `merge_behavior` field to `merge` sets the endpoint to merge any of the following fields found **exclusively** on the anonymous user to the identified user.

  - First name
  - Last name
  - Email
  - Gender
  - Date of birth
  - Phone number
  - Time zone
  - Home city
  - Country
  - Language
  - Session count (the sum of sessions from both profiles)
  - Date of first session (Braze will pick the earlier date of the two dates)
  - Date of last session (Braze will pick the later date of the two dates)
  - Custom attributes
  - Custom event and purchase event data (excluding event properties)
  - Custom event and purchase event properties for "X times in Y days" segmentation (where X<=50 and Y<=30)
  - Segmentable custom events summary
    - Event count (the sum from both profiles)
    - Event first occurred (Braze will pick the earlier date of the two dates)
    - Event last occurred (Braze will pick the later date of the two dates)
  - In-app purchase total in cents (the sum from both profiles)
  - Total number of purchases (the sum from both profiles)
  - Date of first purchase (Braze will pick the earlier date of the two dates)
  - Date of last purchase (Braze will pick the later date of the two dates)
  - App summaries
  - Last_X_at fields (Braze will update the fields if the orphaned profile fields are more recent)
  - Campaign summaries (Braze will pick the most recent date fields)
  - Workflow summaries (Braze will pick the most recent date fields)
  - Message and message engagement history
    

  Any of the following fields found on the anonymous user to the identified user:

  - Custom event and purchase event count and first date and last date timestamps
    - These merged fields will update "for X events in Y days" filters. For purchase events, these filters include "number of purchases in Y days" and "money spent in last Y days".

  Session data will only be merged if the app exists on both user profiles. For example, if our target user doesn't have an app summary for "ABCApp" but our original user does, the target user will have the "ABCApp" app summary on their profile after the merge.

  Setting the field to `none` will not merge any user data to the identified user profile.

  ### Parameters

  - `connection` (BrazeEx.Connection): Connection to server
  - `opts` (keyword): Optional parameters
    - `:"Content-Type"` (String.t): 
    - `:Authorization` (String.t): 
    - `:body` (String.t): 

  ### Returns

  - `{:ok, nil}` on success
  - `{:error, Tesla.Env.t}` on failure
  """
  @spec users_identify_post(Tesla.Env.client(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t()}
  def users_identify_post(connection, opts \\ []) do
    optional_params = %{
      :"Content-Type" => :headers,
      :Authorization => :headers,
      :body => :body
    }

    request =
      %{}
      |> method(:post)
      |> url("/users/identify")
      |> add_optional_params(optional_params, opts)
      |> ensure_body()
      |> Enum.into([])

    connection
    |> Connection.request(request)
    |> evaluate_response([
      {200, false}
    ])
  end

  @doc """
  ## Merge Users

  > Use this endpoint to merge one user into another user. 

  Up to 50 merges may be specified per request. This endpoint is asynchronous.

  ## Prerequisites

  To use this endpoint, you'll need an [API key](https://braze.com/docs/api/api_key/) with the `users.merge` permission.

  ## Rate limit

  For customers who onboarded with Braze on or after September 16, 2021, we apply a shared rate limit of 20,000 requests per minute to this endpoint. This rate limit is shared with the `/users/delete`, `/users/alias/new`, `/users/identify`, and `/users/alias/update` endpoints, as documented in [API rate limits](https://www.braze.com/docs/api/api_limits/).

  ## Request parameters

  | Parameter | Required | Data Type | Description |
  | --- | --- | --- | --- |
  | `merge_updates` | Required | Array | An object array. Each object should contain an `identifier_to_merge` object and an `identifier_to_keep` object, which should each reference a user either by `external_id` or `user_alias`. Both users being merged must be identified using the same method. |

  ### Merge_updates behavior

  **Important**: The endpoint does not guarantee the sequence of `merge_updates` objects being updated.

  This endpoint will merge any of the following fields found exclusively on the original user to the target user.

  - First name
  - Last name
  - Email
  - Gender
  - Date of birth
  - Phone number
  - Time zone
  - Home city
  - Country
  - Language
  - Session count (the sum of sessions from both profiles)
  - Date of first session (Braze will pick the earlier date of the two dates)
  - Date of last session (Braze will pick the later date of the two dates)
  - Custom attributes
  - Custom event and purchase event data (excluding event properties)
  - Custom event and purchase event properties for "X times in Y days" segmentation (where X<=50 and Y<=30)
  - Segmentable custom events summary
    - Event count (the sum from both profiles)
    - Event first occurred (Braze will pick the earlier date of the two dates)
    - Event last occurred (Braze will pick the later date of the two dates)
  - In-app purchase total in cents (the sum from both profiles)
  - Total number of purchases (the sum from both profiles)
  - Date of first purchase (Braze will pick the earlier date of the two dates)
  - Date of last purchase (Braze will pick the later date of the two dates)
  - App summaries
  - Last_X_at fields (Braze will update the fields if the orphaned profile fields are more recent)
  - Campaign summaries (Braze will pick the most recent date fields)
  - Workflow summaries (Braze will pick the most recent date fields)
    
  Session data will only be merged if the app exists on both user profiles. Note that message and message engagement history aren't retained after both user profiles are merged.

  #### Custom event date and purchase event date behavior
  Note that these merged fields will update "for X events in Y days" filters. For purchase events, these filters include "number of purchases in Y days" and "money spent in last Y days".


  ## Response

  There are two status code responses for this endpoint: `202` and `400`.

  ### Example success response

  The status code `202` could return the following response body.

  ``` json
  {
  "message": "success"
  }

  ```

  ### Example error response

  The status code `400` could return the following response body. Refer to Troubleshooting for more information about errors you may encounter.

  ``` json
  {
  "message": "'merge_updates' must be an array of objects"
  }

  ```

  ## Troubleshooting

  The following table lists possible error messages that may occur.

  | Error | Troubleshooting |
  | --- | --- |
  | `'merge_updates' must be an array of objects` | Ensure that `merge_updates` is an array of objects. |
  | `a single request may not contain more than 50 merge updates` | You can only specify up to 50 merge updates in a single request. |
  | `identifiers must be objects with an 'external_id' property that is a string, or 'user_alias' property that is an object` | Check the identifiers in your request. |
  | `identifiers must be objects of the same type` | Ensure that the identifier object types match. |
  | `'merge_updates' must only have 'identifier_to_merge' and 'identifier_to_keep'` | Ensure that `merge_updates` only contains the two objects `identifier_to_merge` and `identifier_to_keep`. |

  ### Parameters

  - `connection` (BrazeEx.Connection): Connection to server
  - `opts` (keyword): Optional parameters
    - `:"Content-Type"` (String.t): 
    - `:Authorization` (String.t): 
    - `:body` (String.t): 

  ### Returns

  - `{:ok, nil}` on success
  - `{:error, Tesla.Env.t}` on failure
  """
  @spec users_merge_post(Tesla.Env.client(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t()}
  def users_merge_post(connection, opts \\ []) do
    optional_params = %{
      :"Content-Type" => :headers,
      :Authorization => :headers,
      :body => :body
    }

    request =
      %{}
      |> method(:post)
      |> url("/users/merge")
      |> add_optional_params(optional_params, opts)
      |> ensure_body()
      |> Enum.into([])

    connection
    |> Connection.request(request)
    |> evaluate_response([
      {200, false}
    ])
  end

  @doc """
  ## Track Users

  > Use this endpoint to record custom events, purchases, and update user profile attributes. 


  **Note:** Braze processes the data passed via API at face value and customers should only pass deltas (changing data) to minimize unnecessary data point consumption. To read more, refer to [Data points](https://www.braze.com/docs/user_guide/onboarding_with_braze/data_points#data-points).

  ## Prerequisites

  To use this endpoint, you'll need an [API key](https://braze.com/docs/api/api_key/) with the `users.track` permission.

  Customers using the API for server-to-server calls may need to allowlist `rest.iad-01.braze.com` if they’re behind a firewall.

  ## Rate limit

  We apply a base speed limit of 50,000 requests per minute to this endpoint for all customers. Each request to the `/users/track` endpoint can contain up to 75 events, 75 attribute updates, and 75 purchases. Each object (event, attribute, and purchase arrays) can update one user each. In total, this means a maximum of 225 users can be updated in a single call. In addition, a single user profile can be updated by multiple objects.

  See our page on [API rate limits](https://www.braze.com/docs/api/api_limits/) for details, and reach out to your customer success manager if you need your limit increased.

  ## Request parameters

  For each of the request components listed in the following table, one of `external_id`, `user_alias`, or `braze_id` is required.

  | Parameter | Required | Data Type | Description |
  | --- | --- | --- | --- |
  | `attributes` | Optional | Array of attributes objects | See [user attributes object](https://www.braze.com/docs/api/objects_filters/user_attributes_object/) |
  | `events` | Optional | Array of event objects | See [events object](https://www.braze.com/docs/api/objects_filters/event_object/) |
  | `purchases` | Optional | Array of purchase objects | See [purchases object](https://www.braze.com/docs/api/objects_filters/purchase_object/) |

  ## Responses

  Upon using any of the aforementioned API requests you should receive one of the following three general responses: a successful message, a successful message with non-fatal errors, or a message with fatal errors.

  ### Successful message

  Successful messages will be met with the following response:

  ``` json
  {
  "message" : "success",
  "attributes_processed" : (optional, integer), if attributes are included in the request, this will return an integer of the number of external_ids with attributes that were queued to be processed,
  "events_processed" : (optional, integer), if events are included in the request, this will return an integer of the number of events that were queued to be processed,
  "purchases_processed" : (optional, integer), if purchases are included in the request, this will return an integer of the number of purchases that were queued to be processed,
  }

  ```

  ### Successful message with non-fatal errors

  If your message is successful but has non-fatal errors such as one invalid event object out of a long list of events, then you will receive the following response:

  ``` json
  {
  "message" : "success",
  "errors" : [
    {
      <minor error message>
    }
  ]
  }

  ```

  For success messages, any data that was not affected by an error in the `errors` array will still be processed.

  ### Message with fatal errors

  In the case of a success, any data that was not affected by an error in the `errors` array will still be processed. If your message has a fatal error you will receive the following response:

  ``` json
  {
  "message" : <fatal error message>,
  "errors" : [
    {
      <fatal error message>
    }
  ]
  }

  ```

  ### Fatal error response codes

  For status codes and associated error messages that will be returned if your request encounters a fatal error, reference [Fatal errors &amp; responses](https://www.braze.com/api/errors/#fatal-errors).

  If you receive the error “provided external_id is blacklisted and disallowed”, your request may have included a “dummy user.” For more information, refer to [Spam blocking](https://www.braze.com/docs/user_guide/data_and_analytics/user_data_collection/user_archival/#spam-blocking).

  ## Frequently asked questions

  ### What happens when multiple profiles with the same email address are found?

  If the `external_id` exists, the most recently updated profile with an external ID will be prioritized for updates. If the `external_id` doesn't exist, the most recently updated profile will be prioritized for updates.

  ### What happens if no profile with the email address currently exists?

  A new profile will be created and an email-only user will be created. An alias will not be created. The email field will be set to [test@braze.com](https://mailto:test@braze.com), as noted in the example request for updating a user profile by email address.

  ### How do you use `/users/track` to import legacy user data?

  You may submit data through the Braze API for a user who has not yet used your mobile app in order to generate a user profile. If the user subsequently uses the application all information following their identification via the SDK will be merged with the existing user profile you created via the API call. Any user behavior that is recorded anonymously by the SDK prior to identification will be lost upon merging with the existing API-generated user profile.

  The segmentation tool will include these users regardless of whether they have engaged with the app. If you want to exclude users uploaded via the User API who have not yet engaged with the app, simply add the filter: `Session Count > 0`.

  ### Parameters

  - `connection` (BrazeEx.Connection): Connection to server
  - `opts` (keyword): Optional parameters
    - `:"Content-Type"` (String.t): 
    - `:Authorization` (String.t): 
    - `:body` (String.t): 

  ### Returns

  - `{:ok, nil}` on success
  - `{:error, Tesla.Env.t}` on failure
  """
  @spec users_track_post(Tesla.Env.client(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t()}
  def users_track_post(connection, opts \\ []) do
    optional_params = %{
      :"Content-Type" => :headers,
      :Authorization => :headers,
      :body => :body
    }

    request =
      %{}
      |> method(:post)
      |> url("/users/track")
      |> add_optional_params(optional_params, opts)
      |> ensure_body()
      |> Enum.into([])

    connection
    |> Connection.request(request)
    |> evaluate_response([
      {200, false}
    ])
  end
end