|
| 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 | + # Allow public access / bypass JWT authentication via "POST /api/v1/authenticate" |
| 8 | + skip_before_action :authorize_request, only: [:index] |
| 9 | + |
| 10 | + # GET /api/ca_dashboard/stats |
| 11 | + def index |
| 12 | + base_hash = { |
| 13 | + 'plans' => Plan.all, |
| 14 | + 'orgs' => Org.where(managed: true).all, |
| 15 | + 'users' => User.all |
| 16 | + } |
| 17 | + @totals = { |
| 18 | + 'all_time' => all_time_counts(base_hash), |
| 19 | + 'last_30_days' => last_30_days_counts(base_hash) |
| 20 | + } |
| 21 | + begin |
| 22 | + @totals['custom_range'] = custom_range_counts(base_hash) if date_params_present? |
| 23 | + render 'api/ca_dashboard/stats/index', status: :ok |
| 24 | + rescue ArgumentError |
| 25 | + error_msg = _('Invalid date format. please use YYYY-MM-DD when supplying `start` or `end` params.') |
| 26 | + render_error(errors: [error_msg], status: :bad_request) |
| 27 | + end |
| 28 | + end |
| 29 | + |
| 30 | + private |
| 31 | + |
| 32 | + def all_time_counts(base_hash) |
| 33 | + base_hash.transform_values(&:count) |
| 34 | + end |
| 35 | + |
| 36 | + def last_30_days_counts(base_hash) |
| 37 | + base_hash.transform_values do |scope| |
| 38 | + scope.where('created_at >= ?', 30.days.ago).count |
| 39 | + end |
| 40 | + end |
| 41 | + |
| 42 | + def custom_range_counts(base_hash) |
| 43 | + start_date = parse_date(params[:start]) |
| 44 | + end_date = parse_date(params[:end]) |
| 45 | + base_hash.transform_values do |scope| |
| 46 | + scope.where(created_at: start_date..end_date).count |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + def date_params_present? |
| 51 | + params[:start].present? || params[:end].present? |
| 52 | + end |
| 53 | + |
| 54 | + def parse_date(date_string) |
| 55 | + Date.strptime(date_string, '%Y-%m-%d') if date_string.present? |
| 56 | + end |
| 57 | + end |
| 58 | + end |
| 59 | +end |
0 commit comments