main
rb 43 lines 1.25 KB
Raw
1 # frozen_string_literal: true
2
3 module Admin
4 # Filter / paginate subscriptions and expose the revenue rollups the admin
5 # subscriptions index needs (MRR + plan/status breakdowns).
6 class SubscriptionSearch
7 PER_PAGE = 30
8
9 attr_reader :plan, :status, :page
10
11 def initialize(params)
12 @plan = params[:plan].presence
13 @status = params[:status].presence
14 @page = [ params[:page].to_i, 1 ].max
15 end
16
17 def records
18 @records ||= scope.includes(:user)
19 .order(created_at: :desc)
20 .limit(PER_PAGE)
21 .offset((page - 1) * PER_PAGE)
22 .to_a
23 end
24
25 def total = @total ||= scope.count
26 def has_next? = page * PER_PAGE < total
27 def per_page = PER_PAGE
28 def estimated_mrr = BillingMetrics.estimated_mrr
29
30 # group(:plan)/group(:status) key back as the enums' string labels.
31 def by_plan = @by_plan ||= Subscription.group(:plan).count
32 def by_status = @by_status ||= Subscription.group(:status).count
33
34 private
35
36 def scope
37 s = Subscription.all
38 s = s.where(status: status) if Subscription.statuses.key?(status)
39 s = s.where(plan: plan) if Subscription.plans.key?(plan)
40 s
41 end
42 end
43 end