|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Api |
| 4 | + module CaDashboard |
| 5 | + # Handles CRUD operations for "/api/ca_dashboard/stats" |
| 6 | + class StatsController < Api::V1::BaseApiController |
| 7 | + respond_to :json |
| 8 | + |
| 9 | + # GET /api/ca_dashboard/stats |
| 10 | + def index |
| 11 | + # To access this endpoint, the user must provide a valid JWT |
| 12 | + # JWT is acquired by authenticating via POST /api/v1/authenticate |
| 13 | + base_hash = { |
| 14 | + 'plans' => Plan.all, |
| 15 | + 'orgs' => Org.where(managed: true).all, |
| 16 | + 'users' => User.all |
| 17 | + } |
| 18 | + @totals = { |
| 19 | + 'all_time' => all_time_counts(base_hash), |
| 20 | + 'last_30_days' => last_30_days_counts(base_hash) |
| 21 | + } |
| 22 | + begin |
| 23 | + @totals['custom_range'] = custom_range_counts(base_hash) if date_params_present? |
| 24 | + render 'api/ca_dashboard/stats/index', status: :ok |
| 25 | + rescue ArgumentError |
| 26 | + error_msg = _('Invalid date format. please use YYYY-MM-DD when supplying `start` or `end` params.') |
| 27 | + render_error(errors: [error_msg], status: :bad_request) |
| 28 | + end |
| 29 | + end |
| 30 | + |
| 31 | + private |
| 32 | + |
| 33 | + def all_time_counts(base_hash) |
| 34 | + base_hash.transform_values(&:count) |
| 35 | + end |
| 36 | + |
| 37 | + def last_30_days_counts(base_hash) |
| 38 | + base_hash.transform_values do |scope| |
| 39 | + scope.where('created_at >= ?', 30.days.ago).count |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + def custom_range_counts(base_hash) |
| 44 | + start_date = parse_date(params[:start]) |
| 45 | + end_date = parse_date(params[:end]) |
| 46 | + base_hash.transform_values do |scope| |
| 47 | + scope.where(created_at: start_date..end_date).count |
| 48 | + end |
| 49 | + end |
| 50 | + |
| 51 | + def date_params_present? |
| 52 | + params[:start].present? || params[:end].present? |
| 53 | + end |
| 54 | + |
| 55 | + def parse_date(date_string) |
| 56 | + Date.strptime(date_string, '%Y-%m-%d') if date_string.present? |
| 57 | + end |
| 58 | + end |
| 59 | + end |
| 60 | +end |
0 commit comments