Files
firefly-iii/app/Http/Controllers/Chart/ExpenseReportController.php

280 lines
10 KiB
PHP
Raw Normal View History

2017-12-12 18:22:29 +01:00
<?php
/**
* ExpenseReportController.php
* Copyright (c) 2017 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2017-12-17 14:41:58 +01:00
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
2017-12-12 18:22:29 +01:00
*/
2018-07-08 12:08:53 +02:00
/** @noinspection MoreThanThreeArgumentsInspection */
2017-12-12 18:22:29 +01:00
declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Chart;
use Carbon\Carbon;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Collector\JournalCollectorInterface;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Support\CacheProperties;
2018-07-08 12:28:42 +02:00
use Illuminate\Http\JsonResponse;
2017-12-12 18:22:29 +01:00
use Illuminate\Support\Collection;
/**
* Separate controller because many helper functions are shared.
*
* Class ExpenseReportController
*/
class ExpenseReportController extends Controller
{
/** @var AccountRepositoryInterface The account repository */
2017-12-12 18:22:29 +01:00
protected $accountRepository;
2018-07-21 08:06:24 +02:00
/** @var GeneratorInterface Chart generation methods. */
2017-12-12 18:22:29 +01:00
protected $generator;
/**
2018-07-22 08:10:16 +02:00
* ExpenseReportController constructor.
2017-12-12 18:22:29 +01:00
*/
public function __construct()
{
parent::__construct();
$this->middleware(
function ($request, $next) {
$this->generator = app(GeneratorInterface::class);
$this->accountRepository = app(AccountRepositoryInterface::class);
return $next($request);
}
);
}
2018-07-17 22:21:03 +02:00
/** @noinspection MoreThanThreeArgumentsInspection */
2017-12-12 18:22:29 +01:00
/**
2018-07-21 08:06:24 +02:00
* Main chart that shows income and expense for a combination of expense/revenue accounts.
*
2017-12-12 18:22:29 +01:00
* @param Collection $accounts
* @param Collection $expense
* @param Carbon $start
* @param Carbon $end
*
2018-07-08 12:28:42 +02:00
* @return JsonResponse
2018-07-17 22:21:03 +02:00
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
2017-12-12 18:22:29 +01:00
*/
2018-07-08 12:28:42 +02:00
public function mainChart(Collection $accounts, Collection $expense, Carbon $start, Carbon $end): JsonResponse
2017-12-12 18:22:29 +01:00
{
$cache = new CacheProperties;
$cache->addProperty('chart.expense.report.main');
$cache->addProperty($accounts);
$cache->addProperty($expense);
$cache->addProperty($start);
$cache->addProperty($end);
if ($cache->has()) {
2018-03-10 20:30:09 +01:00
return response()->json($cache->get()); // @codeCoverageIgnore
2017-12-12 18:22:29 +01:00
}
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$function = app('navigation')->preferredEndOfPeriod($start, $end);
2017-12-12 18:22:29 +01:00
$chartData = [];
$currentStart = clone $start;
$combined = $this->combineAccounts($expense);
// make "all" set:
$all = new Collection;
foreach ($combined as $name => $combi) {
$all = $all->merge($combi);
}
// prep chart data:
foreach ($combined as $name => $combi) {
// first is always expense account:
/** @var Account $exp */
$exp = $combi->first();
$chartData[$exp->id . '-in'] = [
2018-04-02 15:10:40 +02:00
'label' => $name . ' (' . strtolower((string)trans('firefly.income')) . ')',
2017-12-12 18:22:29 +01:00
'type' => 'bar',
'yAxisID' => 'y-axis-0',
'entries' => [],
];
$chartData[$exp->id . '-out'] = [
2018-04-02 15:10:40 +02:00
'label' => $name . ' (' . strtolower((string)trans('firefly.expenses')) . ')',
2017-12-12 18:22:29 +01:00
'type' => 'bar',
'yAxisID' => 'y-axis-0',
'entries' => [],
];
// total in, total out:
$chartData[$exp->id . '-total-in'] = [
2018-04-02 15:10:40 +02:00
'label' => $name . ' (' . strtolower((string)trans('firefly.sum_of_income')) . ')',
2017-12-12 18:22:29 +01:00
'type' => 'line',
'fill' => false,
'yAxisID' => 'y-axis-1',
'entries' => [],
];
$chartData[$exp->id . '-total-out'] = [
2018-04-02 15:10:40 +02:00
'label' => $name . ' (' . strtolower((string)trans('firefly.sum_of_expenses')) . ')',
2017-12-12 18:22:29 +01:00
'type' => 'line',
'fill' => false,
'yAxisID' => 'y-axis-1',
'entries' => [],
];
}
$sumOfIncome = [];
$sumOfExpense = [];
while ($currentStart < $end) {
$currentEnd = clone $currentStart;
$currentEnd = $currentEnd->$function();
// get expenses grouped by opposing name:
$expenses = $this->groupByName($this->getExpenses($accounts, $all, $currentStart, $currentEnd));
$income = $this->groupByName($this->getIncome($accounts, $all, $currentStart, $currentEnd));
$label = $currentStart->formatLocalized($format);
foreach ($combined as $name => $combi) {
// first is always expense account:
/** @var Account $exp */
$exp = $combi->first();
$labelIn = $exp->id . '-in';
$labelOut = $exp->id . '-out';
$labelSumIn = $exp->id . '-total-in';
$labelSumOut = $exp->id . '-total-out';
$currentIncome = $income[$name] ?? '0';
$currentExpense = $expenses[$name] ?? '0';
// add to sum:
$sumOfIncome[$exp->id] = $sumOfIncome[$exp->id] ?? '0';
$sumOfExpense[$exp->id] = $sumOfExpense[$exp->id] ?? '0';
$sumOfIncome[$exp->id] = bcadd($sumOfIncome[$exp->id], $currentIncome);
$sumOfExpense[$exp->id] = bcadd($sumOfExpense[$exp->id], $currentExpense);
// add to chart:
$chartData[$labelIn]['entries'][$label] = $currentIncome;
$chartData[$labelOut]['entries'][$label] = $currentExpense;
$chartData[$labelSumIn]['entries'][$label] = $sumOfIncome[$exp->id];
$chartData[$labelSumOut]['entries'][$label] = $sumOfExpense[$exp->id];
}
2018-07-09 19:24:08 +02:00
/** @var Carbon $currentStart */
2017-12-12 18:22:29 +01:00
$currentStart = clone $currentEnd;
$currentStart->addDay();
}
// remove all empty entries to prevent cluttering:
$newSet = [];
foreach ($chartData as $key => $entry) {
if (0 === !array_sum($entry['entries'])) {
$newSet[$key] = $chartData[$key];
}
}
2018-04-28 06:23:13 +02:00
if (0 === \count($newSet)) {
2017-12-12 18:22:29 +01:00
$newSet = $chartData; // @codeCoverageIgnore
}
$data = $this->generator->multiSet($newSet);
$cache->store($data);
2018-03-10 20:30:09 +01:00
return response()->json($data);
2017-12-12 18:22:29 +01:00
}
/**
2018-07-21 08:06:24 +02:00
* Searches for the opposing account.
*
2017-12-12 18:22:29 +01:00
* @param Collection $accounts
*
* @return array
*/
protected function combineAccounts(Collection $accounts): array
{
$combined = [];
/** @var Account $expenseAccount */
foreach ($accounts as $expenseAccount) {
$collection = new Collection;
$collection->push($expenseAccount);
$revenue = $this->accountRepository->findByName($expenseAccount->name, [AccountType::REVENUE]);
2018-04-02 15:10:40 +02:00
if (null !== $revenue) {
2017-12-12 18:22:29 +01:00
$collection->push($revenue);
}
$combined[$expenseAccount->name] = $collection;
}
return $combined;
}
/**
2018-07-21 08:06:24 +02:00
* Get all expenses for a set of accounts.
*
2017-12-12 18:22:29 +01:00
* @param Collection $accounts
* @param Collection $opposing
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
private function getExpenses(Collection $accounts, Collection $opposing, Carbon $start, Carbon $end): Collection
{
/** @var JournalCollectorInterface $collector */
$collector = app(JournalCollectorInterface::class);
$collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL])->setOpposingAccounts($opposing);
2018-04-02 15:10:40 +02:00
return $collector->getJournals();
2017-12-12 18:22:29 +01:00
}
/**
2018-07-21 08:06:24 +02:00
* Get the income for a set of accounts.
*
2017-12-12 18:22:29 +01:00
* @param Collection $accounts
* @param Collection $opposing
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
private function getIncome(Collection $accounts, Collection $opposing, Carbon $start, Carbon $end): Collection
{
/** @var JournalCollectorInterface $collector */
/** @var JournalCollectorInterface $collector */
$collector = app(JournalCollectorInterface::class);
$collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionType::DEPOSIT])->setOpposingAccounts($opposing);
2018-04-02 15:10:40 +02:00
return $collector->getJournals();
2017-12-12 18:22:29 +01:00
}
/**
2018-07-21 08:06:24 +02:00
* Group set of transactions by name of opposing account.
*
2017-12-12 18:22:29 +01:00
* @param Collection $set
*
* @return array
*/
private function groupByName(Collection $set): array
{
// group by opposing account name.
$grouped = [];
/** @var Transaction $transaction */
foreach ($set as $transaction) {
$name = $transaction->opposing_account_name;
$grouped[$name] = $grouped[$name] ?? '0';
$grouped[$name] = bcadd($transaction->transaction_amount, $grouped[$name]);
}
return $grouped;
}
}