Class: Heya::Campaigns::Scheduler

Inherits:
Object
  • Object
show all
Defined in:
lib/heya/campaigns/scheduler.rb

Overview

Scheduler schedules campaign jobs to run for each campaign.

For each step in each campaign:

1. Find users who haven't completed step, and are outside the `wait`
window
2. Match segment
3. Create CampaignReceipt (excludes user in subsequent steps)
4. Process job

Instance Method Summary collapse

Instance Method Details

#run(user: nil) ⇒ Object



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
# File 'lib/heya/campaigns/scheduler.rb', line 14

def run(user: nil)
  Heya.campaigns.each do |campaign|
    if campaign.steps.any?
      Queries::OrphanedMemberships.call(campaign).update_all(step_gid: campaign.steps.first.gid)
    end
  end

  Queries::MembershipsToProcess.call(user: user).find_each do |membership|
    step = GlobalID::Locator.locate(membership.step_gid)
    campaign = GlobalID::Locator.locate(membership.campaign_gid)

    if membership.user.nil?
      # User not found; delete orphaned memberships and receipts.
      CampaignReceipt.where(
        user_type: membership.user_type,
        user_id: membership.user_id
      ).delete_all
      CampaignMembership.where(
        user_type: membership.user_type,
        user_id: membership.user_id
      ).delete_all
      next
    end

    process(campaign, step, membership.user)

    if (next_step = get_next_step(campaign, step, user))
      membership.update(step_gid: next_step.gid)
    else
      membership.destroy
    end
  end
end