Skip to content

Commit 636db77

Browse files
committed
Create GET "/api/ca_dashboard/stats" endpoint
1 parent a96bc6e commit 636db77

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# frozen_string_literal: true
2+
3+
json.partial! 'api/v1/standard_response'
4+
json.stats do
5+
json.totals @totals
6+
end

config/routes.rb

+4
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,10 @@
204204
resources :plans, only: %i[create show index]
205205
resources :templates, only: [:index]
206206
end
207+
208+
namespace :ca_dashboard do
209+
resources :stats, only: [:index]
210+
end
207211
end
208212

209213
namespace :paginable do

0 commit comments

Comments
 (0)