diff --git a/README.md b/README.md index ba669ae..a2278ec 100644 --- a/README.md +++ b/README.md @@ -544,6 +544,54 @@ You can target the broadcast audience in several ways. Only one audience option If you omit the audience option, the broadcast uses its default audience configured in the UI. +### Import data from a CSV + +You can start a CSV import and read its result using the `APIClient`. Create a `CreateImportRequest` containing: + +* `name`: a name for the import. +* `data_file_url`: the public URL of your CSV file. +* `type`: what the file holds: `people`, `event`, `object`, `relationship` or `device`. +* `identifier`: the column that identifies each person, `id` or `email`. Every type except `object` needs it. +* `description`: optional notes about the import. + +Use `create_import` to start the import, then `get_import` with the returned `id` to check on it. This example adds push tokens to people who already exist: + +```ruby +require "customerio" + +client = Customerio::APIClient.new("your API key", region: Customerio::Regions::US) + +request = Customerio::CreateImportRequest.new( + name: "Push tokens", + data_file_url: "https://example.com/devices.csv", + type: "device", + identifier: "id", +) + +begin + import = client.create_import(request)["import"] + puts import["id"], import["state"] + + import = client.get_import(import["id"])["import"] + puts import["state"], import["rows_imported"], import["error_download_url"] +rescue Customerio::InvalidResponse => e + puts e.code, e.message +end +``` + +A `device` file needs these columns: + +* `id` or `email`, matching the `identifier` you set +* `token`: the device's push token +* `platform`: `ios` or `android` +* `last_used` (optional): when the device was last used, in unix seconds + +Any other column is saved as a device attribute. + +A device import only adds devices to people who already exist. It skips rows for people it can't find and tokens that repeat for another person. The skipped rows and the reason for each are in the file at `error_download_url`, which can be set even when the import succeeds. + +With the one-key client, these calls are on `cio.api_client`, like `cio.api_client.create_import(request)`. + ## Contributing 1. Fork it diff --git a/lib/customerio.rb b/lib/customerio.rb index e8fe320..c533e17 100644 --- a/lib/customerio.rb +++ b/lib/customerio.rb @@ -13,6 +13,7 @@ module Customerio require "customerio/requests/send_inbox_message_request" require "customerio/requests/send_in_app_request" require "customerio/requests/trigger_broadcast_request" + require "customerio/requests/create_import_request" require "customerio/api" require "customerio/unified_client" end diff --git a/lib/customerio/api.rb b/lib/customerio/api.rb index 7c373b7..f0bafda 100644 --- a/lib/customerio/api.rb +++ b/lib/customerio/api.rb @@ -58,10 +58,23 @@ def trigger_broadcast(req) deliver(trigger_broadcast_path(req.broadcast_id), req.message) end + def create_import(req) + validate_request!(req, CreateImportRequest) + + deliver(imports_path, { import: req.message }) + end + + def get_import(import_id) + whole_number = (import_id.is_a?(Integer) || import_id.is_a?(String)) && import_id.to_s.match?(/\A\d+\z/) + raise ArgumentError, "import_id must be a whole number" unless whole_number + + deliver(import_path(import_id), nil, :get) + end + private - def deliver(path, message) - response = @client.request(:post, path, message) + def deliver(path, message, method = :post) + response = @client.request(method, path, message) case response when Net::HTTPSuccess @@ -107,5 +120,13 @@ def send_in_app_path def trigger_broadcast_path(broadcast_id) "/v1/campaigns/#{broadcast_id}/triggers" end + + def imports_path + "/v1/imports" + end + + def import_path(import_id) + "/v1/imports/#{import_id}" + end end end diff --git a/lib/customerio/requests/create_import_request.rb b/lib/customerio/requests/create_import_request.rb new file mode 100644 index 0000000..134eeb5 --- /dev/null +++ b/lib/customerio/requests/create_import_request.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module Customerio + class CreateImportRequest + REQUIRED_FIELDS = %i[data_file_url type].freeze + + OPTIONAL_FIELDS = %i[name identifier description people_to_process data_to_process object_type_id].freeze + + attr_reader :message + + def initialize(opts) + REQUIRED_FIELDS.each do |field| + raise ArgumentError, "#{field} is required" if blank?(opts[field]) + end + + @message = opts.select { |field, _value| valid_field?(field) } + end + + private + + def blank?(value) + value.nil? || value.to_s.strip.empty? + end + + def valid_field?(field) + REQUIRED_FIELDS.include?(field) || OPTIONAL_FIELDS.include?(field) + end + end +end diff --git a/spec/api_client_spec.rb b/spec/api_client_spec.rb index a961666..c4d24f1 100644 --- a/spec/api_client_spec.rb +++ b/spec/api_client_spec.rb @@ -614,4 +614,182 @@ def json(data) ) end end + + describe "#create_import" do + let(:import_body) do + { + import: { + id: "15", + type: "device", + state: "preparing", + name: "Push tokens", + description: "", + identifier: "id", + error: "", + created_at: 1511315635, + updated_at: 1511315635, + }, + } + end + + it "sends a POST request to the imports path" do + req = Customerio::CreateImportRequest.new( + name: "Push tokens", + data_file_url: "https://example.com/devices.csv", + type: "device", + identifier: "id", + ) + + stub_request(:post, api_uri('/v1/imports')) + .with(headers: request_headers, body: { import: req.message }) + .to_return(status: 200, body: import_body.to_json, headers: {}) + + expect(client.create_import(req)).to eq(JSON.parse(import_body.to_json)) + end + + it "raises an error when data_file_url is missing" do + expect { + Customerio::CreateImportRequest.new(name: "Push tokens", type: "device", identifier: "id") + }.to raise_error(ArgumentError, "data_file_url is required") + + expect { + Customerio::CreateImportRequest.new(data_file_url: "", type: "device") + }.to raise_error(ArgumentError, "data_file_url is required") + end + + it "raises an error when type is missing" do + expect { + Customerio::CreateImportRequest.new(name: "Push tokens", data_file_url: "https://example.com/devices.csv") + }.to raise_error(ArgumentError, "type is required") + + expect { + Customerio::CreateImportRequest.new(data_file_url: "https://example.com/devices.csv", type: "") + }.to raise_error(ArgumentError, "type is required") + end + + it "drops unknown fields from the message" do + req = Customerio::CreateImportRequest.new( + name: "Push tokens", + data_file_url: "https://example.com/devices.csv", + type: "device", + identifier: "email", + description: "Tokens from the old provider", + unknown_field: "ignored", + ) + + expect(req.message).to eq( + name: "Push tokens", + data_file_url: "https://example.com/devices.csv", + type: "device", + identifier: "email", + description: "Tokens from the old provider", + ) + end + + it "raises an error when request is not a CreateImportRequest" do + expect { + client.create_import("not a request") + }.to raise_error(ArgumentError, /must be an instance of/) + end + + it "handles validation failures (422)" do + req = Customerio::CreateImportRequest.new( + name: "Push tokens", + data_file_url: "https://example.com/devices.csv", + type: "device", + identifier: "id", + people_to_process: "all", + ) + + err_json = { + errors: [ + { + detail: "example error", + source: { pointer: "/example" }, + status: "422", + }, + ], + }.to_json + + stub_request(:post, api_uri('/v1/imports')) + .with(headers: request_headers, body: { import: req.message }) + .to_return(status: 422, body: err_json, headers: {}) + + expect { client.create_import(req) }.to( + raise_error(Customerio::InvalidResponse) { |error| + expect(error.message).to eq(err_json) + expect(error.code).to eq("422") + } + ) + end + end + + describe "#get_import" do + def get_request_headers + { 'Authorization': "Bearer #{app_key}", 'User-Agent': 'Customer.io Ruby Client/' + Customerio::VERSION } + end + + let(:import_body) do + { + import: { + id: "15", + type: "device", + state: "imported", + name: "Push tokens", + description: "", + identifier: "id", + rows_to_import: 3, + rows_imported: 2, + error: "", + error_download_url: "https://example.com/errors.csv", + created_at: 1511315635, + updated_at: 1511315700, + }, + } + end + + it "sends a GET request to the import path" do + stub = stub_request(:get, api_uri('/v1/imports/15')) + .with(headers: get_request_headers) + .to_return(status: 200, body: import_body.to_json, headers: {}) + + expect(client.get_import(15)).to eq(JSON.parse(import_body.to_json)) + expect(client.get_import("15")).to eq(JSON.parse(import_body.to_json)) + expect(stub).to have_been_requested.twice + end + + it "sends no body and no Content-Type" do + stub_request(:get, api_uri('/v1/imports/15')) + .to_return(status: 200, body: import_body.to_json, headers: {}) + + client.get_import(15) + + expect( + a_request(:get, api_uri('/v1/imports/15')).with { |request| + request.body.nil? && !request.headers.key?("Content-Type") + } + ).to have_been_made + end + + it "raises an error when the import id is not a whole number" do + [nil, "", "abc", "15/../1", "1.5", 1.5, -15, "15\n"].each do |import_id| + expect { + client.get_import(import_id) + }.to raise_error(ArgumentError, "import_id must be a whole number") + end + end + + it "handles failures (404)" do + stub_request(:get, api_uri('/v1/imports/15')) + .with(headers: get_request_headers) + .to_return(status: 404, body: "not found", headers: {}) + + expect { client.get_import(15) }.to( + raise_error(Customerio::InvalidResponse) { |error| + expect(error.message).to eq("not found") + expect(error.code).to eq("404") + } + ) + end + end end