-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathusers.rb
More file actions
86 lines (71 loc) · 2.47 KB
/
Copy pathusers.rb
File metadata and controls
86 lines (71 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
require 'csv'
# Performs a bulk import of users to RMI
#
# Pass in a path to a CSV file with the following headers:
#
# email - the email address of the user
# name - the full name of the user
# supplier_salesforce_id - the Salesforce ID for the user's supplier
#
# New users are added to RMI, added to Auth0, and associated with the supplier
# matching the supplier_salesforce_id. If the user already exists, the existing
# user will be associated with the supplier, but only if it isn't already
# associated, making running the import idempotent.
#
# The import process pauses 0.2 seconds between each user so as not to trigger
# the Auth0 rate limiting. This can be overridden by passing in the optional
# named parameter `wait_time`.
#
# Example:
#
# Import::Users.new('/tmp/new_users.csv').run
#
# Note: when running this on a docker container you will need to copy the CSV
# file into the container itself. Use the `docker cp` command to do this.
module Import
class Users
class InvalidSalesforceId < StandardError; end
class InvalidFormat < StandardError; end
DEFAULT_WAIT = 0.2
EXPECTED_HEADERS = %I[supplier_salesforce_id email name].freeze
attr_reader :logger, :wait_time
def initialize(csv_path, wait_time: DEFAULT_WAIT, logger: Logger.new($stdout))
@csv_path = csv_path
@csv = CSV.read(csv_path, headers: true, header_converters: :symbol)
@logger = logger
@wait_time = wait_time
verify_csv_headers!
end
def run
check_for_missing_salesforce_ids
ActiveRecord::Base.transaction do
@csv.each do |row_data|
user = Row.new(**row_data).import!
log "User #{user.email} is associated with #{user.suppliers.map(&:name).to_sentence}"
wait
end
end
end
private
def wait
sleep(wait_time)
end
def log(message)
logger.info message
end
def verify_csv_headers!
raise InvalidFormat, "Missing headers in CSV file: #{missing_headers.to_sentence}" if missing_headers.any?
end
def missing_headers
EXPECTED_HEADERS - @csv.headers
end
def check_for_missing_salesforce_ids
supplier_salesforce_ids = Supplier.pluck(:salesforce_id, 1).to_h
@csv.each do |row_data|
salesforce_id = row_data[:supplier_salesforce_id]
next if supplier_salesforce_ids.key?(salesforce_id)
raise InvalidSalesforceId, "Could not find a supplier with salesforce_id '#{salesforce_id}'."
end
end
end
end