Class: Analytics::TrendServices

Inherits:
Lesli::ApplicationLesliService
  • Object
show all
Defined in:
app/services/lesli_audit/analytics/trend_services.rb

Instance Method Summary collapse

Instance Method Details

#indexObject



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'app/services/lesli_audit/analytics/trend_services.rb', line 36

def index

    #Default period
    period = 'day'

    #Get filters from http request
    filters = nil #params[:f]

    #Get start and final date only if the request have filters
    unless filters.blank?
        finalDate = filters[:finalDate]
        startDate = filters[:startDate]
        period = filters[:groupBy]
    end

    #Default search if range date is not provided
    user_requests = ::User::Request.select('created_at').where(created_at: (Time.now.beginning_of_day - 3.month)..)

    # Verify if there are startDate and finalDate
    unless startDate.blank? || finalDate.blank?
        user_requests = ::User::Request.where(created_at: (startDate..finalDate))
    end

    unless period.blank? || (period != 'day' && period != 'hour')
        #Group by day/time depending on the period param
        if period == 'day'
            user_requests = user_requests.group("DATE_TRUNC('#{period}', created_at)")
            user_requests.count.map do |request|
                { 
                    :day => request[0].strftime('%A').to_s,
                    :count => request[1]
                }
            end
            

        elsif period == 'hour'
            user_requests = user_requests.group("DATE_PART('#{period}', created_at)").order('date_part_hour_created_at')
            user_requests.count.map do |request|
                { 
                :hour => request[0],
                :count => request[1]
                }
            end
        end 
    end
end