Added metrics filter dropdown. Closes #518

This commit is contained in:
James Brooks
2015-08-02 15:43:20 +01:00
committed by James Brooks
parent 4a22b1b053
commit d99f95b2d6
15 changed files with 348 additions and 139 deletions

View File

@@ -16,6 +16,7 @@ use CachetHQ\Cachet\Models\Component;
use CachetHQ\Cachet\Models\ComponentGroup; use CachetHQ\Cachet\Models\ComponentGroup;
use CachetHQ\Cachet\Models\Incident; use CachetHQ\Cachet\Models\Incident;
use CachetHQ\Cachet\Models\Metric; use CachetHQ\Cachet\Models\Metric;
use CachetHQ\Cachet\Repositories\MetricRepository;
use Exception; use Exception;
use GrahamCampbell\Binput\Facades\Binput; use GrahamCampbell\Binput\Facades\Binput;
use GrahamCampbell\Markdown\Facades\Markdown; use GrahamCampbell\Markdown\Facades\Markdown;
@@ -27,7 +28,24 @@ use Jenssegers\Date\Date;
class HomeController extends Controller class HomeController extends Controller
{ {
/** /**
* Returns the rendered Blade templates. * @var \CachetHQ\Cachet\Repositories\MetricRepository
*/
protected $metricRepository;
/**
* Construct a new home controller instance.
*
* @param \CachetHQ\Cachet\Repositories\MetricRepository $metricRepository
*
* @return void
*/
public function __construct(MetricRepository $metricRepository)
{
$this->metricRepository = $metricRepository;
}
/**
* Displays the status page.
* *
* @return \Illuminate\View\View * @return \Illuminate\View\View
*/ */
@@ -52,9 +70,17 @@ class HomeController extends Controller
} }
$metrics = null; $metrics = null;
$metricData = [];
if ($displayMetrics = Setting::get('display_graphs')) { if ($displayMetrics = Setting::get('display_graphs')) {
$metrics = Metric::where('display_chart', 1)->get(); $metrics = Metric::where('display_chart', 1)->get();
$metrics->map(function ($metric) use (&$metricData) {
$metricData[$metric->id] = [
'today' => $this->metricRepository->listPointsToday($metric),
'week' => $this->metricRepository->listPointsForWeek($metric),
'month' => $this->metricRepository->listPointsForMonth($metric),
];
});
} }
$daysToShow = Setting::get('app_incident_days') ?: 7; $daysToShow = Setting::get('app_incident_days') ?: 7;
@@ -98,6 +124,7 @@ class HomeController extends Controller
->withUngroupedComponents($ungroupedComponents) ->withUngroupedComponents($ungroupedComponents)
->withDisplayMetrics($displayMetrics) ->withDisplayMetrics($displayMetrics)
->withMetrics($metrics) ->withMetrics($metrics)
->withMetricData($metricData)
->withAllIncidents($allIncidents) ->withAllIncidents($allIncidents)
->withScheduledMaintenance($scheduledMaintenance) ->withScheduledMaintenance($scheduledMaintenance)
->withAboutApp(Markdown::convertToHtml(Setting::get('app_about'))) ->withAboutApp(Markdown::convertToHtml(Setting::get('app_about')))

View File

@@ -12,13 +12,8 @@
namespace CachetHQ\Cachet\Models; namespace CachetHQ\Cachet\Models;
use AltThree\Validator\ValidatingTrait; use AltThree\Validator\ValidatingTrait;
use CachetHQ\Cachet\Facades\Setting as SettingFacade;
use CachetHQ\Cachet\Presenters\MetricPresenter; use CachetHQ\Cachet\Presenters\MetricPresenter;
use DateInterval;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Jenssegers\Date\Date;
use McCool\LaravelAutoPresenter\HasPresenter; use McCool\LaravelAutoPresenter\HasPresenter;
class Metric extends Model implements HasPresenter class Metric extends Model implements HasPresenter
@@ -86,58 +81,6 @@ class Metric extends Model implements HasPresenter
return $this->hasMany(MetricPoint::class, 'metric_id', 'id'); return $this->hasMany(MetricPoint::class, 'metric_id', 'id');
} }
/**
* Returns the sum of all values a metric has by the hour.
*
* @param int $hour
*
* @return int
*/
public function getValuesByHour($hour)
{
$dateTimeZone = SettingFacade::get('app_timezone');
$dateTime = (new Date())->setTimezone($dateTimeZone)->sub(new DateInterval('PT'.$hour.'H'));
$hourInterval = $dateTime->format('YmdH');
if (Config::get('database.default') === 'mysql') {
if (!isset($this->calc_type) || $this->calc_type == self::CALC_SUM) {
$value = $this->points()
->whereRaw('DATE_FORMAT(created_at, "%Y%m%d%H") = '.$hourInterval)
->groupBy(DB::raw('HOUR(created_at)'))->sum('value');
} elseif ($this->calc_type == self::CALC_AVG) {
$value = $this->points()
->whereRaw('DATE_FORMAT(created_at, "%Y%m%d%H") = '.$hourInterval)
->groupBy(DB::raw('HOUR(created_at)'))->avg('value');
}
} else {
// Default metrics calculations.
if (!isset($this->calc_type) || $this->calc_type == self::CALC_SUM) {
$queryType = 'sum(metric_points.value)';
} elseif ($this->calc_type == self::CALC_AVG) {
$queryType = 'avg(metric_points.value)';
} else {
$queryType = 'sum(metric_points.value)';
}
$query = DB::select("select {$queryType} as aggregate FROM metrics JOIN metric_points ON metric_points.metric_id = metrics.id WHERE metric_points.metric_id = {$this->id} AND to_char(metric_points.created_at, 'YYYYMMDDHH24') = :timestamp GROUP BY to_char(metric_points.created_at, 'H')", [
'timestamp' => $hourInterval,
]);
if (isset($query[0])) {
$value = $query[0]->aggregate;
} else {
$value = 0;
}
}
if ($value === 0 && $this->default_value != $value) {
return $this->default_value;
}
return round($value, $this->places);
}
/** /**
* Determines whether a chart should be shown. * Determines whether a chart should be shown.
* *

View File

@@ -0,0 +1,207 @@
<?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Repositories;
use CachetHQ\Cachet\Facades\Setting as SettingFacade;
use CachetHQ\Cachet\Models\Metric;
use DateInterval;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Jenssegers\Date\Date;
class MetricRepository
{
/**
* The timezone the status page is showing in.
*
* @var string
*/
protected $dateTimeZone;
/**
* Creates a new instance of the metric repository.
*
* @return void
*/
public function __construct()
{
$this->dateTimeZone = SettingFacade::get('app_timezone');
}
/**
* Returns all points as an array, by x hours.
*
* @param \CachetHQ\Cachet\Models\Metric $metric
* @param int $hours
*
* @return array
*/
public function listPointsToday(Metric $metric, $hours = 12)
{
$dateTime = (new Date())->setTimezone($this->dateTimeZone);
$points = [];
$pointKey = $dateTime->format('H:00');
for ($i = 0; $i <= $hours; $i++) {
$points[$pointKey] = $this->getPointsByHour($metric, $i + 1);
$pointKey = $dateTime->sub(new DateInterval('PT1H'))->format('H:00');
}
return array_reverse($points);
}
/**
* Returns all points as an array, in the last week.
*
* @param \CachetHQ\Cachet\Models\Metric $metric
*
* @return array
*/
public function listPointsForWeek(Metric $metric)
{
$dateTime = (new Date())->setTimezone($this->dateTimeZone);
$points = [];
$pointKey = $dateTime->format('jS M');
for ($i = 0; $i <= 7; $i++) {
$points[$pointKey] = $this->getPointsForDayInWeek($metric, $i);
$pointKey = $dateTime->sub(new DateInterval('P1D'))->format('D jS M');
}
return array_reverse($points);
}
/**
* Returns all points as an array, in the last month.
*
* @param \CachetHQ\Cachet\Models\Metric $metric
*
* @return array
*/
public function listPointsForMonth(Metric $metric)
{
$dateTime = (new Date())->setTimezone($this->dateTimeZone);
$daysInMonth = $dateTime->format('t');
$points = [];
$pointKey = $dateTime->format('jS M');
for ($i = 0; $i <= $daysInMonth; $i++) {
$points[$pointKey] = $this->getPointsForDayInWeek($metric, $i);
$pointKey = $dateTime->sub(new DateInterval('P1D'))->format('jS M');
}
return array_reverse($points);
}
/**
* Returns metrics for a given hour.
*
* @param \CachetHQ\Cachet\Models\Metric $metric
* @param int $hour
*
* @return int
*/
protected function getPointsByHour(Metric $metric, $hour)
{
$dateTime = (new Date())->setTimezone($this->dateTimeZone);
$dateTime->sub(new DateInterval('PT'.$hour.'H'));
$hourInterval = $dateTime->format('YmdH');
if (Config::get('database.default') === 'mysql') {
$points = $metric->points()
->whereRaw('DATE_FORMAT(created_at, "%Y%m%d%H") = '.$hourInterval)
->groupBy(DB::raw('HOUR(created_at)'));
if (!isset($metric->calc_type) || $metric->calc_type == Metric::CALC_SUM) {
$value = $points->sum('value');
} elseif ($metric->calc_type == Metric::CALC_AVG) {
$value = $points->avg('value');
}
} else {
// Default metrics calculations.
if (!isset($metric->calc_type) || $metric->calc_type == Metric::CALC_SUM) {
$queryType = 'sum(metric_points.value)';
} elseif ($metric->calc_type == Metric::CALC_AVG) {
$queryType = 'avg(metric_points.value)';
} else {
$queryType = 'sum(metric_points.value)';
}
$query = DB::select("select {$queryType} as aggregate FROM metrics JOIN metric_points ON metric_points.metric_id = metrics.id WHERE metric_points.metric_id = {$metric->id} AND to_char(metric_points.created_at, 'YYYYMMDDHH24') = :timestamp GROUP BY to_char(metric_points.created_at, 'H')", [
'timestamp' => $hourInterval,
]);
if (isset($query[0])) {
$value = $query[0]->aggregate;
} else {
$value = 0;
}
}
if ($value === 0 && $metric->default_value != $value) {
return $metric->default_value;
}
return round($value, $metric->places);
}
/**
* Returns metrics for the week.
*
* @param \CachetHQ\Cachet\Models\Metric $metric
*
* @return int
*/
protected function getPointsForDayInWeek(Metric $metric, $day)
{
$dateTime = (new Date())->setTimezone($this->dateTimeZone);
$dateTime->sub(new DateInterval('P'.$day.'D'));
if (Config::get('database.default') === 'mysql') {
$points = $metric->points()
->whereRaw('created_at BETWEEN DATE_SUB(created_at, INTERVAL 1 WEEK) AND NOW()')
->whereRaw('DATE_FORMAT(created_at, "%Y%m%d") = '.$dateTime->format('Ymd'))
->groupBy(DB::raw('DATE_FORMAT(created_at, "%Y%m%d")'));
if (!isset($metric->calc_type) || $metric->calc_type == Metric::CALC_SUM) {
$value = $points->sum('value');
} elseif ($metric->calc_type == Metric::CALC_AVG) {
$value = $points->avg('value');
}
} else {
// Default metrics calculations.
if (!isset($metric->calc_type) || $metric->calc_type == Metric::CALC_SUM) {
$queryType = 'sum(metric_points.value)';
} elseif ($metric->calc_type == Metric::CALC_AVG) {
$queryType = 'avg(metric_points.value)';
} else {
$queryType = 'sum(metric_points.value)';
}
$query = DB::select("select {$queryType} as aggregate FROM metrics JOIN metric_points ON metric_points.metric_id = metrics.id WHERE metric_points.metric_id = {$metric->id} AND to_char(metric_points.created_at, 'YYYYMMDD') = :timestamp GROUP BY to_char(metric_points.created_at, 'YYYYMMDD')", [
'timestamp' => $hourInterval,
]);
if (isset($query[0])) {
$value = $query[0]->aggregate;
} else {
$value = 0;
}
}
if ($value === 0 && $metric->default_value != $value) {
return $metric->default_value;
}
return round($value, $metric->places);
}
}

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => 'Stündlich', 'hourly' => 'Last 12 Hours',
'daily' => 'Täglich', 'weekly' => 'Week',
'monthly' => 'Monatlich', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => 'Hourly', 'hourly' => 'Last 12 Hours',
'daily' => 'Daily', 'weekly' => 'Week',
'monthly' => 'Monthly', 'monthly' => 'Month',
], ],
], ],

View File

@@ -50,9 +50,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => 'Hourly', 'hourly' => 'Last 12 Hours',
'daily' => 'Daily', 'weekly' => 'Week',
'monthly' => 'Monthly', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => 'Toutes les heures', 'hourly' => 'Last 12 Hours',
'daily' => 'Tous les jours', 'weekly' => 'Week',
'monthly' => 'Mensuel', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => 'Per jam', 'hourly' => 'Last 12 Hours',
'daily' => 'Harian', 'weekly' => 'Week',
'monthly' => 'Bulanan', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => '시간별', 'hourly' => 'Last 12 Hours',
'daily' => '일별', 'weekly' => 'Week',
'monthly' => '월별', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => 'Ieder uur', 'hourly' => 'Last 12 Hours',
'daily' => 'Dagelijks', 'weekly' => 'Week',
'monthly' => 'Maandelijks', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => 'Godzinowo', 'hourly' => 'Last 12 Hours',
'daily' => 'Dziennie', 'weekly' => 'Week',
'monthly' => 'Miesięcznie', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => '', 'hourly' => 'Last 12 Hours',
'daily' => '', 'weekly' => 'Week',
'monthly' => '', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => 'Ежечасно', 'hourly' => 'Last 12 Hours',
'daily' => 'Ежедневно', 'weekly' => 'Week',
'monthly' => 'Ежемесячно', 'monthly' => 'Month',
], ],
], ],

View File

@@ -52,9 +52,9 @@ return [
// Metrics // Metrics
'metrics' => [ 'metrics' => [
'filter' => [ 'filter' => [
'hourly' => '每小时的', 'hourly' => 'Last 12 Hours',
'daily' => '每日的', 'weekly' => 'Week',
'monthly' => '每月的', 'monthly' => 'Month',
], ],
], ],

View File

@@ -1,14 +1,7 @@
@if($metrics->count() > 0) @if($metrics->count() > 0)
<ul class="list-group metrics"> <ul class="list-group metrics">
@foreach($metrics as $metric) @foreach($metrics as $metric)
<?php <li class="list-group-item metric" data-metric-id="{{ $metric->id }}">
$hourPoints = [];
foreach (range(1, 11) as $hour) {
$hourPoints[$hour] = $metric->getValuesByHour($hour);
}
$hourPoints = array_reverse($hourPoints);
?>
<li class="list-group-item metric">
<div class="row"> <div class="row">
<div class="col-xs-10"> <div class="col-xs-10">
<h4> <h4>
@@ -19,55 +12,94 @@
</h4> </h4>
</div> </div>
<div class="col-xs-2 text-right"> <div class="col-xs-2 text-right">
<small>{{ trans('cachet.metrics.filter.hourly') }}</small> <div class="dropdown">
<a href="javascript: void(0);" class="btn btn-default dropdown-toggle" data-toggle="dropdown"><span class='filter'>{{ trans('cachet.metrics.filter.hourly') }}</span> <span class="caret"></span></a>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="#" data-filter-type="today">{{ trans('cachet.metrics.filter.hourly') }}</a></li>
<li><a href="#" data-filter-type="week">{{ trans('cachet.metrics.filter.weekly') }}</a></li>
<li><a href="#" data-filter-type="month">{{ trans('cachet.metrics.filter.monthly') }}</a></li>
</ul>
</div>
</div> </div>
</div> </div>
<hr> <hr>
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
<div> <div>
<canvas id="metric-{{ $metric->id }}" height="125" width="600"></canvas> <canvas id="metric-{{ $metric->id }}" data-metric-id="{{ $metric->id }}" data-metric-group="today" height="125" width="600"></canvas>
</div> </div>
</div> </div>
</div> </div>
<script>
(function () {
Chart.defaults.global.pointHitDetectionRadius = 1;
var hourList = [], date = new Date();
for (var i = 10; i >= 1; i--) {
hourList.push(moment(date).subtract(i, 'hours').seconds(0).format('HH:ss'));
}
hourList.push(moment(date).seconds(0).format('HH:ss'));
var hourPoints = [{{ implode(',', $hourPoints) }}];
var data = {
showTooltips: false,
labels: hourList,
datasets: [{
fillColor: "rgba(220,220,220,0.1)",
strokeColor: "rgba(52,152,219,0.6)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: hourPoints
}],
};
var ctx = document.getElementById("metric-{{ $metric->id }}").getContext("2d");
new Chart(ctx).Line(data, {
tooltipTemplate: "{!! $metric->name !!}: <%= value %> {!! $metric->suffix !!}",
scaleShowVerticalLines: true,
responsive: true,
maintainAspectRatio: false
});
}());
</script>
</li> </li>
@endforeach @endforeach
</ul> </ul>
<script type="text/json" id="metricData">
{!! json_encode($metric_data) !!}
</script>
<script>
(function () {
Chart.defaults.global.pointHitDetectionRadius = 1;
var charts = JSON.parse(document.getElementById('metricData').innerText);
var defaultData = {
showTooltips: false,
labels: [],
datasets: [{
fillColor: "rgba(220,220,220,0.1)",
strokeColor: "rgba(52,152,219,0.6)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: []
}],
};
$('a[data-filter-type]').on('click', function(e) {
e.preventDefault();
var $this = $(this);
// Change the selected view.
var $li = $this.parents('li')
$li.find('a[data-toggle=dropdown] span.filter').text($this.text());
var $canvas = $li.find('canvas');
$canvas.data('metric-group', $this.data('filter-type'));
drawChart($canvas);
});
$('canvas[data-metric-id]').each(function() {
var $this = $(this);
drawChart($this);
});
function drawChart($el) {
var metricId = $el.data('metric-id');
var metricGroup = $el.data('metric-group');
charts[metricId].context = document.getElementById("metric-"+metricId).getContext("2d");
if (typeof charts[metricId].chart !== 'undefined') {
charts[metricId].chart.destroy();
}
var chartConfig = defaultData;
var charter = charts[metricId][metricGroup];
chartConfig.labels = _.keys(charter);
chartConfig.datasets[0].data = _.values(charter);
charts[metricId].chart = new Chart(charts[metricId].context).Line(chartConfig, {
tooltipTemplate: "{!! $metric->name !!}: <%= value %> {!! $metric->suffix !!}",
scaleShowVerticalLines: true,
scaleShowLabels: false,
responsive: true,
maintainAspectRatio: false
});
}
}());
</script>
@endif @endif