Class: MassSearch::CustomerCreateAudienceWorker

Inherits:
Object
  • Object
show all
Includes:
Sidekiq::Job, Sidekiq::Status::Worker
Defined in:
app/workers/mass_search/customer_create_audience_worker.rb

Overview

Creates a Audience from the selected Customers in the background.
action_params: { audience: { audience_name:, audience_type:, add_all_emails: } }

Instance Method Summary collapse

Instance Method Details

#perform(args = {}) ⇒ Object

Runs the job.

Parameters:

  • args (Hash) (defaults to: {})

    the args to evaluate

Returns:

  • (Object)

    the result



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
# File 'app/workers/mass_search/customer_create_audience_worker.rb', line 15

def perform(args = {})
  search = Search.find(args[:search_id])
  CurrentScope.locale = args[:locale]&.to_sym || :en

  params        = (args[:action_params] || {}).with_indifferent_access
  sl_params     = params[:audience] || {}
  audience = Audience.new(
    name:      sl_params[:audience_name],
    list_type: sl_params[:audience_type]
  )

  pinned = search.pinned_query
                 .where.not(resource_id: nil)
                 .joins("join parties p on p.id = search_results.resource_id and p.type = 'Customer' and p.state NOT IN ('closed','bankrupt','guest')")

  case audience.list_type
  when 'static'
    emails = []
    pinned.each do |sr|
      if sl_params[:add_all_emails].to_b
        sr.resource.all_emails.each { |e| emails << e if e.present? }
      elsif sr.resource.email.present?
        emails << sr.resource.email
      end
    end
    if audience.save
      rows = emails.uniq.map { |e| { active: true, email_address: e, audience_id: audience.id } }
      AudienceMember.insert_all(rows) if rows.any?
    end
  when 'dynamic'
    audience.customer_search_params = search.query_params
    audience.add_all_emails = sl_params[:add_all_emails].to_b
    audience.save
  when 'customer'
    if audience.save
      customer_ids = pinned.distinct.pluck(:resource_id)
      rows = customer_ids.map { |cid| { active: true, customer_id: cid, audience_id: audience.id } }
      AudienceMember.insert_all(rows) if rows.any?
    end
  end

  if audience.persisted?
    store info_message:  "Audience #{audience.name} [#{audience.id}] created.",
          redirect_to:   UrlHelper.instance.audience_path(audience.id)
  else
    store error_message: "Unable to save Audience: #{audience.errors_to_s}.",
          redirect_to:   Rails.application.routes.url_helpers.search_path(search.id)
  end
end