Files
firefly-iii/app/Http/Controllers/Budget/IndexController.php

337 lines
14 KiB
PHP
Raw Normal View History

2018-07-14 15:22:21 +02:00
<?php
/**
* IndexController.php
2020-01-31 07:32:04 +01:00
* Copyright (c) 2019 james@firefly-iii.org
2018-07-14 15:22:21 +02:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2018-07-14 15:22:21 +02:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
2018-07-14 15:22:21 +02:00
*
* This program is distributed in the hope that it will be useful,
2018-07-14 15:22:21 +02:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2018-07-14 15:22:21 +02:00
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2018-07-14 15:22:21 +02:00
*/
declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Budget;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
2018-07-14 15:22:21 +02:00
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\AvailableBudget;
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\TransactionCurrency;
2019-08-30 08:00:52 +02:00
use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
2018-07-14 15:22:21 +02:00
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Support\Http\Controllers\DateCalculation;
use Illuminate\Contracts\View\Factory;
2018-10-17 15:18:09 +02:00
use Illuminate\Http\JsonResponse;
2018-07-14 15:22:21 +02:00
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Log;
2018-07-14 15:22:21 +02:00
/**
*
* Class IndexController
*/
class IndexController extends Controller
{
use DateCalculation;
2021-03-28 11:46:23 +02:00
2020-09-03 06:34:48 +02:00
private AvailableBudgetRepositoryInterface $abRepository;
2021-03-28 11:46:23 +02:00
private BudgetLimitRepositoryInterface $blRepository;
private CurrencyRepositoryInterface $currencyRepository;
private OperationsRepositoryInterface $opsRepository;
private BudgetRepositoryInterface $repository;
2018-07-14 15:22:21 +02:00
/**
2018-07-21 08:06:24 +02:00
* IndexController constructor.
*
* @codeCoverageIgnore
2018-07-14 15:22:21 +02:00
*/
public function __construct()
{
parent::__construct();
$this->middleware(
function ($request, $next) {
2022-03-29 14:58:06 +02:00
app('view')->share('title', (string) trans('firefly.budgets'));
app('view')->share('mainTitleIcon', 'fa-pie-chart');
$this->repository = app(BudgetRepositoryInterface::class);
$this->opsRepository = app(OperationsRepositoryInterface::class);
$this->abRepository = app(AvailableBudgetRepositoryInterface::class);
$this->currencyRepository = app(CurrencyRepositoryInterface::class);
$this->blRepository = app(BudgetLimitRepositoryInterface::class);
2018-08-07 17:34:43 +02:00
$this->repository->cleanupBudgets();
2018-07-14 15:22:21 +02:00
return $next($request);
}
);
}
/**
2018-07-21 08:06:24 +02:00
* Show all budgets.
*
2018-07-14 15:22:21 +02:00
* @param Request $request
*
* @param Carbon|null $start
* @param Carbon|null $end
2018-07-14 15:22:21 +02:00
*
* @return Factory|View
* @throws FireflyException
2022-03-29 15:10:05 +02:00
* @throws \JsonException
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
2018-07-14 15:22:21 +02:00
*/
2022-11-04 05:11:05 +01:00
public function index(Request $request, Carbon $start = null, Carbon $end = null) // @phpstan-ignore-line
2018-07-14 15:22:21 +02:00
{
2020-05-22 13:52:33 +02:00
Log::debug('Start of IndexController::index()');
2020-07-25 08:03:57 +02:00
2018-08-07 17:34:43 +02:00
// collect some basic vars:
2022-03-29 14:58:06 +02:00
$range = (string) app('preferences')->get('viewRange', '1M')->data;
$start = $start ?? session('start', Carbon::now()->startOfMonth());
$end = $end ?? app('navigation')->endOfPeriod($start, $range);
2018-08-07 17:34:43 +02:00
$defaultCurrency = app('amount')->getDefaultCurrency();
2020-10-31 08:00:44 +01:00
$currencies = $this->currencyRepository->get();
$budgeted = '0';
$spent = '0';
// new period stuff:
$periodTitle = app('navigation')->periodShow($start, $range);
$prevLoop = $this->getPreviousPeriods($start, $range);
$nextLoop = $this->getNextPeriods($start, $range);
2020-07-25 08:03:57 +02:00
// get all available budgets:
$availableBudgets = $this->getAllAvailableBudgets($start, $end);
// get all active budgets:
$budgets = $this->getAllBudgets($start, $end, $currencies, $defaultCurrency);
$sums = $this->getSums($budgets);
// get budgeted for default currency:
2022-11-04 05:11:05 +01:00
if (0 === count($availableBudgets)) {
2022-10-30 14:24:19 +01:00
$budgeted = $this->blRepository->budgeted($start, $end, $defaultCurrency, );
2020-07-25 08:03:57 +02:00
$spentArr = $this->opsRepository->sumExpenses($start, $end, null, null, $defaultCurrency);
$spent = $spentArr[$defaultCurrency->id]['sum'] ?? '0';
unset($spentArr);
}
// number of days for consistent budgeting.
$activeDaysPassed = $this->activeDaysPassed($start, $end); // see method description.
2022-03-29 14:58:06 +02:00
$activeDaysLeft = $this->activeDaysLeft($start, $end); // see method description.
2020-07-25 08:03:57 +02:00
// get all inactive budgets, and simply list them:
$inactive = $this->repository->getInactiveBudgets();
return view(
2022-10-30 14:24:19 +01:00
'budgets.index',
compact(
'availableBudgets',
'budgeted',
'spent',
'prevLoop',
'nextLoop',
'budgets',
'currencies',
'periodTitle',
'defaultCurrency',
'activeDaysPassed',
'activeDaysLeft',
'inactive',
'budgets',
'start',
'end',
'sums'
)
2020-07-25 08:03:57 +02:00
);
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function getAllAvailableBudgets(Carbon $start, Carbon $end): array
{
// get all available budgets.
$ab = $this->abRepository->get($start, $end);
$availableBudgets = [];
// for each, complement with spent amount:
/** @var AvailableBudget $entry */
foreach ($ab as $entry) {
$array = $entry->toArray();
$array['start_date'] = $entry->start_date;
$array['end_date'] = $entry->end_date;
// spent in period:
$spentArr = $this->opsRepository->sumExpenses($entry->start_date, $entry->end_date, null, null, $entry->transactionCurrency);
$array['spent'] = $spentArr[$entry->transaction_currency_id]['sum'] ?? '0';
// budgeted in period:
2022-10-30 14:24:19 +01:00
$budgeted = $this->blRepository->budgeted($entry->start_date, $entry->end_date, $entry->transactionCurrency, );
$array['budgeted'] = $budgeted;
$availableBudgets[] = $array;
unset($spentArr);
}
2020-07-25 08:03:57 +02:00
return $availableBudgets;
}
2018-08-07 17:34:43 +02:00
2020-07-25 08:03:57 +02:00
/**
* @param Carbon $start
* @param Carbon $end
* @param Collection $currencies
* @param TransactionCurrency $defaultCurrency
*
* @return array
*/
private function getAllBudgets(Carbon $start, Carbon $end, Collection $currencies, TransactionCurrency $defaultCurrency): array
{
2018-08-07 17:34:43 +02:00
// get all budgets, and paginate them into $budgets.
$collection = $this->repository->getActiveBudgets();
$budgets = [];
2020-05-22 13:52:33 +02:00
Log::debug(sprintf('7) Start is "%s", end is "%s"', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
// complement budget with budget limits in range, and expenses in currency X in range.
/** @var Budget $current */
foreach ($collection as $current) {
2020-12-25 12:45:34 +01:00
Log::debug(sprintf('Working on budget #%d ("%s")', $current->id, $current->name));
$array = $current->toArray();
$array['spent'] = [];
$array['budgeted'] = [];
2020-03-19 18:28:02 +01:00
$array['attachments'] = $this->repository->getAttachments($current);
2020-03-14 08:03:43 +01:00
$array['auto_budget'] = $this->repository->getAutoBudget($current);
$budgetLimits = $this->blRepository->getBudgetLimits($current, $start, $end);
/** @var BudgetLimit $limit */
foreach ($budgetLimits as $limit) {
2020-12-25 12:45:34 +01:00
Log::debug(sprintf('Working on budget limit #%d', $limit->id));
$currency = $limit->transactionCurrency ?? $defaultCurrency;
$array['budgeted'][] = [
'id' => $limit->id,
2022-12-24 05:06:39 +01:00
'amount' => app('steam')->bcround($limit->amount, $currency->decimal_places),
2022-03-27 20:24:13 +02:00
'start_date' => $limit->start_date->isoFormat($this->monthAndDayFormat),
'end_date' => $limit->end_date->isoFormat($this->monthAndDayFormat),
2020-05-22 13:52:33 +02:00
'in_range' => $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end),
2019-09-06 06:02:22 +02:00
'currency_id' => $currency->id,
'currency_symbol' => $currency->symbol,
'currency_name' => $currency->name,
'currency_decimal_places' => $currency->decimal_places,
];
}
/** @var TransactionCurrency $currency */
foreach ($currencies as $currency) {
$spentArr = $this->opsRepository->sumExpenses($start, $end, null, new Collection([$current]), $currency);
2021-04-07 10:52:38 +02:00
if (array_key_exists($currency->id, $spentArr) && array_key_exists('sum', $spentArr[$currency->id])) {
$array['spent'][$currency->id]['spent'] = $spentArr[$currency->id]['sum'];
$array['spent'][$currency->id]['currency_id'] = $currency->id;
$array['spent'][$currency->id]['currency_symbol'] = $currency->symbol;
$array['spent'][$currency->id]['currency_decimal_places'] = $currency->decimal_places;
}
}
$budgets[] = $array;
}
2021-03-28 11:46:23 +02:00
2020-07-25 08:03:57 +02:00
return $budgets;
2018-10-17 15:18:09 +02:00
}
2021-03-28 11:46:23 +02:00
/**
* @param array $budgets
*
* @return array
*/
private function getSums(array $budgets): array
{
$sums = [
'budgeted' => [],
'spent' => [],
'left' => [],
];
/** @var array $budget */
foreach ($budgets as $budget) {
/** @var array $spent */
foreach ($budget['spent'] as $spent) {
$currencyId = $spent['currency_id'];
$sums['spent'][$currencyId]
= $sums['spent'][$currencyId]
?? [
'amount' => '0',
'currency_id' => $spent['currency_id'],
'currency_symbol' => $spent['currency_symbol'],
'currency_decimal_places' => $spent['currency_decimal_places'],
];
$sums['spent'][$currencyId]['amount'] = bcadd($sums['spent'][$currencyId]['amount'], $spent['spent']);
}
/** @var array $budgeted */
foreach ($budget['budgeted'] as $budgeted) {
$currencyId = $budgeted['currency_id'];
$sums['budgeted'][$currencyId]
= $sums['budgeted'][$currencyId]
?? [
'amount' => '0',
'currency_id' => $budgeted['currency_id'],
'currency_symbol' => $budgeted['currency_symbol'],
'currency_decimal_places' => $budgeted['currency_decimal_places'],
];
$sums['budgeted'][$currencyId]['amount'] = bcadd($sums['budgeted'][$currencyId]['amount'], $budgeted['amount']);
// also calculate how much left from budgeted:
$sums['left'][$currencyId] = $sums['left'][$currencyId]
?? [
'amount' => '0',
'currency_id' => $budgeted['currency_id'],
'currency_symbol' => $budgeted['currency_symbol'],
'currency_decimal_places' => $budgeted['currency_decimal_places'],
];
}
}
// final calculation for 'left':
foreach ($sums['budgeted'] as $currencyId => $info) {
$spent = $sums['spent'][$currencyId]['amount'] ?? '0';
$budgeted = $sums['budgeted'][$currencyId]['amount'] ?? '0';
$sums['left'][$currencyId]['amount'] = bcadd($spent, $budgeted);
}
return $sums;
}
/**
* @param Request $request
* @param BudgetRepositoryInterface $repository
*
* @return JsonResponse
*/
public function reorder(Request $request, BudgetRepositoryInterface $repository): JsonResponse
{
$budgetIds = $request->get('budgetIds');
foreach ($budgetIds as $index => $budgetId) {
2022-03-29 14:58:06 +02:00
$budgetId = (int) $budgetId;
2021-06-30 06:17:38 +02:00
$budget = $repository->find($budgetId);
2021-03-28 11:46:23 +02:00
if (null !== $budget) {
Log::debug(sprintf('Set budget #%d ("%s") to position %d', $budget->id, $budget->name, $index + 1));
$repository->setBudgetOrder($budget, $index + 1);
}
}
app('preferences')->mark();
return response()->json(['OK']);
}
}