Skip to content

Commit 1ace30b

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

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
8+
# GET /api/ca_dashboard/stats
9+
def index
10+
# To access this endpoint, the user must provide a valid JWT
11+
# JWT is acquired by authenticating via POST /api/v1/authenticate
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
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)