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

320 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;
2023-10-28 06:58:33 +02:00
use FireflyIII\Repositories\UserGroups\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;
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.
2018-07-14 15:22:21 +02:00
*/
public function __construct()
{
parent::__construct();
$this->middleware(
function ($request, $next) {
2022-12-29 19:41:57 +01: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.
*
* @return Factory|View
2023-12-20 19:35:52 +01:00
*
* @throws FireflyException
2023-12-22 07:58:35 +01:00
* */
2023-11-29 06:30:35 +01:00
public function index(Carbon $start = null, Carbon $end = null)
2018-07-14 15:22:21 +02:00
{
$this->abRepository->cleanup();
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Start of IndexController::index("%s", "%s")', $start?->format('Y-m-d'), $end?->format('Y-m-d')));
2020-07-25 08:03:57 +02:00
2018-08-07 17:34:43 +02:00
// collect some basic vars:
$range = app('navigation')->getViewRange(true);
$isCustomRange = session('is_custom_range', false);
if (false === $isCustomRange) {
2023-12-10 06:45:59 +01:00
$start ??= session('start', today(config('app.timezone'))->startOfMonth());
2023-12-10 06:51:59 +01:00
$end ??= app('navigation')->endOfPeriod($start, $range);
}
// overrule start and end if necessary:
if (true === $isCustomRange) {
2023-12-10 06:45:59 +01:00
$start ??= session('start', today(config('app.timezone'))->startOfMonth());
2023-12-10 06:51:59 +01:00
$end ??= session('end', today(config('app.timezone'))->endOfMonth());
}
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)) {
2023-12-20 19:35:52 +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
);
}
2023-12-20 19:35:52 +01:00
public function reorder(Request $request, BudgetRepositoryInterface $repository): JsonResponse
{
$this->abRepository->cleanup();
$budgetIds = $request->get('budgetIds');
foreach ($budgetIds as $index => $budgetId) {
$budgetId = (int)$budgetId;
$budget = $repository->find($budgetId);
if (null !== $budget) {
app('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']);
}
2020-07-25 08:03:57 +02:00
private function getAllAvailableBudgets(Carbon $start, Carbon $end): array
{
// get all available budgets.
$ab = $this->abRepository->get($start, $end);
$availableBudgets = [];
2023-12-20 19:35:52 +01:00
// 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:
2023-12-20 19:35:52 +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
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 = [];
2023-10-29 06:33:43 +01:00
app('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) {
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Working on budget #%d ("%s")', $current->id, $current->name));
$array = $current->toArray();
$array['spent'] = [];
2023-09-03 17:38:54 +02:00
$array['spent_total'] = [];
$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);
2023-12-20 19:35:52 +01:00
/** @var BudgetLimit $limit */
foreach ($budgetLimits as $limit) {
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Working on budget limit #%d', $limit->id));
$currency = $limit->transactionCurrency ?? $defaultCurrency;
2023-09-03 17:38:54 +02:00
$amount = app('steam')->bcround($limit->amount, $currency->decimal_places);
$array['budgeted'][] = [
'id' => $limit->id,
2023-09-03 17:38:54 +02:00
'amount' => $amount,
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,
];
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('The amount budgeted for budget limit #%d is %s %s', $limit->id, $currency->code, $amount));
}
/** @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
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]
2023-12-10 06:51:59 +01:00
??= [
2023-12-20 19:35:52 +01:00
'amount' => '0',
'currency_id' => $spent['currency_id'],
'currency_symbol' => $spent['currency_symbol'],
'currency_decimal_places' => $spent['currency_decimal_places'],
];
2021-03-28 11:46:23 +02:00
$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]
2023-12-10 06:51:59 +01:00
??= [
2023-12-20 19:35:52 +01:00
'amount' => '0',
'currency_id' => $budgeted['currency_id'],
'currency_symbol' => $budgeted['currency_symbol'],
'currency_decimal_places' => $budgeted['currency_decimal_places'],
];
2021-03-28 11:46:23 +02:00
$sums['budgeted'][$currencyId]['amount'] = bcadd($sums['budgeted'][$currencyId]['amount'], $budgeted['amount']);
// also calculate how much left from budgeted:
2023-12-10 06:51:59 +01:00
$sums['left'][$currencyId]
??= [
2023-12-20 19:35:52 +01:00
'amount' => '0',
'currency_id' => $budgeted['currency_id'],
'currency_symbol' => $budgeted['currency_symbol'],
'currency_decimal_places' => $budgeted['currency_decimal_places'],
];
2021-03-28 11:46:23 +02:00
}
}
2023-12-20 19:35:52 +01:00
2021-03-28 11:46:23 +02:00
// final calculation for 'left':
2023-01-03 06:48:53 +01:00
/**
2023-11-29 06:30:35 +01:00
* @var int $currencyId
2023-01-03 06:48:53 +01:00
*/
2023-11-29 06:30:35 +01:00
foreach (array_keys($sums['budgeted']) as $currencyId) {
2021-03-28 11:46:23 +02:00
$spent = $sums['spent'][$currencyId]['amount'] ?? '0';
$budgeted = $sums['budgeted'][$currencyId]['amount'] ?? '0';
$sums['left'][$currencyId]['amount'] = bcadd($spent, $budgeted);
}
return $sums;
}
}