demarches-normaliennes/app/controllers/stats_controller.rb

57 lines
1.3 KiB
Ruby
Raw Normal View History

2017-03-24 18:04:37 +01:00
class StatsController < ApplicationController
def index
procedures = Procedure.where(:published => true)
dossiers = Dossier.where.not(:state => :draft)
@procedures_30_days_flow = thirty_days_flow_hash(procedures)
@dossiers_30_days_flow = thirty_days_flow_hash(dossiers)
@procedures_cumulative = cumulative_hash(procedures)
@dossiers_cumulative = cumulative_hash(dossiers)
@procedures_count = procedures.count
@dossiers_count = dossiers.count
2017-03-24 18:04:37 +01:00
end
private
def thirty_days_flow_hash(association)
min_date = 30.days.ago.to_date
max_date = Time.now.to_date
thirty_days_flow_hash = association
.where(:created_at => min_date..max_date)
.group("date_trunc('day', created_at)")
.count
clean_hash(thirty_days_flow_hash, min_date, max_date)
end
def clean_hash(h, min_date, max_date)
# Convert keys to date
h = Hash[h.map { |(k, v)| [k.to_date, v] }]
# Add missing vales where count is 0
2017-03-24 18:04:37 +01:00
(min_date..max_date).each do |date|
if h[date].nil?
h[date] = 0
end
2017-03-24 18:04:37 +01:00
end
2017-03-24 18:04:37 +01:00
h
end
def cumulative_hash(association)
sum = 0
association
.group("DATE_TRUNC('month', created_at)")
.count
.to_a
.sort{ |x, y| x[0] <=> y[0] }
.map { |x, y| { x => (sum += y)} }
.reduce({}, :merge)
end
2017-03-24 18:04:37 +01:00
end