Class: Workarea::Insights::CustomerAcquisition

Inherits:
Base
  • Object
show all
Defined in:
app/models/workarea/insights/customer_acquisition.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

add_worker, assert_valid_config!, async, caching_classes?, disable, enable, inline, #run_callbacks, workers, workers_list

Methods included from Mongoid::Document

#embedded_children

Class Method Details

.dashboardsObject



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

def dashboards
  %w(people marketing)
end

.days_last_monthObject



28
29
30
# File 'app/models/workarea/insights/customer_acquisition.rb', line 28

def days_last_month
  (end_of_last_month.to_date - beginning_of_last_month.to_date).to_i + 1
end

.filter_date_rangeObject



36
37
38
39
40
41
42
43
44
45
# File 'app/models/workarea/insights/customer_acquisition.rb', line 36

def filter_date_range
  {
    '$match' => {
      'first_order_at' => {
        '$gte' => beginning_of_last_month.utc,
        '$lte' => end_of_last_month.utc
      }
    }
  }
end

.find_resultsObject



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

def find_results
  Metrics::User.collection.aggregate([filter_date_range, group_by_time]).to_a
end

.first_order_at_in_time_zoneObject



60
61
62
# File 'app/models/workarea/insights/customer_acquisition.rb', line 60

def first_order_at_in_time_zone
  { 'date' => '$first_order_at', 'timezone' => Time.zone.tzinfo.name }
end

.generate_monthly!Object



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

def generate_monthly!
  aggregation_results = find_results

  results = Array.new(days_last_month) do |i|
    result = aggregation_results.detect { |r| r['_id']['day'] == i + 1 } || {}

    {
      new_customers: result['new_customers'] || 0,
      date: Time.zone.local(
        beginning_of_last_month.year,
        beginning_of_last_month.month,
        i + 1
      )
    }
  end

  create!(results: results) if results.present?
end

.group_by_timeObject



47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/models/workarea/insights/customer_acquisition.rb', line 47

def group_by_time
  {
    '$group' => {
      '_id' => {
        'year' => { '$year' => first_order_at_in_time_zone },
        'month' => { '$month' => first_order_at_in_time_zone },
        'day' => { '$dayOfMonth' => first_order_at_in_time_zone }
      },
      'new_customers' => { '$sum' => 1 }
    }
  }
end