Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 154 #1167

Merged
merged 1 commit into from
Feb 15, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions app/controllers/api/v0/statistics_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,47 @@ def completed_plans
end
end

# /api/v0/statistics/created_plans
# Returns the number of created plans within the user's org for the data start_date and end_date specified
def created_plans
raise Pundit::NotAuthorizedError unless Api::V0::StatisticsPolicy.new(@user, :statistics).plans?

roles = Role.where("#{Role.creator_condition} OR #{Role.administrator_condition}")

users = User.unscoped
if @user.can_super_admin? && params[:org_id].present?
users = users.where(org_id: params[:org_id])
else
users = users.where(org_id: @user.org_id)
end

plans = Plan.all
if params[:range_dates].present?
r = {}
params[:range_dates].each_pair do |k, v|
range_date_plans = plans
.where('plans.created_at >=?', v['start_date'])
.where('plans.created_at <=?', v['end_date'])
r[k] = roles.joins(:user, :plan).merge(users).merge(range_date_plans).select(:plan_id).distinct.count
end
respond_to do |format|
format.json { render(json: r.to_json) }
format.csv {
send_data(CSV.generate do |csv|
csv << [_('Month'), _('No. Plans')]
total = 0
r.each_pair{ |k,v| csv << [k,v]; total+=v }
csv << [_('Total'), total]
end, filename: "#{_('plans')}.csv") }
end
else
plans = plans.where('plans.created_at >= ?', Date.parse(params[:start_date])) if params[:start_date].present?
plans = plans.where('plans.created_at <= ?', Date.parse(params[:end_date])) if params[:end_date].present?
count = roles.joins(:user, :plan).merge(users).merge(plans).select(:plan_id).distinct.count
render(json: { created_plans: count })
end
end

##
# GET
# @return the number of DMPs using the specified template between the optional specified dates
Expand Down
25 changes: 12 additions & 13 deletions app/views/usage/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<%= select_tag('topic', options_for_select(
[
[_('Users'), 'users', { 'data-url': users_joined_api_v0_statistics_path }],
[_('Completed Plans'), 'completed_plans', { 'data-url': completed_plans_api_v0_statistics_path }]
[_('Plans'), 'plans', { 'data-url': created_plans_api_v0_statistics_path }]
]), class: 'form-control') %>
</div>
</div>
Expand Down Expand Up @@ -62,7 +62,7 @@
<div class="panel panel-default">
<div class="panel-body">
<h4 style="margin-top:0px" style="display: none" data-topic="users"><%= _('New users') %></h4>
<h4 style="margin-top:0px" style="display: none" data-topic="completed_plans"><%= _('Completed plans') %></h4>
<h4 style="margin-top:0px" style="display: none" data-topic="plans"><%= _('Plans') %></h4>
<strong data-range style="font-size: 36px;"></strong>
</div>
</div>
Expand All @@ -71,7 +71,7 @@
<div class="panel panel-default">
<div class="panel-body">
<h4 style="margin-top:0px" style="display: none" data-topic="users"><%= _('Total users') %></h4>
<h4 style="margin-top:0px" style="display: none" data-topic="completed_plans"><%= _('Total completed plans') %></h4>
<h4 style="margin-top:0px" style="display: none" data-topic="plans"><%= _('Total plans') %></h4>
<strong data-totals style="font-size: 36px;"></strong>
</div>
</div>
Expand All @@ -82,31 +82,30 @@
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="col-md-6">
<div class="pull-left">
<h3><%= _('No. users joined during last year') %></h3>
<h4><%= _('No. users joined during last year') %></h4>
</div>
<div class="pull-right">
<button type="button" class="btn btn-default" data-url="<%= users_joined_api_v0_statistics_path(format: :csv) %>">
<%= _('Export') %> <i class="fa fa-download" aria-hidden="true"></i>
<%= _('Download') %> <i class="fa fa-download" aria-hidden="true"></i>
</button>
</div>
<div class="clearfix"></div>
<p class="alert alert-info" style="display: none;"><%= _('There is no data available for users joined yet.') %></p>
<canvas id="yearly_users"></canvas>
<hr />
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="col-md-6">
<div class="pull-left">
<h3><%= _('No. completed plans during last year') %></h3>
<h4><%= _('No. plans during last year') %></h4>
</div>
<div class="pull-right">
<button type="button" class="btn btn-default" data-url="<%= completed_plans_api_v0_statistics_path(format: :csv) %>">
<%= _('Export') %> <i class="fa fa-download" aria-hidden="true"></i>
<button type="button" class="btn btn-default" data-url="<%= created_plans_api_v0_statistics_path(format: :csv) %>">
<%= _('Download') %> <i class="fa fa-download" aria-hidden="true"></i>
</button>
</div>
<div class="clearfix"></div>
<p class="alert alert-info" style="display: none;"><%= _('There is no data available for plans yet.') %></p>
<canvas id="yearly_plans"></canvas>
</div>
</div>
1 change: 1 addition & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@
member do
get :users_joined
get :completed_plans
get :created_plans
get :using_template
get :plans_by_template
get :plans
Expand Down
64 changes: 40 additions & 24 deletions lib/assets/javascripts/views/usage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ $(() => {
label: tooltipItem => `${tooltipItem.yLabel} ${appendTolabel}`,
},
},
scales: {
yAxes: [{
ticks: { min: 0, suggestedMax: 50 },
}],
},
},
});
};
Expand All @@ -62,26 +67,29 @@ $(() => {
url: topicToURL[topic],
data: totals ? { topic, org_id: orgId } : target.serialize(),
});
$.when($.ajax(ajaxSettings()), $.ajax(ajaxSettings({ totals: true }))).then((r1, r2) => {
let dataRange;
let dataTotals;
if (topic === 'users') {
dataRange = r1[0].users_joined;
dataTotals = r2[0].users_joined;
} else if (topic === 'completed_plans') {
dataRange = r1[0].completed_plans;
dataTotals = r2[0].completed_plans;
} else {
dataRange = null;
dataTotals = null;
}
const dataTopics = $('[data-topics]');
const views = $(`[data-topic="${topic}"]`);
dataRange !== null ? dataTopics.find('[data-range]').html(dataRange) : undefined; // eslint-disable-line no-unused-expressions
dataTotals !== null ? dataTopics.find('[data-totals]').html(dataTotals) : undefined; // eslint-disable-line no-unused-expressions
views.show();
dataTopics.show();
}); // TODO request error handling
// Awaits until both AJAX request responds.
// Note, the success handler is only executed if both AJAX requests return success
$.when($.ajax(ajaxSettings()), $.ajax(ajaxSettings({ totals: true }))).then(
(dataRangeSuccessCb, dataTotalsSuccessCb) => {
let dataRange = null;
let dataTotals = null;
if (dataRangeSuccessCb[0]) { // data is the first argument of the successCb ranges
const dataKeys = Object.keys(dataRangeSuccessCb[0]);
// We assume the dataRange is the first key of the object responded
dataRange = dataKeys.length > 0 ? dataRangeSuccessCb[0][dataKeys[0]] : null;
}
if (dataTotalsSuccessCb[0]) { // data is the first argument of the successCb for totals
const dataKeys = Object.keys(dataTotalsSuccessCb[0]);
// We assume the dataTotals is the first key of the object responded
dataTotals = dataKeys.length > 0 ? dataTotalsSuccessCb[0][dataKeys[0]] : null;
}
const dataTopics = $('[data-topics]');
const views = $(`[data-topic="${topic}"]`);
dataRange !== null ? dataTopics.find('[data-range]').html(dataRange) : undefined; // eslint-disable-line no-unused-expressions
dataTotals !== null ? dataTopics.find('[data-totals]').html(dataTotals) : undefined; // eslint-disable-line no-unused-expressions
views.show();
dataTopics.show();
}); // TODO request error handling
});
/*
Click event associated to each Export button
Expand All @@ -106,8 +114,16 @@ $(() => {
link.remove();
});
});
const yearlySuccesHandler = ({ data, selector } = {}) => {
const keys = Object.keys(data); // Keys are Month-Year strings and values might be [0...N]
if (keys.findIndex(k => data[k] > 0) > -1) {
createChart({ selector, data });
} else {
$(selector).prev().show();
}
};
// Sends an AJAX request to our two current endpoints that generate yearly data
// (e.g. users_joined_api_v0_statistics_path, completed_plans_api_v0_statistics_path )
// (e.g. users_joined_api_v0_statistics_path, created_plans_api_v0_statistics_path )
// and draws a barChart when success response is found
const initialise = () => {
// Only fire AJAX requests if topicToURL object has keys, i.e. topics mapping to URLs
Expand All @@ -118,14 +134,14 @@ $(() => {
url: topicToURL.users,
data: { range_dates: rangeDates },
}).then((data) => {
createChart({ selector: '#yearly_users', data, appendTolabel: 'users' });
yearlySuccesHandler({ data, selector: '#yearly_users' });
}); // TODO request error handling
$.ajax({
headers: { Authorization: `Token token="${apiToken}"` },
url: topicToURL.completed_plans,
url: topicToURL.plans,
data: { range_dates: rangeDates },
}).then((data) => {
createChart({ selector: '#yearly_plans', data, appendTolabel: 'completed plans' });
yearlySuccesHandler({ data, selector: '#yearly_plans' });
}); // TODO request error handling
}
};
Expand Down