new_users_measure.rb 983 B

12345678910111213141516171819202122232425262728293031323334353637
  1. # frozen_string_literal: true
  2. class Admin::Metrics::Measure::NewUsersMeasure < Admin::Metrics::Measure::BaseMeasure
  3. def key
  4. 'new_users'
  5. end
  6. protected
  7. def perform_total_query
  8. User.where(created_at: time_period).count
  9. end
  10. def perform_previous_total_query
  11. User.where(created_at: previous_time_period).count
  12. end
  13. def perform_data_query
  14. sql = <<-SQL.squish
  15. SELECT axis.*, (
  16. WITH new_users AS (
  17. SELECT users.id
  18. FROM users
  19. WHERE date_trunc('day', users.created_at)::date = axis.period
  20. )
  21. SELECT count(*) FROM new_users
  22. ) AS value
  23. FROM (
  24. SELECT generate_series(date_trunc('day', $1::timestamp)::date, date_trunc('day', $2::timestamp)::date, interval '1 day') AS period
  25. ) AS axis
  26. SQL
  27. rows = ActiveRecord::Base.connection.select_all(sql, nil, [[nil, @start_at], [nil, @end_at]])
  28. rows.map { |row| { date: row['period'], value: row['value'].to_s } }
  29. end
  30. end