Class: Campaign

Inherits:
ApplicationRecord show all
Includes:
Models::Auditable, Models::LiquidMethods
Defined in:
app/models/campaign.rb

Overview

== Schema Information

Table name: campaigns
Database name: primary

id :integer not null, primary key
active_since :datetime
auto_assign_source :boolean
auto_assign_until :date
auto_enroll :boolean default(FALSE)
campaign_type :string
category :string
description :text
end_date :date
exclude_from_monthly_report :boolean default(FALSE), not null
name :string(255) not null
start_date :date
state :string
created_at :datetime
updated_at :datetime
creator_id :integer
customer_filter_id :integer
source_id :integer
updater_id :integer

Indexes

idx_campaign_type (campaign_type)
idx_campaigns_state (state)
index_campaigns_on_customer_filter_id (customer_filter_id)
index_campaigns_on_source_id (source_id)

Foreign Keys

fk_rails_... (customer_filter_id => customer_filters.id)

Defined Under Namespace

Classes: AddCustomerResult, AssignCustomersToSubscriberList, AssignDripCampaigns, DripContext

Constant Summary collapse

CATEGORIES =
%w[announcements events newsletters promotions webinars].freeze
CAMPAIGN_TYPES =
%w[email_marketing outside_sales].freeze

Constants included from Models::Auditable

Models::Auditable::ALWAYS_IGNORED

Instance Attribute Summary collapse

Belongs to collapse

Methods included from Models::Auditable

#creator, #updater

Has and belongs to many collapse

Has many collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Models::Auditable

#all_skipped_columns, #audit_reference_data, #should_not_save_version, #stamp_record

Methods inherited from ApplicationRecord

ransackable_associations, ransackable_attributes, ransackable_scopes, ransortable_attributes, #to_relation

Methods included from Models::EventPublishable

#publish_event

Instance Attribute Details

#campaign_typeObject (readonly)



65
# File 'app/models/campaign.rb', line 65

validates :name, :campaign_type, presence: true

#categoryObject (readonly)



66
# File 'app/models/campaign.rb', line 66

validates :category, presence: true, if: proc { |c| c.campaign_type == 'email_marketing' }

#nameObject (readonly)



65
# File 'app/models/campaign.rb', line 65

validates :name, :campaign_type, presence: true

Class Method Details

.activeActiveRecord::Relation<Campaign>

A relation of Campaigns that are active. Active Record Scope

Returns:

See Also:



75
# File 'app/models/campaign.rb', line 75

scope :active, -> { where(state: 'active') }

.active_options_for_selectObject



184
185
186
# File 'app/models/campaign.rb', line 184

def self.active_options_for_select
  where(state: 'active').order(:name).map { |c| [c.name_and_type, c.id] }
end

.merge_subscriber_lists(campaign_ids: nil) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'app/models/campaign.rb', line 129

def self.merge_subscriber_lists(campaign_ids: nil)
  unshared_subscriber_lists = SubscriberList
                              .customers
                              .where(%{
                    (select count(*)
                     from campaigns_subscriber_lists csl
                     where csl.subscriber_list_id = subscriber_lists.id) = 1})
  campaigns = Campaign.joins(:subscriber_lists)
                      .merge(unshared_subscriber_lists)
                      .where(%{
                        (select count(*) from campaigns_subscriber_lists csl
                                inner join subscriber_lists sl on sl.id = csl.subscriber_list_id
                                where sl.list_type = 'customer'
                                  and csl.campaign_id = campaigns.id) > 1 })
  campaigns = campaigns.where(id: campaign_ids) if campaign_ids.present?
  Campaign.transaction do
    merged_subscribers = []
    subscriber_ids_to_delete = []
    subscriber_list_ids_to_delete = []
    campaigns.distinct.each do |campaign|
      first_list = campaign.subscriber_lists.order(:created_at).first
      puts "Consolidating campaign #{campaign.id} into subscriber list #{first_list.id}"
      campaign.subscriber_lists.where.not(id: first_list.id).each do |sl|
        merged_subscribers += sl.subscribers.map do |sub|
          {
            subscriber_list_id: first_list.id,
            customer_id: sub.customer_id,
            state: sub.state,
            created_at: sub.created_at,
            updated_at: sub.updated_at,
            creator_id: sub.creator_id,
            updater_id: sub.updater_id
          }
        end
        subscriber_list_ids_to_delete << sl.id
        subscriber_ids_to_delete += sl.subscriber_ids
      end
    end
    msg = "Moving #{merged_subscribers.size} subscribers, deleting #{subscriber_list_ids_to_delete.size} lists"
    Rails.logger.info msg
    require 'activerecord-import/base'
    require 'activerecord-import/active_record/adapters/postgresql_adapter'
    Subscriber.import merged_subscribers, validate: false, on_duplicate_key_ignore: true
    Subscriber.where(id: subscriber_ids_to_delete).delete_all
    SubscriberList.where(id: subscriber_list_ids_to_delete).delete_all
    msg
  end
end

.options_for_selectObject



178
179
180
181
182
# File 'app/models/campaign.rb', line 178

def self.options_for_select
  res = order(:name)
  res = yield(res) if block_given?
  res.order(:name).map { |c| [c.name_and_type, c.id] }
end

.outside_salesActiveRecord::Relation<Campaign>

A relation of Campaigns that are outside sales. Active Record Scope

Returns:

See Also:



76
# File 'app/models/campaign.rb', line 76

scope :outside_sales, -> { where(campaign_type: 'outside_sales') }

.reconcile_sources_for_campaigns(customer_ids: nil, campaign_ids: nil, campaign_source_ids: nil) ⇒ Object

Reconciles sources for campaigns based on the subscription start date.
campaigns allow to narrow the scope of campaigns being looked at
campaign_source_ids are protected source which should not be touched
eg: Campaign.reconcile_sources_for_campaigns(campaign_ids: 274, campaign_source_ids: [])



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'app/models/campaign.rb', line 321

def self.reconcile_sources_for_campaigns(customer_ids: nil, campaign_ids: nil, campaign_source_ids: nil)
  # Find all subscribers
  campaign_source_ids ||= Campaign.where.not(source_id: nil).distinct.pluck(:source_id)

  campaigns = Campaign.outside_sales
                      .where.not(source_id: nil)
                      .where(auto_assign_source: true)
  campaigns = campaigns.where(id: campaign_ids)

  subscribers = Subscriber.where.not(customer_id: nil)
                          .joins(subscriber_list: :campaigns)
                          .includes(:customer, { subscriber_list: :campaigns })
                          .merge(campaigns)
                          .order(:customer_id, 'subscribers.created_at desc'.sql_safe)
  # If a list of customer is specified, we always use it
  subscribers = if customer_ids.present?
                  subscribers.where(customer_id: customer_ids)
                else # If not, we go by what's not been processed before
                  subscribers.where(reconciled: false)
                end
  total = subscribers.size
  puts "Total Subscribers to process: #{total}"
  subscribers.each_with_index do |subscriber, index|
    puts "[#{index + 1} / #{total}] Processing Subscriber #{subscriber.id}"
    # Subscribers are sorted by customer then by most recent first, while technically
    # subscribrers could belong to many campaigns, only the first one will be used
    campaign = subscriber.campaigns.first
    res = campaign.synchronize_source(customer: subscriber.customer,
                              start_time: subscriber.created_at,
                              include_inactive_campaign: true,
                              campaign_source_ids: campaign_source_ids)
    subscriber.update_column(:reconciled, true)
  end
end

.states_for_selectObject



188
189
190
# File 'app/models/campaign.rb', line 188

def self.states_for_select
  state_machines[:state].states.map { |s| [s.human_name, s.value] }
end

.with_campaign_emails_countActiveRecord::Relation<Campaign>

A relation of Campaigns that are with campaign emails count. Active Record Scope

Returns:

See Also:



84
85
86
87
88
89
# File 'app/models/campaign.rb', line 84

scope :with_campaign_emails_count, lambda {
  select('campaigns.*')
    .select('COUNT(campaign_actions.id) as emails_count')
    .left_joins(:campaign_emails)
    .group('campaigns.id')
}

.with_email_statsActiveRecord::Relation<Campaign>

A relation of Campaigns that are with email stats. Active Record Scope

Returns:

See Also:



91
92
93
94
95
96
97
# File 'app/models/campaign.rb', line 91

scope :with_email_stats, lambda {
  select('campaigns.*')
    .select('MAX(campaign_actions.created_at) as last_email_created_at')
    .select('COUNT(campaign_actions.id) as emails_count')
    .left_joins(:campaign_emails)
    .group('campaigns.id')
}

.with_last_created_at_emailActiveRecord::Relation<Campaign>

A relation of Campaigns that are with last created at email. Active Record Scope

Returns:

See Also:



78
79
80
81
82
83
# File 'app/models/campaign.rb', line 78

scope :with_last_created_at_email, lambda {
  select('campaigns.*')
    .select('MAX(campaign_actions.created_at) as last_email_created_at')
    .left_joins(:campaign_emails)
    .group('campaigns.id')
}

Instance Method Details

#activitiesActiveRecord::Relation<Activity>

Returns:

See Also:



58
# File 'app/models/campaign.rb', line 58

has_many :activities

#activity_chain_typesActiveRecord::Relation<ActivityChainType>

Returns:

See Also:



59
# File 'app/models/campaign.rb', line 59

has_many :activity_chain_types

#add_customer(customer) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'app/models/campaign.rb', line 196

def add_customer(customer)
  return AddCustomerResult.new(subscribed: false, message: 'Customer is GUEST and cannot be subscribed') if customer.guest?
  return AddCustomerResult.new(subscribed: false, message: 'Customer has no contact information') unless customer.contactable?

  subscriber_list = subscriber_lists.where(list_type: 'customer', name: "#{name} system added").first_or_create

  subscriber = subscriber_list.subscribers.where(customer_id: customer.id).first

  # Check customer against filter
  if customer_filter.nil? || customer_filter.applies_to_customer?(customer)
    if subscriber
      # make sure it is active and return
      subscriber.activate
    else
      begin
        subscriber = subscriber_list.subscribers.create(customer_id: customer.id)
        synchronize_source(customer: customer)
      rescue ActiveRecord::RecordNotUnique => e
        # Another process might have caused a race condition here
      end
    end
    res = AddCustomerResult.new(subscribed: true, subscriber: subscriber)
  else # Does not meet filter qualification
    # customer does not apply to filter in place, inactivate subscription if applicable
    if subscriber && subscriber.active?
      subscriber.deactivate
      message = 'Existing subscriber was de-activated due to customer filter'
    end
    res = AddCustomerResult.new(subscribed: false, subscriber: subscriber)
  end
  res
end

#campaign_deliveriesActiveRecord::Relation<CampaignDelivery>

Returns:

See Also:



56
# File 'app/models/campaign.rb', line 56

has_many :campaign_deliveries, through: :campaign_emails

#campaign_emailsActiveRecord::Relation<CampaignEmail>

Returns:

See Also:



55
# File 'app/models/campaign.rb', line 55

has_many :campaign_emails, dependent: :destroy, inverse_of: :campaign

#can_be_deativated?Boolean

Returns:

  • (Boolean)


247
248
249
250
251
252
253
# File 'app/models/campaign.rb', line 247

def can_be_deativated?
  return false if created_at < 1.month.ago

  last_transmitted = campaign_emails.where.not(last_transmitted: nil).maximum(:last_transmitted)

  campaign_emails.empty? || (last_transmitted && (last_transmitted > 1.month.ago))
end

#check_for_active_campaign_emailsObject



269
270
271
272
273
274
275
276
277
278
# File 'app/models/campaign.rb', line 269

def check_for_active_campaign_emails
  if campaign_emails.empty?
    true
  elsif campaign_emails.any? { |ce| !ce.can_be_destroyed? }
    errors.add :base, 'cannot delete campaign which has emails which have already been sent'
    false
  else
    true
  end
end

#customer_filterCustomerFilter



51
# File 'app/models/campaign.rb', line 51

belongs_to :customer_filter, optional: true

#delivery_statsObject



121
122
123
# File 'app/models/campaign.rb', line 121

def delivery_stats
  CampaignEmail.delivery_stats(campaign_deliveries)
end

#email_marketing?Boolean

Returns:

  • (Boolean)


284
285
286
# File 'app/models/campaign.rb', line 284

def email_marketing?
  campaign_type == 'email_marketing'
end

#generate_sourceObject



255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'app/models/campaign.rb', line 255

def generate_source
  s = Source.new
  s.parent_id = (campaign_type == 'outside_sales' ? Source.outside_sales_campaign_id : Source.email_campaign_id)
  s.name = name
  s.referral_code = s.generate_ref_code
  if s.save
    self.source_id = s.id
    true
  else
    errors.add(:base, "Unable to create source. Error: #{s.errors.full_messages}")
    throw :abort
  end
end

#merge_subscriber_listsObject



125
126
127
# File 'app/models/campaign.rb', line 125

def merge_subscriber_lists
  self.class.merge_subscriber_lists(campaign_ids: id)
end

#name_and_typeObject



229
230
231
# File 'app/models/campaign.rb', line 229

def name_and_type
  "#{name} [#{campaign_type}]"
end

#outside_sales?Boolean

Returns:

  • (Boolean)


280
281
282
# File 'app/models/campaign.rb', line 280

def outside_sales?
  campaign_type == 'outside_sales'
end

#reconcile_sources_for_subscribersObject



313
314
315
# File 'app/models/campaign.rb', line 313

def reconcile_sources_for_subscribers
  self.class.reconcile_sources_for_campaigns(campaign_ids: id)
end

#sourceSource

Returns:

See Also:



50
# File 'app/models/campaign.rb', line 50

belongs_to :source, optional: true

#subscriber_countObject



233
234
235
# File 'app/models/campaign.rb', line 233

def subscriber_count
  subscriber_lists.sum(&:subscriber_count)
end

#subscriber_listsActiveRecord::Relation<SubscriberList>

Returns:

See Also:



53
# File 'app/models/campaign.rb', line 53

has_and_belongs_to_many :subscriber_lists

#subscriber_lists_all_customerObject



294
295
296
297
298
# File 'app/models/campaign.rb', line 294

def subscriber_lists_all_customer
  return unless subscriber_lists.any? && subscriber_lists.any? { |sl| ['customer'].exclude?(sl.list_type) }

  errors.add(:subscriber_list_ids, 'Only customer subscriber lists are allowed for outside_sales campaigns')
end

#subscriber_lists_all_emailObject



288
289
290
291
292
# File 'app/models/campaign.rb', line 288

def subscriber_lists_all_email
  return unless subscriber_lists.any? && subscriber_lists.any? { |sl| %w[email_static email_dynamic].exclude?(sl.list_type) }

  errors.add(:subscriber_list_ids, 'Only email subscriber lists are allowed for email_marketing campaigns')
end

#subscribersActiveRecord::Relation<Subscriber>

Returns:

See Also:



57
# File 'app/models/campaign.rb', line 57

has_many :subscribers, through: :subscriber_lists

#synchronize_source(customer:, start_time: nil, trial_run: false, include_inactive_campaign: false, campaign_source_ids: nil) ⇒ Object

If a new campaign is assigned to a customer, it is necessary to take into
consideration the time of this assignment to retroactively populate
orders/opportunities



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'app/models/campaign.rb', line 359

def synchronize_source(customer:, start_time: nil, trial_run: false, include_inactive_campaign: false, campaign_source_ids: nil)
  Rails.logger.info "Synchronizing source for campaign: #{id} - #{name} for customer #{customer.id} #{customer.full_name}"

  return { status: :warning, messages: ['Campaign is not active'] }.freeze unless active? || include_inactive_campaign

  # When did this customer become a subscriber?
  start_time ||= subscribers.where(customer_id: customer.id).active.minimum(:created_at)
  # if we don't have a subscriber entry, take the time the campaign became active
  start_time ||= active_since.beginning_of_day

  return { status: :warning, messages: ['Active since not set on campaign or could not determine effective start time'] }.freeze unless start_time

  end_time = auto_assign_until.end_of_day if auto_assign_until.present?
  # Retrieve all other campaign source ids, so we don't override them
  campaign_source_ids ||= Campaign.where.not(source_id: nil).pluck('distinct source_id'.sql_safe)

  # Opportunities that would qualify
  opportunities_scope = customer.opportunities.where(Opportunity[:created_at].gteq(start_time))
                                .where(opportunity_reception_type: 'CRM')
                                .where(opportunity_type: 'S')
                                .where(Opportunity[:source_id].not_in(campaign_source_ids).or(Opportunity[:source_id].eq(nil)))
  # Skip those already assigned to campaign, you must check for nil  or the not_in clause will exclude them
  # Orders that would qualify
  orders_scope = customer.orders.so_only
                         .where(Order[:created_at].gteq(start_time))
                         .where(order_reception_type: 'CRM')
                         .where(Order[:source_id].not_in(campaign_source_ids).or(Order[:source_id].eq(nil)))
  # Skip those already assigned to campaigns, you must check for nil or the not_in clause will exclude them

  # if campaign expires apply that scope to our opportunities and orders
  if end_time
    opportunities_scope = opportunities_scope.where(Opportunity[:created_at].lteq(end_time))
    orders_scope = orders_scope.where(Order[:created_at].lteq(end_time))
  end

  messages = []

  # Time to update everything, make this a transaction
  unless trial_run
    Opportunity.transaction do
      # Assign the campaign source
      opportunities_scope.update_all(source_id: source_id)
      # Push this source down to orders
      orders_scope.update_all(source_id: source_id)
      order_ids = orders_scope.pluck(:id)
      invoices_scope = Invoice.where(order_id: order_ids)
      invoices_scope.update_all(source_id: source_id)
      messages << "Updated #{opportunities_scope.size} opportunities, #{orders_scope.size} orders, #{invoices_scope.size} invoices for customer #{customer.id}"
    end
  end

  { status: :ok, messages: messages }
end

#synchronize_source_with_all_subscribersObject



304
305
306
307
308
309
310
311
# File 'app/models/campaign.rb', line 304

def synchronize_source_with_all_subscribers
  customer_ids = subscribers.active.distinct.pluck(:customer_id)
  res = []
  Customer.where(id: customer_ids).find_each do |customer|
    res << { customer_id: customer.id, result: synchronize_source(customer: customer) }
  end
  res
end

#to_sObject



192
193
194
# File 'app/models/campaign.rb', line 192

def to_s
  "#{name} [#{id}]"
end

#unique_subscribersObject



237
238
239
240
241
242
243
244
245
# File 'app/models/campaign.rb', line 237

def unique_subscribers
  Campaign.joins("LEFT OUTER JOIN campaigns_subscriber_lists ON campaigns_subscriber_lists.campaign_id = campaigns.id
                  LEFT OUTER JOIN subscriber_lists ON subscriber_lists.id = campaigns_subscriber_lists.subscriber_list_id
                  LEFT OUTER JOIN subscribers ON subscribers.subscriber_list_id = subscriber_lists.id
                  LEFT OUTER JOIN view_customers ON subscribers.customer_id = view_customers.id
                    AND view_customers.state != 'guest'")
          .where('campaigns.id = :id', { id: id })
          .count('distinct view_customers.id')
end

#update_source_nameObject



300
301
302
# File 'app/models/campaign.rb', line 300

def update_source_name
  source&.update(name: name)
end