Join two charts, simpler code.

This commit is contained in:
James Cole
2016-11-19 07:27:54 +01:00
parent 73f0cc705b
commit e15ea04186
12 changed files with 104 additions and 220 deletions

View File

@@ -22,7 +22,6 @@ use FireflyIII\Models\Budget;
use FireflyIII\Models\LimitRepetition; use FireflyIII\Models\LimitRepetition;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Support\CacheProperties;
use Illuminate\Database\Query\JoinClause; use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use stdClass; use stdClass;
@@ -47,60 +46,6 @@ class BudgetReportHelper implements BudgetReportHelperInterface
$this->repository = $repository; $this->repository = $repository;
} }
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength) // at 43, its ok.
* @SuppressWarnings(PHPMD.CyclomaticComplexity) // it's exactly 5.
*
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
* @return Collection
*/
public function budgetYearOverview(Carbon $start, Carbon $end, Collection $accounts): Collection
{
// chart properties for cache:
$cache = new CacheProperties;
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty('budget-year');
$cache->addProperty($accounts->pluck('id')->toArray());
if ($cache->has()) {
return $cache->get();
}
$current = clone $start;
$return = new Collection;
$set = $this->repository->getBudgets();
$budgets = [];
$spent = [];
$headers = $this->createYearHeaders($current, $end);
/** @var Budget $budget */
foreach ($set as $budget) {
$id = $budget->id;
$budgets[$id] = $budget->name;
$current = clone $start;
$budgetData = $this->getBudgetSpentData($current, $end, $budget, $accounts);
$sum = $budgetData['sum'];
$spent[$id] = $budgetData['spent'];
if (bccomp('0', $sum) === 0) {
// not spent anything.
unset($spent[$id]);
unset($budgets[$id]);
}
}
$return->put('headers', $headers);
$return->put('budgets', $budgets);
$return->put('spent', $spent);
$cache->store($return);
return $return;
}
/** /**
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
@@ -108,10 +53,25 @@ class BudgetReportHelper implements BudgetReportHelperInterface
* *
* @return array * @return array
*/ */
public function getBudgetMultiYear(Carbon $start, Carbon $end, Collection $accounts): array public function getBudgetPeriodReport(Carbon $start, Carbon $end, Collection $accounts): array
{ {
// get account ID's.
$accountIds = $accounts->pluck('id')->toArray(); $accountIds = $accounts->pluck('id')->toArray();
$query = TransactionJournal
// define period to group on:
$sqlDateFormat = '%Y-%m-%d';
// monthly report (for year)
if ($start->diffInMonths($end) > 1) {
$sqlDateFormat = '%Y-%m';
}
// yearly report (for multi year)
if ($start->diffInMonths($end) > 12) {
$sqlDateFormat = '%Y';
}
// build query.
$query = TransactionJournal
::leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') ::leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->leftJoin( ->leftJoin(
@@ -127,18 +87,18 @@ class BudgetReportHelper implements BudgetReportHelperInterface
if (count($accountIds) > 0) { if (count($accountIds) > 0) {
$query->whereIn('transactions.account_id', $accountIds); $query->whereIn('transactions.account_id', $accountIds);
} }
$query->groupBy(['budget_transaction_journal.budget_id', 'the_year']); $query->groupBy(['budget_transaction_journal.budget_id', 'period_marker']);
$queryResult = $query->get( $queryResult = $query->get(
[ [
'budget_transaction_journal.budget_id', 'budget_transaction_journal.budget_id',
DB::raw('DATE_FORMAT(transaction_journals.date,"%Y") AS the_year'), DB::raw('DATE_FORMAT(transaction_journals.date,"' . $sqlDateFormat . '") AS period_marker'),
DB::raw('SUM(transactions.amount) as sum_of_period'), DB::raw('SUM(transactions.amount) as sum_of_period'),
] ]
); );
$data = []; $data = [];
$budgets = $this->repository->getBudgets(); $budgets = $this->repository->getBudgets();
$years = $this->listOfYears($start, $end); $periods = $this->listOfPeriods($start, $end);
// do budget "zero" // do budget "zero"
$emptyBudget = new Budget; $emptyBudget = new Budget;
@@ -151,12 +111,12 @@ class BudgetReportHelper implements BudgetReportHelperInterface
foreach ($budgets as $budget) { foreach ($budgets as $budget) {
$data[$budget->id] = [ $data[$budget->id] = [
'name' => $budget->name, 'name' => $budget->name,
'entries' => $this->filterAmounts($queryResult, $budget->id, $years), 'entries' => $this->filterAllAmounts($queryResult, $budget->id, $periods),
'sum' => '0', 'sum' => '0',
]; ];
} }
// filter out empty ones and fill sum: // filter out empty ones and fill sum:
$data = $this->getBudgetMultiYearMeta($data); $data = $this->filterBudgetPeriodReport($data);
return $data; return $data;
} }
@@ -252,16 +212,34 @@ class BudgetReportHelper implements BudgetReportHelperInterface
* *
* @return array * @return array
*/ */
public function listOfYears(Carbon $start, Carbon $end): array public function listOfPeriods(Carbon $start, Carbon $end): array
{ {
$begin = clone $start; // define period to increment
$years = []; $increment = 'addDay';
while ($begin < $end) { $format = 'Y-m-d';
$years[] = $begin->year; // increment by month (for year)
$begin->addYear(); if ($start->diffInMonths($end) > 1) {
$increment = 'addMonth';
$format = 'Y-m';
} }
return $years; // increment by year (for multi year)
if ($start->diffInMonths($end) > 12) {
$increment = 'addYear';
$format = 'Y';
}
$begin = clone $start;
$entries = [];
while ($begin < $end) {
$formatted = $begin->format($format);
$entries[$formatted] = $formatted;
$begin->$increment();
}
return $entries;
} }
/** /**
@@ -285,38 +263,22 @@ class BudgetReportHelper implements BudgetReportHelperInterface
} }
/** /**
* @param Carbon $current * Filters entries from the result set generated by getBudgetPeriodReport
* @param Carbon $end
* *
* @return array
*/
private function createYearHeaders(Carbon $current, Carbon $end): array
{
$headers = [];
while ($current < $end) {
$short = $current->format('m-Y');
$headers[$short] = $current->formatLocalized((string)trans('config.month'));
$current->addMonth();
}
return $headers;
}
/**
* @param Collection $set * @param Collection $set
* @param int $budgetId * @param int $budgetId
* @param array $years * @param array $periods
* *
* @return array * @return array
*/ */
private function filterAmounts(Collection $set, int $budgetId, array $years):array private function filterAllAmounts(Collection $set, int $budgetId, array $periods):array
{ {
$arr = []; $arr = [];
foreach ($years as $year) { foreach ($periods as $period) {
/** @var stdClass $object */ /** @var stdClass $object */
$result = $set->filter( $result = $set->filter(
function (TransactionJournal $object) use ($budgetId, $year) { function (TransactionJournal $object) use ($budgetId, $period) {
return intval($object->the_year) === $year && $budgetId === intval($object->budget_id); return strval($object->period_marker) === $period && $budgetId === intval($object->budget_id);
} }
); );
$amount = '0'; $amount = '0';
@@ -324,18 +286,20 @@ class BudgetReportHelper implements BudgetReportHelperInterface
$amount = $result->first()->sum_of_period; $amount = $result->first()->sum_of_period;
} }
$arr[$year] = $amount; $arr[$period] = $amount;
} }
return $arr; return $arr;
} }
/** /**
* Filters empty results from getBudgetPeriodReport
*
* @param array $data * @param array $data
* *
* @return array * @return array
*/ */
private function getBudgetMultiYearMeta(array $data): array private function filterBudgetPeriodReport(array $data): array
{ {
/** /**
* @var int $budgetId * @var int $budgetId
@@ -355,31 +319,4 @@ class BudgetReportHelper implements BudgetReportHelperInterface
return $data; return $data;
} }
/**
* @param Carbon $current
* @param Carbon $end
* @param Budget $budget
* @param Collection $accounts
*
* @return array
*/
private function getBudgetSpentData(Carbon $current, Carbon $end, Budget $budget, Collection $accounts): array
{
$sum = '0';
$spent = [];
while ($current < $end) {
$currentEnd = clone $current;
$currentEnd->endOfMonth();
$format = $current->format('m-Y');
$budgetSpent = $this->repository->spentInPeriod(new Collection([$budget]), $accounts, $current, $currentEnd);
$spent[$format] = $budgetSpent;
$sum = bcadd($sum, $budgetSpent);
$current->addMonth();
}
return [
'spent' => $spent,
'sum' => $sum,
];
}
} }

View File

@@ -25,14 +25,6 @@ use Illuminate\Support\Collection;
*/ */
interface BudgetReportHelperInterface interface BudgetReportHelperInterface
{ {
/**
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
* @return Collection
*/
public function budgetYearOverview(Carbon $start, Carbon $end, Collection $accounts): Collection;
/** /**
* @param Carbon $start * @param Carbon $start
@@ -41,7 +33,7 @@ interface BudgetReportHelperInterface
* *
* @return array * @return array
*/ */
public function getBudgetMultiYear(Carbon $start, Carbon $end, Collection $accounts): array; public function getBudgetPeriodReport(Carbon $start, Carbon $end, Collection $accounts): array;
/** /**
* @param Carbon $start * @param Carbon $start
@@ -67,6 +59,6 @@ interface BudgetReportHelperInterface
* *
* @return array * @return array
*/ */
public function listOfYears(Carbon $start, Carbon $end): array; public function listOfPeriods(Carbon $start, Carbon $end): array;
} }

View File

@@ -49,20 +49,18 @@ class ReportController extends Controller
* This chart, by default, is shown on the multi-year and year report pages, * This chart, by default, is shown on the multi-year and year report pages,
* which means that giving it a 2 week "period" should be enough granularity. * which means that giving it a 2 week "period" should be enough granularity.
* *
* @param string $reportType
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* @param Collection $accounts * @param Collection $accounts
* *
* @return \Illuminate\Http\JsonResponse * @return \Illuminate\Http\JsonResponse
*/ */
public function netWorth(string $reportType, Carbon $start, Carbon $end, Collection $accounts) public function netWorth(Carbon $start, Carbon $end, Collection $accounts)
{ {
// chart properties for cache: // chart properties for cache:
$cache = new CacheProperties; $cache = new CacheProperties;
$cache->addProperty('netWorth'); $cache->addProperty('netWorth');
$cache->addProperty($start); $cache->addProperty($start);
$cache->addProperty($reportType);
$cache->addProperty($accounts); $cache->addProperty($accounts);
$cache->addProperty($end); $cache->addProperty($end);
if ($cache->has()) { if ($cache->has()) {

View File

@@ -29,6 +29,7 @@ class BudgetController extends Controller
{ {
/** /**
*
* @param BudgetReportHelperInterface $helper * @param BudgetReportHelperInterface $helper
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
@@ -36,22 +37,20 @@ class BudgetController extends Controller
* *
* @return mixed|string * @return mixed|string
*/ */
public function budgetMultiYear(BudgetReportHelperInterface $helper, Carbon $start, Carbon $end, Collection $accounts) public function budgetPeriodReport(BudgetReportHelperInterface $helper, Carbon $start, Carbon $end, Collection $accounts)
{ {
$cache = new CacheProperties; $cache = new CacheProperties;
$cache->addProperty($start); $cache->addProperty($start);
$cache->addProperty($end); $cache->addProperty($end);
$cache->addProperty('budget-mult-year-report'); $cache->addProperty('budget-period-report');
$cache->addProperty($accounts->pluck('id')->toArray()); $cache->addProperty($accounts->pluck('id')->toArray());
if ($cache->has()) { if ($cache->has()) {
return $cache->get(); //return $cache->get();
} }
$periods = $helper->listOfPeriods($start, $end);
$years = $helper->listOfYears($start, $end); $budgets = $helper->getBudgetPeriodReport($start, $end, $accounts);
$budgetMultiYear = $helper->getBudgetMultiYear($start, $end, $accounts); $result = view('reports.partials.budget-period', compact('budgets', 'periods'))->render();
$result = view('reports.partials.budget-multi-year', compact('budgetMultiYear', 'years'))->render();
$cache->store($result); $cache->store($result);
return $result; return $result;
@@ -86,35 +85,4 @@ class BudgetController extends Controller
return $result; return $result;
} }
/**
* @param BudgetReportHelperInterface $helper
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
* @return string
*/
public function budgetYearOverview(BudgetReportHelperInterface $helper, Carbon $start, Carbon $end, Collection $accounts)
{
// chart properties for cache:
$cache = new CacheProperties;
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty('budget-year-overview');
$cache->addProperty($accounts->pluck('id')->toArray());
if ($cache->has()) {
return $cache->get();
}
$budgets = $helper->budgetYearOverview($start, $end, $accounts);
$result = view('reports.partials.budget-year-overview', compact('budgets'))->render();
$cache->store($result);
return $result;
}
} }

View File

@@ -187,6 +187,7 @@ class SplitController extends Controller
'transactions' => $this->getTransactionDataFromRequest($request), 'transactions' => $this->getTransactionDataFromRequest($request),
]; ];
return $array; return $array;
} }

View File

@@ -5,7 +5,7 @@ $(function () {
"use strict"; "use strict";
drawChart(); drawChart();
loadAjaxPartial('budgetMultiYear', budgetMultiUri); loadAjaxPartial('budgetPeriodReport', budgetPeriodReportUri);
}); });
function drawChart() { function drawChart() {

View File

@@ -1,16 +1,16 @@
/* globals google, accountIds, budgetYearOverviewUri */ /* globals google, accountIds, budgetPeriodReportUri */
$(function () { $(function () {
"use strict"; "use strict";
drawChart(); drawChart();
loadAjaxPartial('budgetOverview',budgetYearOverviewUri); loadAjaxPartial('budgetPeriodReport', budgetPeriodReportUri);
}); });
function drawChart() { function drawChart() {
"use strict"; "use strict";
lineChart('chart/report/net-worth/' + reportType + '/' + startDate + '/' + endDate + '/' + accountIds, 'net-worth'); lineChart('chart/report/net-worth/' + startDate + '/' + endDate + '/' + accountIds, 'net-worth');
columnChart('chart/report/in-out/' + startDate + '/' + endDate + '/' + accountIds, 'income-expenses-chart'); columnChart('chart/report/in-out/' + startDate + '/' + endDate + '/' + accountIds, 'income-expenses-chart');
columnChart('chart/report/in-out-sum/' + startDate + '/' + endDate + '/' + accountIds, 'income-expenses-sum-chart'); columnChart('chart/report/in-out-sum/' + startDate + '/' + endDate + '/' + accountIds, 'income-expenses-sum-chart');

View File

@@ -85,13 +85,29 @@
</div> </div>
{# This is the budget overview generated by budget period report #}
<div class="row"> <div class="row">
<div class="col-lg-12 col-md-12 col-sm-12"> <div class="col-lg-12 col-md-12 col-sm-12">
<div class="box"> <div class="box">
<div class="box-header with-border"> <div class="box-header with-border">
<h3 class="box-title">{{ 'budgets'|_ }}</h3> <h3 class="box-title">{{ 'budgets'|_ }}</h3>
</div> </div>
<div class="box-body no-padding table-responsive loading" id="budgetMultiYear"> <div class="box-body no-padding table-responsive loading" id="budgetPeriodReport">
</div>
</div>
</div>
</div>
{# This is the chart that belongs to the above overview. #}
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">{{ 'chart'|_ }}</h3>
</div>
<div class="box-body">
<canvas height="400" id="budget_chart" style="width:100%;height:400px;"></canvas>
</div> </div>
</div> </div>
@@ -124,7 +140,7 @@
var expenseReportUri = '{{ route('reports.data.expenseReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}'; var expenseReportUri = '{{ route('reports.data.expenseReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}';
var incExpReportUri = '{{ route('reports.data.incExpReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}'; var incExpReportUri = '{{ route('reports.data.incExpReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}';
var budgetMultiUri = '{{ route('reports.data.budgetMultiYear', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}'; var budgetPeriodReportUri = '{{ route('reports.data.budgetPeriodReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}';
</script> </script>
<script type="text/javascript" src="js/ff/reports/default/all.js"></script> <script type="text/javascript" src="js/ff/reports/default/all.js"></script>

View File

@@ -84,17 +84,21 @@
</div> </div>
</div> </div>
{# This is the budget overview generated by budget period report #}
<div class="row"> <div class="row">
<div class="col-lg-12 col-md-12 col-sm-12"> <div class="col-lg-12 col-md-12 col-sm-12">
<div class="box"> <div class="box">
<div class="box-header with-border"> <div class="box-header with-border">
<h3 class="box-title">{{ 'budgets'|_ }}</h3> <h3 class="box-title">{{ 'budgets'|_ }}</h3>
</div> </div>
<div class="box-body no-padding table-responsive loading" id="budgetOverview"> <div class="box-body no-padding table-responsive loading" id="budgetPeriodReport">
</div> </div>
</div> </div>
</div> </div>
</div> </div>
{# This is the chart that belongs to the above overview. #}
<div class="row"> <div class="row">
<div class="col-lg-12 col-md-12 col-sm-12"> <div class="col-lg-12 col-md-12 col-sm-12">
<div class="box"> <div class="box">
@@ -129,7 +133,7 @@
var expenseReportUri = '{{ route('reports.data.expenseReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}'; var expenseReportUri = '{{ route('reports.data.expenseReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}';
var incExpReportUri = '{{ route('reports.data.incExpReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}'; var incExpReportUri = '{{ route('reports.data.incExpReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}';
var budgetYearOverviewUri = '{{ route('reports.data.budgetYearOverview', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}'; var budgetPeriodReportUri = '{{ route('reports.data.budgetPeriodReport', [start.format('Ymd'), end.format('Ymd'), accountIds]) }}';
</script> </script>
<script type="text/javascript" src="js/ff/reports/default/all.js"></script> <script type="text/javascript" src="js/ff/reports/default/all.js"></script>

View File

@@ -2,19 +2,19 @@
<thead> <thead>
<tr> <tr>
<th>{{ 'budget'|_ }}</th> <th>{{ 'budget'|_ }}</th>
{% for year in years %} {% for period in periods %}
<th>{{ year }}</th> <th>{{ period }}</th>
{% endfor %} {% endfor %}
<th>{{ 'sum'|_ }}</th> <th>{{ 'sum'|_ }}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% for id, info in budgetMultiYear %} {% for id, info in budgets %}
<tr> <tr>
<td> <td>
(<a title="{{ info.name }}" href="#" data-budget="{{ id }}" class="budget-chart-activate">{{ info.name }}</a>)
{% if id == 0 %} {% if id == 0 %}
<a href="{{ route('budgets.noBudget') }}">{{ info.name }}</a> <a href="{{ route('budgets.noBudget') }}">{{ info.name }}</a>
{% else %} {% else %}
<a href="{{ route('budgets.show', id) }}">{{ info.name }}</a> <a href="{{ route('budgets.show', id) }}">{{ info.name }}</a>
{% endif %} {% endif %}

View File

@@ -1,25 +0,0 @@
<table class="table table-condensed table-hover">
<thead>
<tr>
<th>&nbsp;</th>
{% for date, header in budgets.get('headers') %}
<th>{{ header }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% set spentData = budgets.get('spent') %}
{% for budgetId, budgetName in budgets.get('budgets') %}
<tr>
<th>
<a title="{{ budgetName }}" href="#" data-budget="{{ budgetId }}" class="budget-chart-activate">{{ budgetName }}</a>
</th>
{% for date, header in budgets.get('headers') %}
<td>{{ spentData[budgetId][date]|formatAmount }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

View File

@@ -237,7 +237,7 @@ Route::group(
// reports: // reports:
Route::get('/chart/report/in-out/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOut']); Route::get('/chart/report/in-out/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOut']);
Route::get('/chart/report/in-out-sum/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOutSummarized']); Route::get('/chart/report/in-out-sum/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOutSummarized']);
Route::get('/chart/report/net-worth/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@netWorth']); Route::get('/chart/report/net-worth/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@netWorth']);
/** /**
@@ -388,19 +388,12 @@ Route::group(
'/reports/data/budget-report/{start_date}/{end_date}/{accountList}', '/reports/data/budget-report/{start_date}/{end_date}/{accountList}',
['uses' => 'Report\BudgetController@budgetReport', 'as' => 'reports.data.budgetReport'] ['uses' => 'Report\BudgetController@budgetReport', 'as' => 'reports.data.budgetReport']
); );
// budget year overview // budget period overview
Route::get( Route::get(
'/reports/data/budget-year-overview/{start_date}/{end_date}/{accountList}', '/reports/data/budget-period/{start_date}/{end_date}/{accountList}',
['uses' => 'Report\BudgetController@budgetYearOverview', 'as' => 'reports.data.budgetYearOverview'] ['uses' => 'Report\BudgetController@budgetPeriodReport', 'as' => 'reports.data.budgetPeriodReport']
); );
// budget multi year overview
Route::get(
'/reports/data/budget-multi-year/{start_date}/{end_date}/{accountList}',
['uses' => 'Report\BudgetController@budgetMultiYear', 'as' => 'reports.data.budgetMultiYear']
);
/** /**
* Rules Controller * Rules Controller
*/ */