retention.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # frozen_string_literal: true
  2. class Admin::Metrics::Retention
  3. CACHE_TTL = 5.minutes.freeze
  4. class Cohort < ActiveModelSerializers::Model
  5. attributes :period, :frequency, :data
  6. end
  7. class CohortData < ActiveModelSerializers::Model
  8. attributes :date, :rate, :value
  9. end
  10. attr_reader :loaded
  11. alias loaded? loaded
  12. def initialize(start_at, end_at, frequency)
  13. @start_at = start_at&.to_date
  14. @end_at = end_at&.to_date
  15. @frequency = %w(day month).include?(frequency) ? frequency : 'day'
  16. @loaded = false
  17. end
  18. def cache_key
  19. ['metrics/retention', @start_at, @end_at, @frequency].join(';')
  20. end
  21. def cohorts
  22. load
  23. end
  24. protected
  25. def load
  26. unless loaded?
  27. @values = Rails.cache.fetch(cache_key, expires_in: CACHE_TTL) { perform_query }
  28. @loaded = true
  29. end
  30. @values
  31. end
  32. def perform_query
  33. sql = <<-SQL.squish
  34. SELECT axis.*, (
  35. WITH new_users AS (
  36. SELECT users.id
  37. FROM users
  38. WHERE date_trunc($3, users.created_at)::date = axis.cohort_period
  39. ),
  40. retained_users AS (
  41. SELECT users.id
  42. FROM users
  43. INNER JOIN new_users on new_users.id = users.id
  44. WHERE date_trunc($3, users.current_sign_in_at) >= axis.retention_period
  45. )
  46. SELECT ARRAY[count(*), (count(*))::float / (SELECT GREATEST(count(*), 1) FROM new_users)] AS retention_value_and_rate
  47. FROM retained_users
  48. )
  49. FROM (
  50. WITH cohort_periods AS (
  51. SELECT generate_series(date_trunc($3, $1::timestamp)::date, date_trunc($3, $2::timestamp)::date, ('1 ' || $3)::interval) AS cohort_period
  52. ),
  53. retention_periods AS (
  54. SELECT cohort_period AS retention_period FROM cohort_periods
  55. )
  56. SELECT *
  57. FROM cohort_periods, retention_periods
  58. WHERE retention_period >= cohort_period
  59. ) as axis
  60. SQL
  61. rows = ActiveRecord::Base.connection.select_all(sql, nil, [[nil, @start_at], [nil, @end_at], [nil, @frequency]])
  62. rows.each_with_object([]) do |row, arr|
  63. current_cohort = arr.last
  64. if current_cohort.nil? || current_cohort.period != row['cohort_period']
  65. current_cohort = Cohort.new(period: row['cohort_period'], frequency: @frequency, data: [])
  66. arr << current_cohort
  67. end
  68. value, rate = row['retention_value_and_rate'].delete('{}').split(',')
  69. current_cohort.data << CohortData.new(
  70. date: row['retention_period'],
  71. rate: rate.to_f,
  72. value: value.to_s
  73. )
  74. end
  75. end
  76. end