Class: Moonshot::Convertkit::UpsertJob

Inherits:
ApplicationJob
  • Object
show all
Defined in:
app/jobs/moonshot/convertkit/upsert_job.rb

Instance Method Summary collapse

Instance Method Details

#find_by(email:) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'app/jobs/moonshot/convertkit/upsert_job.rb', line 42

def find_by email:
  response = get_request({ email_address: email })

  return if response['total_subscribers'].zero?

  if response['total_subscribers'] > 1
    raise "Multiple (#{response['total_subscribers']}) subscribers found for email #{email}"
  end

  response['subscribers'].first
end

#perform(user_object_or_klass, user_id: nil, first_name:, fields:) ⇒ Object



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
# File 'app/jobs/moonshot/convertkit/upsert_job.rb', line 10

def perform user_object_or_klass, user_id: nil, first_name:, fields:
  # return unless Rails.env.production?

  user = if user_object_or_klass.is_a?(String)
    klass = user_object_or_klass.constantize
    klass.respond_to?(:with_deleted) ? klass.with_deleted.find(user_id) : klass.find(user_id)
  else
    user_object_or_klass
  end

  return unless user.respond_to?(:email) && user.email.present?

  assert_required_config!

  if existing_subscriber = find_by(email: user.email)
    params = {
      first_name: user.respond_to?(first_name) ? user.send(first_name) : nil
    }
    params.merge!(fields: user.send(fields)) if user.respond_to?(fields)

    put_request "subscribers/#{existing_subscriber['id']}", params
  else
    params = {
      email: user.email,
      first_name: user.respond_to?(first_name) ? user.send(first_name) : nil
    }
    params.merge!(fields: user.send(fields)) if user.respond_to?(fields)

    post_request "forms/#{convertkit_form_id}/subscribe", params
  end
end