Display breakdown of spendings by tags in pie chart on dashboard
MODIFY
app/Http/Controllers/DashboardController.php
app/Http/Controllers/DashboardController.php
@@ -53,6 +53,22 @@ class DashboardController extends Controller {
LIMIT 1;
', [$user->id]);
+ $tagsBreakdown = DB::select('
+ SELECT
+ tags.name AS name,
+ SUM(spendings.amount) AS amount
+ FROM
+ tags
+ LEFT OUTER JOIN
+ spendings ON tags.id = spendings.tag_id
+ WHERE
+ tags.user_id = ?
+ GROUP BY
+ tags.id
+ HAVING
+ SUM(spendings.amount) > 0;
+ ', [$user->id]);
+
return view('dashboard', [
'currency' => $user->currency,
@@ -61,6 +77,8 @@ class DashboardController extends Controller {
'mostExpensiveTag' => $mostExpensiveTag,
'mostExpensiveWeekday' => $mostExpensiveWeekday,
+ 'tagsBreakdown' => $tagsBreakdown,
+
'earningsCount' => $user->earnings->count(),
'spendingsCount' => $user->spendings->count()
]);

MODIFY
resources/views/dashboard.blade.php
resources/views/dashboard.blade.php
</div>
</div>
</div>
+ @if (count($tagsBreakdown))
+ <div class="box spacing-bottom-large">
+ <div class="box__section">
+ <div class="ct-chart ct-major-eleventh"></div>
+ </div>
+ </div>
+ @endif
<div class="row gutter spacing-bottom-large">
<div class="column">
<div class="box">
</div>
</div>
@endsection
+
+@section('scripts')
+ <script>
+ var labels = [{!! implode(',', array_map(function ($entry) { return '\'' . $entry->name . '\''; }, $tagsBreakdown)) !!}];
+
+ var data = {
+ series: [{!! implode(',', array_map(function ($entry) { return $entry->amount; }, $tagsBreakdown)) !!}]
+ };
+
+ var sum = function(a, b) { return a + b };
+
+ new Chartist.Pie('.ct-chart', data, {
+ labelInterpolationFnc: function (value, x) {
+ return labels[x] + ' (' + Math.round(value / data.series.reduce(sum) * 100) + '%)';
+ }
+ });
+ </script>
+@endsection

MODIFY
resources/views/layout.blade.php
resources/views/layout.blade.php
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Muli:400,400i" />
<link rel="stylesheet" href="/css/app.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
+ <link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" />
+ <script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
</head>
<body>
<div id="app">

Display breakdown of spendings by tags in pie chart on dashboard