Class: Workarea::Insights::RepeatPurchaseRate

Inherits:
Base
  • Object
show all
Defined in:
app/models/workarea/insights/repeat_purchase_rate.rb

Class Method Summary collapse

Methods inherited from Base

beginning_of_last_month, current, end_of_last_month, generate_daily!, generate_weekly!, #include?, #slug

Methods included from ApplicationDocument

#releasable?

Methods included from Sidekiq::Callbacks

assert_valid_config!, async, disable, enable, inline, #run_callbacks

Methods included from Mongoid::Document

#embedded_children

Class Method Details

.customers_who_purchased(since) ⇒ Object



32
33
34
# File 'app/models/workarea/insights/repeat_purchase_rate.rb', line 32

def customers_who_purchased(since)
  Metrics::User.where(:first_order_at.gte => since).count
end

.customers_who_purchased_again(since) ⇒ Object



25
26
27
28
29
30
# File 'app/models/workarea/insights/repeat_purchase_rate.rb', line 25

def customers_who_purchased_again(since)
  Metrics::User
    .where(:first_order_at.gte => since)
    .where('$expr' => { '$gt' => ['$last_order_at', '$first_order_at'] })
    .count
end

.dashboardsObject



5
6
7
# File 'app/models/workarea/insights/repeat_purchase_rate.rb', line 5

def dashboards
  %w(people orders)
end

.generate_monthly!Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'app/models/workarea/insights/repeat_purchase_rate.rb', line 9

def generate_monthly!
  results = [30, 60, 90].reduce([]) do |memo, since|
    purchased = customers_who_purchased(since.days.ago)
    purchased_again = customers_who_purchased_again(since.days.ago)

    memo << {
      days_ago: since,
      purchased: purchased,
      purchased_again: purchased_again,
      percent_purchased_again: (purchased_again / purchased.to_f) * 100
    }
  end

  create!(results: results)
end