Code cleanup.

This commit is contained in:
James Cole
2021-03-28 11:46:23 +02:00
parent 2c575f3ca5
commit b5eeacc128
124 changed files with 1568 additions and 1384 deletions

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Exceptions; namespace FireflyIII\Exceptions;
use Exception; use Exception;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\Attachment; use FireflyIII\Models\Attachment;

View File

@@ -207,6 +207,7 @@ class AccountFactory
if (null !== $result) { if (null !== $result) {
Log::debug(sprintf('Found account type based on %d and "%s": "%s"', $accountTypeId, $accountType, $result->type)); Log::debug(sprintf('Found account type based on %d and "%s": "%s"', $accountTypeId, $accountType, $result->type));
} }
return $result; return $result;
} }

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Factory; namespace FireflyIII\Factory;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use FireflyIII\User; use FireflyIII\User;

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Factory; namespace FireflyIII\Factory;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
use FireflyIII\User; use FireflyIII\User;

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Factory; namespace FireflyIII\Factory;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Recurrence; use FireflyIII\Models\Recurrence;
@@ -42,6 +43,7 @@ class RecurrenceFactory
private MessageBag $errors; private MessageBag $errors;
private User $user; private User $user;
/** /**
* Constructor. * Constructor.
* *

View File

@@ -44,6 +44,7 @@ class TransactionFactory
private TransactionJournal $journal; private TransactionJournal $journal;
private bool $reconciled; private bool $reconciled;
private User $user; private User $user;
/** /**
* Constructor. * Constructor.
* *

View File

@@ -40,6 +40,7 @@ class TransactionGroupFactory
private $journalFactory; private $journalFactory;
/** @var User The user */ /** @var User The user */
private $user; private $user;
/** /**
* TransactionGroupFactory constructor. * TransactionGroupFactory constructor.
*/ */
@@ -73,7 +74,7 @@ class TransactionGroupFactory
if (null !== $title) { if (null !== $title) {
$title = substr($title, 0, 1000); $title = substr($title, 0, 1000);
} }
if(0 === $collection->count()) { if (0 === $collection->count()) {
throw new FireflyException('Created zero transaction journals.'); throw new FireflyException('Created zero transaction journals.');
} }

View File

@@ -65,6 +65,7 @@ class YearReportGenerator implements ReportGeneratorInterface
return $result; return $result;
} }
/** /**
* Set the accounts. * Set the accounts.
* *

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Handlers\Events; namespace FireflyIII\Handlers\Events;
use Exception; use Exception;
use FireflyIII\Mail\AccessTokenCreatedMail; use FireflyIII\Mail\AccessTokenCreatedMail;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Handlers\Events; namespace FireflyIII\Handlers\Events;
use FireflyIII\Events\DestroyedTransactionGroup; use FireflyIII\Events\DestroyedTransactionGroup;
use FireflyIII\Events\RequestedSendWebhookMessages; use FireflyIII\Events\RequestedSendWebhookMessages;
use FireflyIII\Generator\Webhook\MessageGeneratorInterface; use FireflyIII\Generator\Webhook\MessageGeneratorInterface;

View File

@@ -23,12 +23,14 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Handlers\Events; namespace FireflyIII\Handlers\Events;
use FireflyIII\Events\RequestedVersionCheckStatus; use FireflyIII\Events\RequestedVersionCheckStatus;
use FireflyIII\Helpers\Update\UpdateTrait; use FireflyIII\Helpers\Update\UpdateTrait;
use FireflyIII\Models\Configuration; use FireflyIII\Models\Configuration;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Log; use Log;
/** /**
* Class VersionCheckEventHandler * Class VersionCheckEventHandler
*/ */

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Handlers\Events; namespace FireflyIII\Handlers\Events;
use FireflyIII\Jobs\SendWebhookMessage; use FireflyIII\Jobs\SendWebhookMessage;
use FireflyIII\Models\WebhookMessage; use FireflyIII\Models\WebhookMessage;
use Log; use Log;

View File

@@ -55,6 +55,7 @@ class AttachmentHelper implements AttachmentHelperInterface
/** @var Filesystem The disk where attachments are stored. */ /** @var Filesystem The disk where attachments are stored. */
protected $uploadDisk; protected $uploadDisk;
/** /**
* AttachmentHelper constructor. * AttachmentHelper constructor.
* *
@@ -69,6 +70,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$this->attachments = new Collection; $this->attachments = new Collection;
$this->uploadDisk = Storage::disk('upload'); $this->uploadDisk = Storage::disk('upload');
} }
/** /**
* Returns the content of an attachment. * Returns the content of an attachment.
* *

View File

@@ -52,6 +52,7 @@ trait AccountCollection
return $this; return $this;
} }
/** /**
* These accounts must not be source accounts. * These accounts must not be source accounts.
* *
@@ -70,6 +71,7 @@ trait AccountCollection
return $this; return $this;
} }
/** /**
* Define which accounts can be part of the source and destination transactions. * Define which accounts can be part of the source and destination transactions.
* *
@@ -115,6 +117,7 @@ trait AccountCollection
return $this; return $this;
} }
/** /**
* Define which accounts can be part of the source and destination transactions. * Define which accounts can be part of the source and destination transactions.
* *
@@ -133,6 +136,7 @@ trait AccountCollection
return $this; return $this;
} }
/** /**
* Define which accounts can be part of the source and destination transactions. * Define which accounts can be part of the source and destination transactions.
* *
@@ -151,6 +155,7 @@ trait AccountCollection
return $this; return $this;
} }
/** /**
* Either account can be set, but NOT both. This effectively excludes internal transfers. * Either account can be set, but NOT both. This effectively excludes internal transfers.
* *
@@ -187,6 +192,7 @@ trait AccountCollection
return $this; return $this;
} }
/** /**
* Will include the source and destination account names and types. * Will include the source and destination account names and types.
* *
@@ -210,9 +216,9 @@ trait AccountCollection
$this->query->leftJoin('account_types as dest_account_type', 'dest_account_type.id', '=', 'dest_account.account_type_id'); $this->query->leftJoin('account_types as dest_account_type', 'dest_account_type.id', '=', 'dest_account.account_type_id');
// and add fields: // and add fields:
$this->fields[] = 'dest_account.name as destination_account_name'; $this->fields[] = 'dest_account.name as destination_account_name';
$this->fields[] = 'dest_account.iban as destination_account_iban'; $this->fields[] = 'dest_account.iban as destination_account_iban';
$this->fields[] = 'dest_account_type.type as destination_account_type'; $this->fields[] = 'dest_account_type.type as destination_account_type';
$this->hasAccountInfo = true; $this->hasAccountInfo = true;
} }

View File

@@ -43,7 +43,7 @@ trait CollectorProperties
/** @var bool Will be true if query result contains category info. */ /** @var bool Will be true if query result contains category info. */
private $hasCatInformation; private $hasCatInformation;
/** @var bool Will be true for attachments */ /** @var bool Will be true for attachments */
private $hasJoinedAttTables; private $hasJoinedAttTables;
private bool $hasJoinedMetaTables; private bool $hasJoinedMetaTables;
/** @var bool Will be true of the query has the tag info tables joined. */ /** @var bool Will be true of the query has the tag info tables joined. */
private $hasJoinedTagTables; private $hasJoinedTagTables;

View File

@@ -102,6 +102,7 @@ trait TimeCollection
return $this; return $this;
} }
/** /**
* Collect transactions updated on a specific date. * Collect transactions updated on a specific date.
* *

View File

@@ -485,6 +485,25 @@ class GroupCollector implements GroupCollectorInterface
return $this; return $this;
} }
/**
* Join table to get attachment information.
*/
private function joinAttachmentTables(): void
{
if (false === $this->hasJoinedAttTables) {
// join some extra tables:
$this->hasJoinedAttTables = true;
$this->query->leftJoin('attachments', 'attachments.attachable_id', '=', 'transaction_journals.id')
->where(
static function (EloquentBuilder $q1) {
$q1->where('attachments.attachable_type', TransactionJournal::class);
$q1->where('attachments.uploaded', 1);
$q1->orWhereNull('attachments.attachable_type');
}
);
}
}
/** /**
* Build the query. * Build the query.
*/ */
@@ -528,25 +547,6 @@ class GroupCollector implements GroupCollectorInterface
->orderBy('source.amount', 'DESC'); ->orderBy('source.amount', 'DESC');
} }
/**
* Join table to get attachment information.
*/
private function joinAttachmentTables(): void
{
if (false === $this->hasJoinedAttTables) {
// join some extra tables:
$this->hasJoinedAttTables = true;
$this->query->leftJoin('attachments', 'attachments.attachable_id', '=', 'transaction_journals.id')
->where(
static function (EloquentBuilder $q1) {
$q1->where('attachments.attachable_type', TransactionJournal::class);
$q1->where('attachments.uploaded', 1);
$q1->orWhereNull('attachments.attachable_type');
}
);
}
}
/** /**
* *
*/ */

View File

@@ -44,7 +44,7 @@ class CreateController extends Controller
{ {
use ModelInformation; use ModelInformation;
private AttachmentHelperInterface $attachments; private AttachmentHelperInterface $attachments;
private AccountRepositoryInterface $repository; private AccountRepositoryInterface $repository;
/** /**
@@ -60,7 +60,7 @@ class CreateController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('mainTitleIcon', 'fa-credit-card');
app('view')->share('title', (string) trans('firefly.accounts')); app('view')->share('title', (string)trans('firefly.accounts'));
$this->repository = app(AccountRepositoryInterface::class); $this->repository = app(AccountRepositoryInterface::class);
$this->attachments = app(AttachmentHelperInterface::class); $this->attachments = app(AttachmentHelperInterface::class);
@@ -83,7 +83,7 @@ class CreateController extends Controller
$objectType = $objectType ?? 'asset'; $objectType = $objectType ?? 'asset';
$defaultCurrency = app('amount')->getDefaultCurrency(); $defaultCurrency = app('amount')->getDefaultCurrency();
$subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType));
$subTitle = (string) trans(sprintf('firefly.make_new_%s_account', $objectType)); $subTitle = (string)trans(sprintf('firefly.make_new_%s_account', $objectType));
$roles = $this->getRoles(); $roles = $this->getRoles();
$liabilityTypes = $this->getLiabilityTypes(); $liabilityTypes = $this->getLiabilityTypes();
$hasOldInput = null !== $request->old('_token'); $hasOldInput = null !== $request->old('_token');
@@ -98,9 +98,9 @@ class CreateController extends Controller
// interest calculation periods: // interest calculation periods:
$interestPeriods = [ $interestPeriods = [
'daily' => (string) trans('firefly.interest_calc_daily'), 'daily' => (string)trans('firefly.interest_calc_daily'),
'monthly' => (string) trans('firefly.interest_calc_monthly'), 'monthly' => (string)trans('firefly.interest_calc_monthly'),
'yearly' => (string) trans('firefly.interest_calc_yearly'), 'yearly' => (string)trans('firefly.interest_calc_yearly'),
]; ];
// pre fill some data // pre fill some data
@@ -108,7 +108,7 @@ class CreateController extends Controller
'preFilled', 'preFilled',
[ [
'currency_id' => $defaultCurrency->id, 'currency_id' => $defaultCurrency->id,
'include_net_worth' => $hasOldInput ? (bool) $request->old('include_net_worth') : true, 'include_net_worth' => $hasOldInput ? (bool)$request->old('include_net_worth') : true,
] ]
); );
@@ -133,7 +133,7 @@ class CreateController extends Controller
{ {
$data = $request->getAccountData(); $data = $request->getAccountData();
$account = $this->repository->store($data); $account = $this->repository->store($data);
$request->session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name])); $request->session()->flash('success', (string)trans('firefly.stored_new_account', ['name' => $account->name]));
app('preferences')->mark(); app('preferences')->mark();
Log::channel('audit')->info('Stored new account.', $data); Log::channel('audit')->info('Stored new account.', $data);
@@ -152,7 +152,7 @@ class CreateController extends Controller
$this->attachments->saveAttachmentsForModel($account, $files); $this->attachments->saveAttachmentsForModel($account, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info',(string)trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -161,7 +161,7 @@ class CreateController extends Controller
// redirect to previous URL. // redirect to previous URL.
$redirect = redirect($this->getPreviousUri('accounts.create.uri')); $redirect = redirect($this->getPreviousUri('accounts.create.uri'));
if (1 === (int) $request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
// set value so create routine will not overwrite URL: // set value so create routine will not overwrite URL:
$request->session()->put('accounts.create.fromStore', true); $request->session()->put('accounts.create.fromStore', true);

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Account; namespace FireflyIII\Http\Controllers\Account;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
@@ -55,7 +56,7 @@ class DeleteController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('mainTitleIcon', 'fa-credit-card');
app('view')->share('title', (string) trans('firefly.accounts')); app('view')->share('title', (string)trans('firefly.accounts'));
$this->repository = app(AccountRepositoryInterface::class); $this->repository = app(AccountRepositoryInterface::class);
@@ -78,7 +79,7 @@ class DeleteController extends Controller
} }
$typeName = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); $typeName = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type));
$subTitle = (string) trans(sprintf('firefly.delete_%s_account', $typeName), ['name' => $account->name]); $subTitle = (string)trans(sprintf('firefly.delete_%s_account', $typeName), ['name' => $account->name]);
$accountList = app('expandedform')->makeSelectListWithEmpty($this->repository->getAccountsByType([$account->accountType->type])); $accountList = app('expandedform')->makeSelectListWithEmpty($this->repository->getAccountsByType([$account->accountType->type]));
$objectType = $typeName; $objectType = $typeName;
unset($accountList[$account->id]); unset($accountList[$account->id]);
@@ -106,11 +107,11 @@ class DeleteController extends Controller
$type = $account->accountType->type; $type = $account->accountType->type;
$typeName = config(sprintf('firefly.shortNamesByFullName.%s', $type)); $typeName = config(sprintf('firefly.shortNamesByFullName.%s', $type));
$name = $account->name; $name = $account->name;
$moveTo = $this->repository->findNull((int) $request->get('move_account_before_delete')); $moveTo = $this->repository->findNull((int)$request->get('move_account_before_delete'));
$this->repository->destroy($account, $moveTo); $this->repository->destroy($account, $moveTo);
$request->session()->flash('success', (string) trans(sprintf('firefly.%s_deleted', $typeName), ['name' => $name])); $request->session()->flash('success', (string)trans(sprintf('firefly.%s_deleted', $typeName), ['name' => $name]));
app('preferences')->mark(); app('preferences')->mark();
return redirect($this->getPreviousUri('accounts.delete.uri')); return redirect($this->getPreviousUri('accounts.delete.uri'));

View File

@@ -44,13 +44,13 @@ use Illuminate\View\View;
class EditController extends Controller class EditController extends Controller
{ {
use ModelInformation, UserNavigation; use ModelInformation, UserNavigation;
private AttachmentHelperInterface $attachments;
/** @var CurrencyRepositoryInterface The currency repository */ /** @var CurrencyRepositoryInterface The currency repository */
private $currencyRepos; private $currencyRepos;
/** @var AccountRepositoryInterface The account repository */ /** @var AccountRepositoryInterface The account repository */
private $repository; private $repository;
private AttachmentHelperInterface $attachments;
/** /**
* EditController constructor. * EditController constructor.
*/ */
@@ -62,7 +62,7 @@ class EditController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('mainTitleIcon', 'fa-credit-card');
app('view')->share('title', (string) trans('firefly.accounts')); app('view')->share('title', (string)trans('firefly.accounts'));
$this->repository = app(AccountRepositoryInterface::class); $this->repository = app(AccountRepositoryInterface::class);
$this->currencyRepos = app(CurrencyRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class);
@@ -89,7 +89,7 @@ class EditController extends Controller
} }
$objectType = config('firefly.shortNamesByFullName')[$account->accountType->type]; $objectType = config('firefly.shortNamesByFullName')[$account->accountType->type];
$subTitle = (string) trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]); $subTitle = (string)trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]);
$subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType));
$roles = $this->getRoles(); $roles = $this->getRoles();
$liabilityTypes = $this->getLiabilityTypes(); $liabilityTypes = $this->getLiabilityTypes();
@@ -109,9 +109,9 @@ class EditController extends Controller
// interest calculation periods: // interest calculation periods:
$interestPeriods = [ $interestPeriods = [
'daily' => (string) trans('firefly.interest_calc_daily'), 'daily' => (string)trans('firefly.interest_calc_daily'),
'monthly' => (string) trans('firefly.interest_calc_monthly'), 'monthly' => (string)trans('firefly.interest_calc_monthly'),
'yearly' => (string) trans('firefly.interest_calc_yearly'), 'yearly' => (string)trans('firefly.interest_calc_yearly'),
]; ];
// put previous url in session if not redirect from store (not "return_to_edit"). // put previous url in session if not redirect from store (not "return_to_edit").
@@ -120,7 +120,7 @@ class EditController extends Controller
} }
$request->session()->forget('accounts.edit.fromUpdate'); $request->session()->forget('accounts.edit.fromUpdate');
$openingBalanceAmount = (string) $repository->getOpeningBalanceAmount($account); $openingBalanceAmount = (string)$repository->getOpeningBalanceAmount($account);
$openingBalanceDate = $repository->getOpeningBalanceDate($account); $openingBalanceDate = $repository->getOpeningBalanceDate($account);
$currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency(); $currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
@@ -145,7 +145,7 @@ class EditController extends Controller
'interest' => $repository->getMetaValue($account, 'interest'), 'interest' => $repository->getMetaValue($account, 'interest'),
'interest_period' => $repository->getMetaValue($account, 'interest_period'), 'interest_period' => $repository->getMetaValue($account, 'interest_period'),
'notes' => $this->repository->getNoteText($account), 'notes' => $this->repository->getNoteText($account),
'active' => $hasOldInput ? (bool) $request->old('active') : $account->active, 'active' => $hasOldInput ? (bool)$request->old('active') : $account->active,
]; ];
$request->session()->flash('preFilled', $preFilled); $request->session()->flash('preFilled', $preFilled);
@@ -166,6 +166,7 @@ class EditController extends Controller
) )
); );
} }
/** /**
* Update the account. * Update the account.
* *
@@ -183,7 +184,7 @@ class EditController extends Controller
$data = $request->getAccountData(); $data = $request->getAccountData();
$this->repository->update($account, $data); $this->repository->update($account, $data);
$request->session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name])); $request->session()->flash('success', (string)trans('firefly.updated_account', ['name' => $account->name]));
// store new attachment(s): // store new attachment(s):
$files = $request->hasFile('attachments') ? $request->file('attachments') : null; $files = $request->hasFile('attachments') ? $request->file('attachments') : null;
@@ -191,7 +192,7 @@ class EditController extends Controller
$this->attachments->saveAttachmentsForModel($account, $files); $this->attachments->saveAttachmentsForModel($account, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info',(string)trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -200,7 +201,7 @@ class EditController extends Controller
// redirect // redirect
$redirect = redirect($this->getPreviousUri('accounts.edit.uri')); $redirect = redirect($this->getPreviousUri('accounts.edit.uri'));
if (1 === (int) $request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {
// set value so edit routine will not overwrite URL: // set value so edit routine will not overwrite URL:
$request->session()->put('accounts.edit.fromUpdate', true); $request->session()->put('accounts.edit.fromUpdate', true);

View File

@@ -50,6 +50,7 @@ use Log;
class ReconcileController extends Controller class ReconcileController extends Controller
{ {
use UserNavigation; use UserNavigation;
/** @var AccountRepositoryInterface The account repository */ /** @var AccountRepositoryInterface The account repository */
private $accountRepos; private $accountRepos;
/** @var CurrencyRepositoryInterface The currency repository */ /** @var CurrencyRepositoryInterface The currency repository */
@@ -70,7 +71,7 @@ class ReconcileController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('mainTitleIcon', 'fa-credit-card');
app('view')->share('title', (string) trans('firefly.accounts')); app('view')->share('title', (string)trans('firefly.accounts'));
$this->repository = app(JournalRepositoryInterface::class); $this->repository = app(JournalRepositoryInterface::class);
$this->accountRepos = app(AccountRepositoryInterface::class); $this->accountRepos = app(AccountRepositoryInterface::class);
$this->currencyRepos = app(CurrencyRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class);
@@ -87,8 +88,8 @@ class ReconcileController extends Controller
* @param Carbon|null $start * @param Carbon|null $start
* @param Carbon|null $end * @param Carbon|null $end
* *
* @throws Exception
* @return Factory|RedirectResponse|Redirector|View * @return Factory|RedirectResponse|Redirector|View
* @throws Exception
*/ */
public function reconcile(Account $account, Carbon $start = null, Carbon $end = null) public function reconcile(Account $account, Carbon $start = null, Carbon $end = null)
{ {
@@ -97,7 +98,7 @@ class ReconcileController extends Controller
} }
if (AccountType::ASSET !== $account->accountType->type) { if (AccountType::ASSET !== $account->accountType->type) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
session()->flash('error', (string) trans('firefly.must_be_asset_account')); session()->flash('error', (string)trans('firefly.must_be_asset_account'));
return redirect(route('accounts.index', [config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type))])); return redirect(route('accounts.index', [config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type))]));
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@@ -127,10 +128,10 @@ class ReconcileController extends Controller
$startDate = clone $start; $startDate = clone $start;
$startDate->subDay(); $startDate->subDay();
$startBalance = number_format((float) app('steam')->balance($account, $startDate), $currency->decimal_places, '.', ''); $startBalance = number_format((float)app('steam')->balance($account, $startDate), $currency->decimal_places, '.', '');
$endBalance = number_format((float) app('steam')->balance($account, $end), $currency->decimal_places, '.', ''); $endBalance = number_format((float)app('steam')->balance($account, $end), $currency->decimal_places, '.', '');
$subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type)); $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type));
$subTitle = (string) trans('firefly.reconcile_account', ['account' => $account->name]); $subTitle = (string)trans('firefly.reconcile_account', ['account' => $account->name]);
// various links // various links
$transactionsUri = route('accounts.reconcile.transactions', [$account->id, '%start%', '%end%']); $transactionsUri = route('accounts.reconcile.transactions', [$account->id, '%start%', '%end%']);
@@ -178,7 +179,7 @@ class ReconcileController extends Controller
/** @var string $journalId */ /** @var string $journalId */
foreach ($data['journals'] as $journalId) { foreach ($data['journals'] as $journalId) {
$this->repository->reconcileById((int) $journalId); $this->repository->reconcileById((int)$journalId);
} }
Log::debug('Reconciled all transactions.'); Log::debug('Reconciled all transactions.');
@@ -195,10 +196,10 @@ class ReconcileController extends Controller
Log::debug('End of routine.'); Log::debug('End of routine.');
app('preferences')->mark(); app('preferences')->mark();
if ('' === $result) { if ('' === $result) {
session()->flash('success', (string) trans('firefly.reconciliation_stored')); session()->flash('success', (string)trans('firefly.reconciliation_stored'));
} }
if ('' !== $result) { if ('' !== $result) {
session()->flash('error', (string) trans('firefly.reconciliation_error', ['error' => $result])); session()->flash('error', (string)trans('firefly.reconciliation_error', ['error' => $result]));
} }
return redirect(route('accounts.show', [$account->id])); return redirect(route('accounts.show', [$account->id]));
@@ -212,9 +213,9 @@ class ReconcileController extends Controller
* @param Carbon $end * @param Carbon $end
* @param string $difference * @param string $difference
* *
* @return RedirectResponse|Redirector|string
* @throws DuplicateTransactionException * @throws DuplicateTransactionException
* *
* @return RedirectResponse|Redirector|string
*/ */
private function createReconciliation(Account $account, Carbon $start, Carbon $end, string $difference) private function createReconciliation(Account $account, Carbon $start, Carbon $end, string $difference)
{ {

View File

@@ -32,10 +32,12 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Support\Http\Controllers\PeriodOverview; use FireflyIII\Support\Http\Controllers\PeriodOverview;
use FireflyIII\Support\Http\Controllers\UserNavigation; use FireflyIII\Support\Http\Controllers\UserNavigation;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Routing\Redirector; use Illuminate\Routing\Redirector;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\View\View;
/** /**
* Class ShowController * Class ShowController
@@ -46,7 +48,7 @@ class ShowController extends Controller
use UserNavigation, PeriodOverview; use UserNavigation, PeriodOverview;
private CurrencyRepositoryInterface $currencyRepos; private CurrencyRepositoryInterface $currencyRepos;
private AccountRepositoryInterface $repository; private AccountRepositoryInterface $repository;
/** /**
* ShowController constructor. * ShowController constructor.
@@ -63,7 +65,7 @@ class ShowController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('mainTitleIcon', 'fa-credit-card');
app('view')->share('title', (string) trans('firefly.accounts')); app('view')->share('title', (string)trans('firefly.accounts'));
$this->repository = app(AccountRepositoryInterface::class); $this->repository = app(AccountRepositoryInterface::class);
$this->currencyRepos = app(CurrencyRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class);
@@ -72,6 +74,7 @@ class ShowController extends Controller
} }
); );
} }
/** /**
* Show an account. * Show an account.
* *
@@ -80,13 +83,13 @@ class ShowController extends Controller
* @param Carbon|null $start * @param Carbon|null $start
* @param Carbon|null $end * @param Carbon|null $end
* *
* @return RedirectResponse|Redirector|Factory|View
* @throws Exception * @throws Exception
* *
* @return RedirectResponse|Redirector|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/ */
public function show(Request $request, Account $account, Carbon $start = null, Carbon $end = null) public function show(Request $request, Account $account, Carbon $start = null, Carbon $end = null)
{ {
$objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type));
if (!$this->isEditableAccount($account)) { if (!$this->isEditableAccount($account)) {
return $this->redirectAccountToAccount($account); // @codeCoverageIgnore return $this->redirectAccountToAccount($account); // @codeCoverageIgnore
@@ -104,12 +107,12 @@ class ShowController extends Controller
$attachments = $this->repository->getAttachments($account); $attachments = $this->repository->getAttachments($account);
$today = today(config('app.timezone')); $today = today(config('app.timezone'));
$subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type)); $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type));
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency(); $currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
$fStart = $start->formatLocalized($this->monthAndDayFormat); $fStart = $start->formatLocalized($this->monthAndDayFormat);
$fEnd = $end->formatLocalized($this->monthAndDayFormat); $fEnd = $end->formatLocalized($this->monthAndDayFormat);
$subTitle = (string) trans('firefly.journals_in_period_for_account', ['name' => $account->name, 'start' => $fStart, 'end' => $fEnd]); $subTitle = (string)trans('firefly.journals_in_period_for_account', ['name' => $account->name, 'start' => $fStart, 'end' => $fEnd]);
$chartUri = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); $chartUri = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]);
$firstTransaction = $this->repository->oldestJournalDate($account) ?? $start; $firstTransaction = $this->repository->oldestJournalDate($account) ?? $start;
$periods = $this->getAccountPeriodOverview($account, $firstTransaction, $end); $periods = $this->getAccountPeriodOverview($account, $firstTransaction, $end);
@@ -155,9 +158,9 @@ class ShowController extends Controller
* @param Request $request * @param Request $request
* @param Account $account * @param Account $account
* *
* @return RedirectResponse|Redirector|Factory|View
* @throws Exception * @throws Exception
* *
* @return RedirectResponse|Redirector|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/ */
public function showAll(Request $request, Account $account) public function showAll(Request $request, Account $account)
{ {
@@ -166,16 +169,16 @@ class ShowController extends Controller
} }
$location = $this->repository->getLocation($account); $location = $this->repository->getLocation($account);
$isLiability = $this->repository->isLiability($account); $isLiability = $this->repository->isLiability($account);
$attachments = $this->repository->getAttachments($account); $attachments = $this->repository->getAttachments($account);
$objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type));
$end = today(config('app.timezone')); $end = today(config('app.timezone'));
$today = today(config('app.timezone')); $today = today(config('app.timezone'));
$start = $this->repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth(); $start = $this->repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
$subTitleIcon = config('firefly.subIconsByIdentifier.' . $account->accountType->type); $subTitleIcon = config('firefly.subIconsByIdentifier.' . $account->accountType->type);
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency(); $currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
$subTitle = (string) trans('firefly.all_journals_for_account', ['name' => $account->name]); $subTitle = (string)trans('firefly.all_journals_for_account', ['name' => $account->name]);
$periods = new Collection; $periods = new Collection;
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);

View File

@@ -47,7 +47,7 @@ class ConfigurationController extends Controller
$this->middleware( $this->middleware(
static function ($request, $next) { static function ($request, $next) {
app('view')->share('title', (string) trans('firefly.administration')); app('view')->share('title', (string)trans('firefly.administration'));
app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); app('view')->share('mainTitleIcon', 'fa-hand-spock-o');
return $next($request); return $next($request);
@@ -63,7 +63,7 @@ class ConfigurationController extends Controller
*/ */
public function index() public function index()
{ {
$subTitle = (string) trans('firefly.instance_configuration'); $subTitle = (string)trans('firefly.instance_configuration');
$subTitleIcon = 'fa-wrench'; $subTitleIcon = 'fa-wrench';
Log::channel('audit')->info('User visits admin config index.'); Log::channel('audit')->info('User visits admin config index.');
@@ -99,7 +99,7 @@ class ConfigurationController extends Controller
app('fireflyconfig')->set('is_demo_site', $data['is_demo_site']); app('fireflyconfig')->set('is_demo_site', $data['is_demo_site']);
// flash message // flash message
session()->flash('success', (string) trans('firefly.configuration_updated')); session()->flash('success', (string)trans('firefly.configuration_updated'));
app('preferences')->mark(); app('preferences')->mark();
return redirect()->route('admin.configuration.index'); return redirect()->route('admin.configuration.index');

View File

@@ -28,6 +28,8 @@ use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Jobs\SubmitTelemetryData; use FireflyIII\Jobs\SubmitTelemetryData;
use FireflyIII\Repositories\Telemetry\TelemetryRepositoryInterface; use FireflyIII\Repositories\Telemetry\TelemetryRepositoryInterface;
use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\View\View; use Illuminate\View\View;
/** /**
@@ -47,7 +49,7 @@ class TelemetryController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.administration')); app('view')->share('title', (string)trans('firefly.administration'));
app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); app('view')->share('mainTitleIcon', 'fa-hand-spock-o');
$this->repository = app(TelemetryRepositoryInterface::class); $this->repository = app(TelemetryRepositoryInterface::class);
@@ -57,7 +59,19 @@ class TelemetryController extends Controller
} }
/** /**
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * @return RedirectResponse|Redirector
*/
public function deleteAll()
{
$this->repository->deleteAll();
session()->flash('success', trans('firefly.telemetry_all_deleted'));
return redirect(url()->previous(route('admin.telemetry.index')));
}
/**
* @return RedirectResponse|Redirector
*/ */
public function deleteSubmitted() public function deleteSubmitted()
{ {
@@ -69,15 +83,18 @@ class TelemetryController extends Controller
} }
/** /**
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * Index
*/ */
public function deleteAll() public function index()
{ {
$this->repository->deleteAll(); app('view')->share('subTitleIcon', 'fa-eye');
app('view')->share('subTitle', (string)trans('firefly.telemetry_admin_index'));
$version = config('firefly.version');
$enabled = config('firefly.send_telemetry', false) && config('firefly.feature_flags.telemetry');
session()->flash('success', trans('firefly.telemetry_all_deleted')); $count = $this->repository->count();
return redirect(url()->previous(route('admin.telemetry.index'))); return prefixView('admin.telemetry.index', compact('version', 'enabled', 'count'));
} }
/** /**
@@ -94,21 +111,6 @@ class TelemetryController extends Controller
return redirect(url()->previous(route('admin.telemetry.index'))); return redirect(url()->previous(route('admin.telemetry.index')));
} }
/**
* Index
*/
public function index()
{
app('view')->share('subTitleIcon', 'fa-eye');
app('view')->share('subTitle', (string) trans('firefly.telemetry_admin_index'));
$version = config('firefly.version');
$enabled = config('firefly.send_telemetry', false) && config('firefly.feature_flags.telemetry');
$count = $this->repository->count();
return prefixView('admin.telemetry.index', compact('version', 'enabled', 'count'));
}
/** /**
* View telemetry. Paginated because you never know how much will be collected. * View telemetry. Paginated because you never know how much will be collected.
* *

View File

@@ -49,7 +49,7 @@ class UpdateController extends Controller
parent::__construct(); parent::__construct();
$this->middleware( $this->middleware(
static function ($request, $next) { static function ($request, $next) {
app('view')->share('title', (string) trans('firefly.administration')); app('view')->share('title', (string)trans('firefly.administration'));
app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); app('view')->share('mainTitleIcon', 'fa-hand-spock-o');
return $next($request); return $next($request);
@@ -67,22 +67,22 @@ class UpdateController extends Controller
*/ */
public function index() public function index()
{ {
$subTitle = (string) trans('firefly.update_check_title'); $subTitle = (string)trans('firefly.update_check_title');
$subTitleIcon = 'fa-star'; $subTitleIcon = 'fa-star';
$permission = app('fireflyconfig')->get('permission_update_check', -1); $permission = app('fireflyconfig')->get('permission_update_check', -1);
$channel = app('fireflyconfig')->get('update_channel', 'stable'); $channel = app('fireflyconfig')->get('update_channel', 'stable');
$selected = $permission->data; $selected = $permission->data;
$channelSelected = $channel->data; $channelSelected = $channel->data;
$options = [ $options = [
-1 => (string) trans('firefly.updates_ask_me_later'), -1 => (string)trans('firefly.updates_ask_me_later'),
0 => (string) trans('firefly.updates_do_not_check'), 0 => (string)trans('firefly.updates_do_not_check'),
1 => (string) trans('firefly.updates_enable_check'), 1 => (string)trans('firefly.updates_enable_check'),
]; ];
$channelOptions = [ $channelOptions = [
'stable' => (string) trans('firefly.update_channel_stable'), 'stable' => (string)trans('firefly.update_channel_stable'),
'beta' => (string) trans('firefly.update_channel_beta'), 'beta' => (string)trans('firefly.update_channel_beta'),
'alpha' => (string) trans('firefly.update_channel_alpha'), 'alpha' => (string)trans('firefly.update_channel_alpha'),
]; ];
return prefixView('admin.update.index', compact('subTitle', 'subTitleIcon', 'selected', 'options', 'channelSelected', 'channelOptions')); return prefixView('admin.update.index', compact('subTitle', 'subTitleIcon', 'selected', 'options', 'channelSelected', 'channelOptions'));
@@ -97,18 +97,18 @@ class UpdateController extends Controller
*/ */
public function post(Request $request) public function post(Request $request)
{ {
$checkForUpdates = (int) $request->get('check_for_updates'); $checkForUpdates = (int)$request->get('check_for_updates');
$channel = $request->get('update_channel'); $channel = $request->get('update_channel');
$channel = in_array($channel, ['stable', 'beta', 'alpha'], true) ? $channel : 'stable'; $channel = in_array($channel, ['stable', 'beta', 'alpha'], true) ? $channel : 'stable';
// store as telemetry // store as telemetry
app('telemetry')->feature('admin.update.channel', $channel); app('telemetry')->feature('admin.update.channel', $channel);
app('telemetry')->feature('admin.update.permission', (string) $checkForUpdates); app('telemetry')->feature('admin.update.permission', (string)$checkForUpdates);
app('fireflyconfig')->set('permission_update_check', $checkForUpdates); app('fireflyconfig')->set('permission_update_check', $checkForUpdates);
app('fireflyconfig')->set('last_update_check', time()); app('fireflyconfig')->set('last_update_check', time());
app('fireflyconfig')->set('update_channel', $channel); app('fireflyconfig')->set('update_channel', $channel);
session()->flash('success', (string) trans('firefly.configuration_updated')); session()->flash('success', (string)trans('firefly.configuration_updated'));
return redirect(route('admin.update-check')); return redirect(route('admin.update-check'));
} }

View File

@@ -27,8 +27,11 @@ use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Http\Requests\UserFormRequest; use FireflyIII\Http\Requests\UserFormRequest;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector; use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Log; use Log;
/** /**
@@ -36,8 +39,8 @@ use Log;
*/ */
class UserController extends Controller class UserController extends Controller
{ {
private UserRepositoryInterface $repository;
protected bool $externalIdentity; protected bool $externalIdentity;
private UserRepositoryInterface $repository;
/** /**
* UserController constructor. * UserController constructor.
@@ -64,7 +67,7 @@ class UserController extends Controller
/** /**
* @param User $user * @param User $user
* *
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|RedirectResponse|Redirector|\Illuminate\View\View * @return Application|Factory|RedirectResponse|Redirector|View
*/ */
public function delete(User $user) public function delete(User $user)
{ {
@@ -104,7 +107,7 @@ class UserController extends Controller
* *
* @param User $user * @param User $user
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Factory|View
*/ */
public function edit(User $user) public function edit(User $user)
{ {
@@ -135,7 +138,7 @@ class UserController extends Controller
/** /**
* Show index of user manager. * Show index of user manager.
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Factory|View
*/ */
public function index() public function index()
{ {
@@ -159,7 +162,7 @@ class UserController extends Controller
* *
* @param User $user * @param User $user
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Factory|View
*/ */
public function show(User $user) public function show(User $user)
{ {

View File

@@ -26,9 +26,12 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Requests\AttachmentFormRequest; use FireflyIII\Http\Requests\AttachmentFormRequest;
use FireflyIII\Models\Attachment; use FireflyIII\Models\Attachment;
use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface; use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response as LaravelResponse; use Illuminate\Http\Response as LaravelResponse;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
/** /**
* Class AttachmentController. * Class AttachmentController.
@@ -52,7 +55,7 @@ class AttachmentController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-paperclip'); app('view')->share('mainTitleIcon', 'fa-paperclip');
app('view')->share('title', (string) trans('firefly.attachments')); app('view')->share('title', (string)trans('firefly.attachments'));
$this->repository = app(AttachmentRepositoryInterface::class); $this->repository = app(AttachmentRepositoryInterface::class);
return $next($request); return $next($request);
@@ -65,11 +68,11 @@ class AttachmentController extends Controller
* *
* @param Attachment $attachment * @param Attachment $attachment
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Factory|View
*/ */
public function delete(Attachment $attachment) public function delete(Attachment $attachment)
{ {
$subTitle = (string) trans('firefly.delete_attachment', ['name' => $attachment->filename]); $subTitle = (string)trans('firefly.delete_attachment', ['name' => $attachment->filename]);
// put previous url in session // put previous url in session
$this->rememberPreviousUri('attachments.delete.uri'); $this->rememberPreviousUri('attachments.delete.uri');
@@ -83,7 +86,7 @@ class AttachmentController extends Controller
* @param Request $request * @param Request $request
* @param Attachment $attachment * @param Attachment $attachment
* *
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * @return RedirectResponse|Redirector
*/ */
public function destroy(Request $request, Attachment $attachment) public function destroy(Request $request, Attachment $attachment)
{ {
@@ -91,7 +94,7 @@ class AttachmentController extends Controller
$this->repository->destroy($attachment); $this->repository->destroy($attachment);
$request->session()->flash('success', (string) trans('firefly.attachment_deleted', ['name' => $name])); $request->session()->flash('success', (string)trans('firefly.attachment_deleted', ['name' => $name]));
app('preferences')->mark(); app('preferences')->mark();
return redirect($this->getPreviousUri('attachments.delete.uri')); return redirect($this->getPreviousUri('attachments.delete.uri'));
@@ -102,9 +105,9 @@ class AttachmentController extends Controller
* *
* @param Attachment $attachment * @param Attachment $attachment
* *
* @throws FireflyException
* @return mixed * @return mixed
* *
* @throws FireflyException
*/ */
public function download(Attachment $attachment) public function download(Attachment $attachment)
{ {
@@ -136,12 +139,12 @@ class AttachmentController extends Controller
* @param Request $request * @param Request $request
* @param Attachment $attachment * @param Attachment $attachment
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Factory|View
*/ */
public function edit(Request $request, Attachment $attachment) public function edit(Request $request, Attachment $attachment)
{ {
$subTitleIcon = 'fa-pencil'; $subTitleIcon = 'fa-pencil';
$subTitle = (string) trans('firefly.edit_attachment', ['name' => $attachment->filename]); $subTitle = (string)trans('firefly.edit_attachment', ['name' => $attachment->filename]);
// put previous url in session if not redirect from store (not "return_to_edit"). // put previous url in session if not redirect from store (not "return_to_edit").
if (true !== session('attachments.edit.fromUpdate')) { if (true !== session('attachments.edit.fromUpdate')) {
@@ -159,7 +162,7 @@ class AttachmentController extends Controller
/** /**
* Index of all attachments. * Index of all attachments.
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Factory|View
*/ */
public function index() public function index()
{ {
@@ -171,6 +174,7 @@ class AttachmentController extends Controller
return $attachment; return $attachment;
} }
); );
return prefixView('attachments.index', compact('set')); return prefixView('attachments.index', compact('set'));
} }
@@ -187,11 +191,11 @@ class AttachmentController extends Controller
$data = $request->getAttachmentData(); $data = $request->getAttachmentData();
$this->repository->update($attachment, $data); $this->repository->update($attachment, $data);
$request->session()->flash('success', (string) trans('firefly.attachment_updated', ['name' => $attachment->filename])); $request->session()->flash('success', (string)trans('firefly.attachment_updated', ['name' => $attachment->filename]));
app('preferences')->mark(); app('preferences')->mark();
$redirect = redirect($this->getPreviousUri('attachments.edit.uri')); $redirect = redirect($this->getPreviousUri('attachments.edit.uri'));
if (1 === (int) $request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
$request->session()->put('attachments.edit.fromUpdate', true); $request->session()->put('attachments.edit.fromUpdate', true);
@@ -208,8 +212,8 @@ class AttachmentController extends Controller
* *
* @param Attachment $attachment * @param Attachment $attachment
* *
* @throws FireflyException
* @return LaravelResponse * @return LaravelResponse
* @throws FireflyException
*/ */
public function view(Request $request, Attachment $attachment): LaravelResponse public function view(Request $request, Attachment $attachment): LaravelResponse
{ {

View File

@@ -67,6 +67,7 @@ class LoginController extends Controller
parent::__construct(); parent::__construct();
$this->middleware('guest')->except('logout'); $this->middleware('guest')->except('logout');
} }
/** /**
* Handle a login request to the application. * Handle a login request to the application.
* *
@@ -214,6 +215,7 @@ class LoginController extends Controller
$cookieName = config('google2fa.cookie_name', 'google2fa_token'); $cookieName = config('google2fa.cookie_name', 'google2fa_token');
request()->cookies->set($cookieName, 'invalid'); request()->cookies->set($cookieName, 'invalid');
} }
return prefixView('auth.login', compact('allowRegistration', 'email', 'remember', 'allowReset', 'title')); return prefixView('auth.login', compact('allowRegistration', 'email', 'remember', 'allowReset', 'title'));
} }

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Bill; namespace FireflyIII\Http\Controllers\Bill;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Bill; namespace FireflyIII\Http\Controllers\Bill;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Bill; use FireflyIII\Models\Bill;
use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface;

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Bill; namespace FireflyIII\Http\Controllers\Bill;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\BillUpdateRequest; use FireflyIII\Http\Requests\BillUpdateRequest;
@@ -62,6 +63,7 @@ class EditController extends Controller
} }
); );
} }
/** /**
* Edit a bill. * Edit a bill.
* *
@@ -108,6 +110,7 @@ class EditController extends Controller
return prefixView('bills.edit', compact('subTitle', 'periods', 'rules', 'bill', 'defaultCurrency', 'preFilled')); return prefixView('bills.edit', compact('subTitle', 'periods', 'rules', 'bill', 'defaultCurrency', 'preFilled'));
} }
/** /**
* Update a bill. * Update a bill.
* *

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Bill; namespace FireflyIII\Http\Controllers\Bill;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Bill; use FireflyIII\Models\Bill;
@@ -139,6 +140,7 @@ class IndexController extends Controller
return prefixView('bills.index', compact('bills', 'sums', 'total', 'totals')); return prefixView('bills.index', compact('bills', 'sums', 'total', 'totals'));
} }
/** /**
* @param array $bills * @param array $bills
* *

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Bill; namespace FireflyIII\Http\Controllers\Bill;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
@@ -116,6 +117,7 @@ class ShowController extends Controller
return redirect(route('bills.show', [$bill->id])); return redirect(route('bills.show', [$bill->id]));
} }
/** /**
* Show a bill. * Show a bill.
* *

View File

@@ -127,7 +127,7 @@ class AvailableBudgetController extends Controller
return true; return true;
} }
); );
$page = (int)($request->get('page') ?? 1); $page = (int)($request->get('page') ?? 1);
return prefixView('budgets.available-budgets.create-alternative', compact('start', 'end', 'page', 'currencies')); return prefixView('budgets.available-budgets.create-alternative', compact('start', 'end', 'page', 'currencies'));
} }

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Budget; namespace FireflyIII\Http\Controllers\Budget;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\BudgetFormStoreRequest; use FireflyIII\Http\Requests\BudgetFormStoreRequest;
@@ -37,8 +38,8 @@ use Illuminate\View\View;
*/ */
class CreateController extends Controller class CreateController extends Controller
{ {
private BudgetRepositoryInterface $repository;
private AttachmentHelperInterface $attachments; private AttachmentHelperInterface $attachments;
private BudgetRepositoryInterface $repository;
/** /**
* CreateController constructor. * CreateController constructor.
@@ -50,15 +51,16 @@ class CreateController extends Controller
parent::__construct(); parent::__construct();
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('title', (string)trans('firefly.budgets'));
app('view')->share('mainTitleIcon', 'fa-pie-chart'); app('view')->share('mainTitleIcon', 'fa-pie-chart');
$this->repository = app(BudgetRepositoryInterface::class); $this->repository = app(BudgetRepositoryInterface::class);
$this->attachments = app(AttachmentHelperInterface::class); $this->attachments = app(AttachmentHelperInterface::class);
return $next($request); return $next($request);
} }
); );
} }
/** /**
* Form to create a budget. * Form to create a budget.
* *
@@ -72,23 +74,23 @@ class CreateController extends Controller
// auto budget types // auto budget types
$autoBudgetTypes = [ $autoBudgetTypes = [
0 => (string) trans('firefly.auto_budget_none'), 0 => (string)trans('firefly.auto_budget_none'),
AutoBudget::AUTO_BUDGET_RESET => (string) trans('firefly.auto_budget_reset'), AutoBudget::AUTO_BUDGET_RESET => (string)trans('firefly.auto_budget_reset'),
AutoBudget::AUTO_BUDGET_ROLLOVER => (string) trans('firefly.auto_budget_rollover'), AutoBudget::AUTO_BUDGET_ROLLOVER => (string)trans('firefly.auto_budget_rollover'),
]; ];
$autoBudgetPeriods = [ $autoBudgetPeriods = [
'daily' => (string) trans('firefly.auto_budget_period_daily'), 'daily' => (string)trans('firefly.auto_budget_period_daily'),
'weekly' => (string) trans('firefly.auto_budget_period_weekly'), 'weekly' => (string)trans('firefly.auto_budget_period_weekly'),
'monthly' => (string) trans('firefly.auto_budget_period_monthly'), 'monthly' => (string)trans('firefly.auto_budget_period_monthly'),
'quarterly' => (string) trans('firefly.auto_budget_period_quarterly'), 'quarterly' => (string)trans('firefly.auto_budget_period_quarterly'),
'half_year' => (string) trans('firefly.auto_budget_period_half_year'), 'half_year' => (string)trans('firefly.auto_budget_period_half_year'),
'yearly' => (string) trans('firefly.auto_budget_period_yearly'), 'yearly' => (string)trans('firefly.auto_budget_period_yearly'),
]; ];
$currency = app('amount')->getDefaultCurrency(); $currency = app('amount')->getDefaultCurrency();
$preFilled = [ $preFilled = [
'auto_budget_period' => $hasOldInput ? (bool) $request->old('auto_budget_period') : 'monthly', 'auto_budget_period' => $hasOldInput ? (bool)$request->old('auto_budget_period') : 'monthly',
'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $currency->id, 'auto_budget_currency_id' => $hasOldInput ? (int)$request->old('auto_budget_currency_id') : $currency->id,
]; ];
$request->session()->flash('preFilled', $preFilled); $request->session()->flash('preFilled', $preFilled);
@@ -98,10 +100,11 @@ class CreateController extends Controller
$this->rememberPreviousUri('budgets.create.uri'); $this->rememberPreviousUri('budgets.create.uri');
} }
$request->session()->forget('budgets.create.fromStore'); $request->session()->forget('budgets.create.fromStore');
$subTitle = (string) trans('firefly.create_new_budget'); $subTitle = (string)trans('firefly.create_new_budget');
return prefixView('budgets.create', compact('subTitle', 'autoBudgetTypes', 'autoBudgetPeriods')); return prefixView('budgets.create', compact('subTitle', 'autoBudgetTypes', 'autoBudgetPeriods'));
} }
/** /**
* Stores a budget. * Stores a budget.
* *
@@ -115,7 +118,7 @@ class CreateController extends Controller
$budget = $this->repository->store($data); $budget = $this->repository->store($data);
$this->repository->cleanupBudgets(); $this->repository->cleanupBudgets();
$request->session()->flash('success', (string) trans('firefly.stored_new_budget', ['name' => $budget->name])); $request->session()->flash('success', (string)trans('firefly.stored_new_budget', ['name' => $budget->name]));
app('preferences')->mark(); app('preferences')->mark();
// store attachment(s): // store attachment(s):
@@ -124,7 +127,7 @@ class CreateController extends Controller
$this->attachments->saveAttachmentsForModel($budget, $files); $this->attachments->saveAttachmentsForModel($budget, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info',(string)trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -133,7 +136,7 @@ class CreateController extends Controller
$redirect = redirect($this->getPreviousUri('budgets.create.uri')); $redirect = redirect($this->getPreviousUri('budgets.create.uri'));
if (1 === (int) $request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
$request->session()->put('budgets.create.fromStore', true); $request->session()->put('budgets.create.fromStore', true);

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Budget; namespace FireflyIII\Http\Controllers\Budget;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Budget; use FireflyIII\Models\Budget;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
@@ -51,7 +52,7 @@ class DeleteController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('title', (string)trans('firefly.budgets'));
app('view')->share('mainTitleIcon', 'fa-pie-chart'); app('view')->share('mainTitleIcon', 'fa-pie-chart');
$this->repository = app(BudgetRepositoryInterface::class); $this->repository = app(BudgetRepositoryInterface::class);
@@ -59,6 +60,7 @@ class DeleteController extends Controller
} }
); );
} }
/** /**
* Deletes a budget. * Deletes a budget.
* *
@@ -68,7 +70,7 @@ class DeleteController extends Controller
*/ */
public function delete(Budget $budget) public function delete(Budget $budget)
{ {
$subTitle = (string) trans('firefly.delete_budget', ['name' => $budget->name]); $subTitle = (string)trans('firefly.delete_budget', ['name' => $budget->name]);
// put previous url in session // put previous url in session
$this->rememberPreviousUri('budgets.delete.uri'); $this->rememberPreviousUri('budgets.delete.uri');
@@ -88,7 +90,7 @@ class DeleteController extends Controller
{ {
$name = $budget->name; $name = $budget->name;
$this->repository->destroy($budget); $this->repository->destroy($budget);
$request->session()->flash('success', (string) trans('firefly.deleted_budget', ['name' => $name])); $request->session()->flash('success', (string)trans('firefly.deleted_budget', ['name' => $name]));
app('preferences')->mark(); app('preferences')->mark();
return redirect($this->getPreviousUri('budgets.delete.uri')); return redirect($this->getPreviousUri('budgets.delete.uri'));

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Budget; namespace FireflyIII\Http\Controllers\Budget;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\BudgetFormUpdateRequest; use FireflyIII\Http\Requests\BudgetFormUpdateRequest;
@@ -39,11 +40,10 @@ use Illuminate\View\View;
*/ */
class EditController extends Controller class EditController extends Controller
{ {
/** @var BudgetRepositoryInterface The budget repository */
private $repository;
/** @var AttachmentHelperInterface Helper for attachments. */ /** @var AttachmentHelperInterface Helper for attachments. */
private $attachments; private $attachments;
/** @var BudgetRepositoryInterface The budget repository */
private $repository;
/** /**
* EditController constructor. * EditController constructor.
@@ -56,9 +56,9 @@ class EditController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('title', (string)trans('firefly.budgets'));
app('view')->share('mainTitleIcon', 'fa-pie-chart'); app('view')->share('mainTitleIcon', 'fa-pie-chart');
$this->repository = app(BudgetRepositoryInterface::class); $this->repository = app(BudgetRepositoryInterface::class);
$this->attachments = app(AttachmentHelperInterface::class); $this->attachments = app(AttachmentHelperInterface::class);
return $next($request); return $next($request);
@@ -76,30 +76,30 @@ class EditController extends Controller
*/ */
public function edit(Request $request, Budget $budget) public function edit(Request $request, Budget $budget)
{ {
$subTitle = (string) trans('firefly.edit_budget', ['name' => $budget->name]); $subTitle = (string)trans('firefly.edit_budget', ['name' => $budget->name]);
$autoBudget = $this->repository->getAutoBudget($budget); $autoBudget = $this->repository->getAutoBudget($budget);
// auto budget types // auto budget types
$autoBudgetTypes = [ $autoBudgetTypes = [
0 => (string) trans('firefly.auto_budget_none'), 0 => (string)trans('firefly.auto_budget_none'),
AutoBudget::AUTO_BUDGET_RESET => (string) trans('firefly.auto_budget_reset'), AutoBudget::AUTO_BUDGET_RESET => (string)trans('firefly.auto_budget_reset'),
AutoBudget::AUTO_BUDGET_ROLLOVER => (string) trans('firefly.auto_budget_rollover'), AutoBudget::AUTO_BUDGET_ROLLOVER => (string)trans('firefly.auto_budget_rollover'),
]; ];
$autoBudgetPeriods = [ $autoBudgetPeriods = [
'daily' => (string) trans('firefly.auto_budget_period_daily'), 'daily' => (string)trans('firefly.auto_budget_period_daily'),
'weekly' => (string) trans('firefly.auto_budget_period_weekly'), 'weekly' => (string)trans('firefly.auto_budget_period_weekly'),
'monthly' => (string) trans('firefly.auto_budget_period_monthly'), 'monthly' => (string)trans('firefly.auto_budget_period_monthly'),
'quarterly' => (string) trans('firefly.auto_budget_period_quarterly'), 'quarterly' => (string)trans('firefly.auto_budget_period_quarterly'),
'half_year' => (string) trans('firefly.auto_budget_period_half_year'), 'half_year' => (string)trans('firefly.auto_budget_period_half_year'),
'yearly' => (string) trans('firefly.auto_budget_period_yearly'), 'yearly' => (string)trans('firefly.auto_budget_period_yearly'),
]; ];
// code to handle active-checkboxes // code to handle active-checkboxes
$hasOldInput = null !== $request->old('_token'); $hasOldInput = null !== $request->old('_token');
$currency = app('amount')->getDefaultCurrency(); $currency = app('amount')->getDefaultCurrency();
$preFilled = [ $preFilled = [
'active' => $hasOldInput ? (bool) $request->old('active') : $budget->active, 'active' => $hasOldInput ? (bool)$request->old('active') : $budget->active,
'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $currency->id, 'auto_budget_currency_id' => $hasOldInput ? (int)$request->old('auto_budget_currency_id') : $currency->id,
]; ];
if ($autoBudget) { if ($autoBudget) {
$preFilled['auto_budget_amount'] = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount; $preFilled['auto_budget_amount'] = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount;
@@ -128,7 +128,7 @@ class EditController extends Controller
$data = $request->getBudgetData(); $data = $request->getBudgetData();
$this->repository->update($budget, $data); $this->repository->update($budget, $data);
$request->session()->flash('success', (string) trans('firefly.updated_budget', ['name' => $budget->name])); $request->session()->flash('success', (string)trans('firefly.updated_budget', ['name' => $budget->name]));
$this->repository->cleanupBudgets(); $this->repository->cleanupBudgets();
app('preferences')->mark(); app('preferences')->mark();
@@ -140,14 +140,14 @@ class EditController extends Controller
$this->attachments->saveAttachmentsForModel($budget, $files); $this->attachments->saveAttachmentsForModel($budget, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info',(string)trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
$request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore
} }
if (1 === (int) $request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
$request->session()->put('budgets.edit.fromUpdate', true); $request->session()->put('budgets.edit.fromUpdate', true);

View File

@@ -49,11 +49,12 @@ use Log;
class IndexController extends Controller class IndexController extends Controller
{ {
use DateCalculation; use DateCalculation;
private AvailableBudgetRepositoryInterface $abRepository; private AvailableBudgetRepositoryInterface $abRepository;
private BudgetLimitRepositoryInterface $blRepository; private BudgetLimitRepositoryInterface $blRepository;
private CurrencyRepositoryInterface $currencyRepository; private CurrencyRepositoryInterface $currencyRepository;
private OperationsRepositoryInterface $opsRepository; private OperationsRepositoryInterface $opsRepository;
private BudgetRepositoryInterface $repository; private BudgetRepositoryInterface $repository;
/** /**
* IndexController constructor. * IndexController constructor.
@@ -66,7 +67,7 @@ class IndexController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('title', (string)trans('firefly.budgets'));
app('view')->share('mainTitleIcon', 'fa-pie-chart'); app('view')->share('mainTitleIcon', 'fa-pie-chart');
$this->repository = app(BudgetRepositoryInterface::class); $this->repository = app(BudgetRepositoryInterface::class);
$this->opsRepository = app(OperationsRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class);
@@ -95,7 +96,7 @@ class IndexController extends Controller
Log::debug('Start of IndexController::index()'); Log::debug('Start of IndexController::index()');
// collect some basic vars: // collect some basic vars:
$range = (string) app('preferences')->get('viewRange', '1M')->data; $range = (string)app('preferences')->get('viewRange', '1M')->data;
$start = $start ?? session('start', Carbon::now()->startOfMonth()); $start = $start ?? session('start', Carbon::now()->startOfMonth());
$end = $end ?? app('navigation')->endOfPeriod($start, $range); $end = $end ?? app('navigation')->endOfPeriod($start, $range);
$defaultCurrency = app('amount')->getDefaultCurrency(); $defaultCurrency = app('amount')->getDefaultCurrency();
@@ -141,91 +142,6 @@ class IndexController extends Controller
); );
} }
/**
* @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) {
$budgetId = (int) $budgetId;
$budget = $repository->findNull($budgetId);
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']);
}
/**
* @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 Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
@@ -289,7 +205,7 @@ class IndexController extends Controller
$currency = $limit->transactionCurrency ?? $defaultCurrency; $currency = $limit->transactionCurrency ?? $defaultCurrency;
$array['budgeted'][] = [ $array['budgeted'][] = [
'id' => $limit->id, 'id' => $limit->id,
'amount' => number_format((float) $limit->amount, $currency->decimal_places, '.', ''), 'amount' => number_format((float)$limit->amount, $currency->decimal_places, '.', ''),
'start_date' => $limit->start_date->formatLocalized($this->monthAndDayFormat), 'start_date' => $limit->start_date->formatLocalized($this->monthAndDayFormat),
'end_date' => $limit->end_date->formatLocalized($this->monthAndDayFormat), 'end_date' => $limit->end_date->formatLocalized($this->monthAndDayFormat),
'in_range' => $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end), 'in_range' => $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end),
@@ -312,6 +228,92 @@ class IndexController extends Controller
} }
$budgets[] = $array; $budgets[] = $array;
} }
return $budgets; return $budgets;
} }
/**
* @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) {
$budgetId = (int)$budgetId;
$budget = $repository->findNull($budgetId);
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']);
}
} }

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Budget; namespace FireflyIII\Http\Controllers\Budget;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
@@ -44,8 +45,9 @@ use Illuminate\View\View;
class ShowController extends Controller class ShowController extends Controller
{ {
use PeriodOverview, AugumentData; use PeriodOverview, AugumentData;
private JournalRepositoryInterface $journalRepos; private JournalRepositoryInterface $journalRepos;
private BudgetRepositoryInterface $repository; private BudgetRepositoryInterface $repository;
/** /**
* ShowController constructor. * ShowController constructor.
@@ -58,10 +60,10 @@ class ShowController extends Controller
parent::__construct(); parent::__construct();
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('title', (string)trans('firefly.budgets'));
app('view')->share('mainTitleIcon', 'fa-pie-chart'); app('view')->share('mainTitleIcon', 'fa-pie-chart');
$this->journalRepos = app(JournalRepositoryInterface::class); $this->journalRepos = app(JournalRepositoryInterface::class);
$this->repository = app(BudgetRepositoryInterface::class); $this->repository = app(BudgetRepositoryInterface::class);
return $next($request); return $next($request);
} }
@@ -92,8 +94,8 @@ class ShowController extends Controller
$first = $this->journalRepos->firstNull(); $first = $this->journalRepos->firstNull();
$firstDate = null !== $first ? $first->date : $start; $firstDate = null !== $first ? $first->date : $start;
$periods = $this->getNoBudgetPeriodOverview($firstDate, $end); $periods = $this->getNoBudgetPeriodOverview($firstDate, $end);
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
@@ -115,12 +117,12 @@ class ShowController extends Controller
public function noBudgetAll(Request $request) public function noBudgetAll(Request $request)
{ {
$subTitle = (string) trans('firefly.all_journals_without_budget'); $subTitle = (string)trans('firefly.all_journals_without_budget');
$first = $this->journalRepos->firstNull(); $first = $this->journalRepos->firstNull();
$start = null === $first ? new Carbon : $first->date; $start = null === $first ? new Carbon : $first->date;
$end = today(config('app.timezone')); $end = today(config('app.timezone'));
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
@@ -131,6 +133,7 @@ class ShowController extends Controller
return prefixView('budgets.no-budget', compact('groups', 'subTitle', 'start', 'end')); return prefixView('budgets.no-budget', compact('groups', 'subTitle', 'start', 'end'));
} }
/** /**
* Show a single budget. * Show a single budget.
* *
@@ -142,12 +145,12 @@ class ShowController extends Controller
public function show(Request $request, Budget $budget) public function show(Request $request, Budget $budget)
{ {
/** @var Carbon $start */ /** @var Carbon $start */
$allStart = session('first', Carbon::now()->startOfYear()); $allStart = session('first', Carbon::now()->startOfYear());
$allEnd = today(); $allEnd = today();
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$limits = $this->getLimits($budget, $allStart, $allEnd); $limits = $this->getLimits($budget, $allStart, $allEnd);
$repetition = null; $repetition = null;
$attachments = $this->repository->getAttachments($budget); $attachments = $this->repository->getAttachments($budget);
// collector: // collector:
@@ -159,9 +162,9 @@ class ShowController extends Controller
$groups = $collector->getPaginatedGroups(); $groups = $collector->getPaginatedGroups();
$groups->setPath(route('budgets.show', [$budget->id])); $groups->setPath(route('budgets.show', [$budget->id]));
$subTitle = (string) trans('firefly.all_journals_for_budget', ['name' => $budget->name]); $subTitle = (string)trans('firefly.all_journals_for_budget', ['name' => $budget->name]);
return prefixView('budgets.show', compact('limits','attachments', 'budget', 'repetition', 'groups', 'subTitle')); return prefixView('budgets.show', compact('limits', 'attachments', 'budget', 'repetition', 'groups', 'subTitle'));
} }
/** /**
@@ -171,8 +174,8 @@ class ShowController extends Controller
* @param Budget $budget * @param Budget $budget
* @param BudgetLimit $budgetLimit * @param BudgetLimit $budgetLimit
* *
* @throws FireflyException
* @return Factory|View * @return Factory|View
* @throws FireflyException
*/ */
public function showByBudgetLimit(Request $request, Budget $budget, BudgetLimit $budgetLimit) public function showByBudgetLimit(Request $request, Budget $budget, BudgetLimit $budgetLimit)
{ {
@@ -180,8 +183,8 @@ class ShowController extends Controller
throw new FireflyException('This budget limit is not part of this budget.'); // @codeCoverageIgnore throw new FireflyException('This budget limit is not part of this budget.'); // @codeCoverageIgnore
} }
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$subTitle = trans( $subTitle = trans(
'firefly.budget_in_period', 'firefly.budget_in_period',
[ [
@@ -201,11 +204,11 @@ class ShowController extends Controller
$groups = $collector->getPaginatedGroups(); $groups = $collector->getPaginatedGroups();
$groups->setPath(route('budgets.show', [$budget->id, $budgetLimit->id])); $groups->setPath(route('budgets.show', [$budget->id, $budgetLimit->id]));
/** @var Carbon $start */ /** @var Carbon $start */
$start = session('first', Carbon::now()->startOfYear()); $start = session('first', Carbon::now()->startOfYear());
$end = today(config('app.timezone')); $end = today(config('app.timezone'));
$attachments = $this->repository->getAttachments($budget); $attachments = $this->repository->getAttachments($budget);
$limits = $this->getLimits($budget, $start, $end); $limits = $this->getLimits($budget, $start, $end);
return prefixView('budgets.show', compact('limits','attachments', 'budget', 'budgetLimit', 'groups', 'subTitle')); return prefixView('budgets.show', compact('limits', 'attachments', 'budget', 'budgetLimit', 'groups', 'subTitle'));
} }
} }

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Category; namespace FireflyIII\Http\Controllers\Category;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\CategoryFormRequest; use FireflyIII\Http\Requests\CategoryFormRequest;
@@ -37,8 +38,8 @@ use Illuminate\View\View;
*/ */
class CreateController extends Controller class CreateController extends Controller
{ {
private CategoryRepositoryInterface $repository;
private AttachmentHelperInterface $attachments; private AttachmentHelperInterface $attachments;
private CategoryRepositoryInterface $repository;
/** /**
* CategoryController constructor. * CategoryController constructor.
@@ -51,7 +52,7 @@ class CreateController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.categories')); app('view')->share('title', (string)trans('firefly.categories'));
app('view')->share('mainTitleIcon', 'fa-bookmark'); app('view')->share('mainTitleIcon', 'fa-bookmark');
$this->repository = app(CategoryRepositoryInterface::class); $this->repository = app(CategoryRepositoryInterface::class);
$this->attachments = app(AttachmentHelperInterface::class); $this->attachments = app(AttachmentHelperInterface::class);
@@ -60,6 +61,7 @@ class CreateController extends Controller
} }
); );
} }
/** /**
* Create category. * Create category.
* *
@@ -73,10 +75,11 @@ class CreateController extends Controller
$this->rememberPreviousUri('categories.create.uri'); $this->rememberPreviousUri('categories.create.uri');
} }
$request->session()->forget('categories.create.fromStore'); $request->session()->forget('categories.create.fromStore');
$subTitle = (string) trans('firefly.create_new_category'); $subTitle = (string)trans('firefly.create_new_category');
return prefixView('categories.create', compact('subTitle')); return prefixView('categories.create', compact('subTitle'));
} }
/** /**
* Store new category. * Store new category.
* *
@@ -89,7 +92,7 @@ class CreateController extends Controller
$data = $request->getCategoryData(); $data = $request->getCategoryData();
$category = $this->repository->store($data); $category = $this->repository->store($data);
$request->session()->flash('success', (string) trans('firefly.stored_category', ['name' => $category->name])); $request->session()->flash('success', (string)trans('firefly.stored_category', ['name' => $category->name]));
app('preferences')->mark(); app('preferences')->mark();
// store attachment(s): // store attachment(s):
@@ -98,7 +101,7 @@ class CreateController extends Controller
$this->attachments->saveAttachmentsForModel($category, $files); $this->attachments->saveAttachmentsForModel($category, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info', (string) trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -106,7 +109,7 @@ class CreateController extends Controller
} }
$redirect = redirect(route('categories.index')); $redirect = redirect(route('categories.index'));
if (1 === (int) $request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
$request->session()->put('categories.create.fromStore', true); $request->session()->put('categories.create.fromStore', true);

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Category; namespace FireflyIII\Http\Controllers\Category;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
@@ -50,7 +51,7 @@ class DeleteController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.categories')); app('view')->share('title', (string)trans('firefly.categories'));
app('view')->share('mainTitleIcon', 'fa-bookmark'); app('view')->share('mainTitleIcon', 'fa-bookmark');
$this->repository = app(CategoryRepositoryInterface::class); $this->repository = app(CategoryRepositoryInterface::class);
@@ -68,7 +69,7 @@ class DeleteController extends Controller
*/ */
public function delete(Category $category) public function delete(Category $category)
{ {
$subTitle = (string) trans('firefly.delete_category', ['name' => $category->name]); $subTitle = (string)trans('firefly.delete_category', ['name' => $category->name]);
// put previous url in session // put previous url in session
$this->rememberPreviousUri('categories.delete.uri'); $this->rememberPreviousUri('categories.delete.uri');
@@ -89,7 +90,7 @@ class DeleteController extends Controller
$name = $category->name; $name = $category->name;
$this->repository->destroy($category); $this->repository->destroy($category);
$request->session()->flash('success', (string) trans('firefly.deleted_category', ['name' => $name])); $request->session()->flash('success', (string)trans('firefly.deleted_category', ['name' => $name]));
app('preferences')->mark(); app('preferences')->mark();
return redirect($this->getPreviousUri('categories.delete.uri')); return redirect($this->getPreviousUri('categories.delete.uri'));

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Category; namespace FireflyIII\Http\Controllers\Category;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\CategoryFormRequest; use FireflyIII\Http\Requests\CategoryFormRequest;
@@ -39,8 +40,8 @@ use Illuminate\View\View;
class EditController extends Controller class EditController extends Controller
{ {
private CategoryRepositoryInterface $repository;
private AttachmentHelperInterface $attachments; private AttachmentHelperInterface $attachments;
private CategoryRepositoryInterface $repository;
/** /**
* CategoryController constructor. * CategoryController constructor.
@@ -62,6 +63,7 @@ class EditController extends Controller
} }
); );
} }
/** /**
* Edit a category. * Edit a category.
* *

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Category; namespace FireflyIII\Http\Controllers\Category;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
@@ -50,7 +51,7 @@ class IndexController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.categories')); app('view')->share('title', (string)trans('firefly.categories'));
app('view')->share('mainTitleIcon', 'fa-bookmark'); app('view')->share('mainTitleIcon', 'fa-bookmark');
$this->repository = app(CategoryRepositoryInterface::class); $this->repository = app(CategoryRepositoryInterface::class);
@@ -58,6 +59,7 @@ class IndexController extends Controller
} }
); );
} }
/** /**
* Show all categories. * Show all categories.
* *
@@ -67,8 +69,8 @@ class IndexController extends Controller
*/ */
public function index(Request $request) public function index(Request $request)
{ {
$page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$collection = $this->repository->getCategories(); $collection = $this->repository->getCategories();
$total = $collection->count(); $total = $collection->count();
$collection = $collection->slice(($page - 1) * $pageSize, $pageSize); $collection = $collection->slice(($page - 1) * $pageSize, $pageSize);

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Category; namespace FireflyIII\Http\Controllers\Category;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
@@ -41,6 +42,7 @@ use Log;
class NoCategoryController extends Controller class NoCategoryController extends Controller
{ {
use PeriodOverview; use PeriodOverview;
/** @var JournalRepositoryInterface Journals and transactions overview */ /** @var JournalRepositoryInterface Journals and transactions overview */
private $journalRepos; private $journalRepos;
@@ -56,7 +58,7 @@ class NoCategoryController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.categories')); app('view')->share('title', (string)trans('firefly.categories'));
app('view')->share('mainTitleIcon', 'fa-bookmark'); app('view')->share('mainTitleIcon', 'fa-bookmark');
$this->journalRepos = app(JournalRepositoryInterface::class); $this->journalRepos = app(JournalRepositoryInterface::class);
@@ -81,8 +83,8 @@ class NoCategoryController extends Controller
$start = $start ?? session('start'); $start = $start ?? session('start');
/** @var Carbon $end */ /** @var Carbon $end */
$end = $end ?? session('end'); $end = $end ?? session('end');
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$subTitle = trans( $subTitle = trans(
'firefly.without_category_between', 'firefly.without_category_between',
['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)] ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)]
@@ -103,6 +105,7 @@ class NoCategoryController extends Controller
return prefixView('categories.no-category', compact('groups', 'subTitle', 'periods', 'start', 'end')); return prefixView('categories.no-category', compact('groups', 'subTitle', 'periods', 'start', 'end'));
} }
/** /**
* Show all transactions without a category. * Show all transactions without a category.
* *
@@ -116,10 +119,10 @@ class NoCategoryController extends Controller
$start = null; $start = null;
$end = null; $end = null;
$periods = new Collection; $periods = new Collection;
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
Log::debug('Start of noCategory()'); Log::debug('Start of noCategory()');
$subTitle = (string) trans('firefly.all_journals_without_category'); $subTitle = (string)trans('firefly.all_journals_without_category');
$first = $this->journalRepos->firstNull(); $first = $this->journalRepos->firstNull();
$start = null === $first ? new Carbon : $first->date; $start = null === $first ? new Carbon : $first->date;
$end = today(config('app.timezone')); $end = today(config('app.timezone'));

View File

@@ -42,6 +42,7 @@ use Illuminate\View\View;
class ShowController extends Controller class ShowController extends Controller
{ {
use PeriodOverview; use PeriodOverview;
/** @var CategoryRepositoryInterface The category repository */ /** @var CategoryRepositoryInterface The category repository */
private $repository; private $repository;
@@ -57,7 +58,7 @@ class ShowController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.categories')); app('view')->share('title', (string)trans('firefly.categories'));
app('view')->share('mainTitleIcon', 'fa-bookmark'); app('view')->share('mainTitleIcon', 'fa-bookmark');
$this->repository = app(CategoryRepositoryInterface::class); $this->repository = app(CategoryRepositoryInterface::class);
@@ -65,6 +66,7 @@ class ShowController extends Controller
} }
); );
} }
/** /**
* Show a single category. * Show a single category.
* *
@@ -82,9 +84,9 @@ class ShowController extends Controller
/** @var Carbon $end */ /** @var Carbon $end */
$end = $end ?? session('end', Carbon::now()->endOfMonth()); $end = $end ?? session('end', Carbon::now()->endOfMonth());
$subTitleIcon = 'fa-bookmark'; $subTitleIcon = 'fa-bookmark';
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$attachments = $this->repository->getAttachments($category); $attachments = $this->repository->getAttachments($category);
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$oldest = $this->repository->firstUseDate($category) ?? Carbon::now()->startOfYear(); $oldest = $this->repository->firstUseDate($category) ?? Carbon::now()->startOfYear();
$periods = $this->getCategoryPeriodOverview($category, $oldest, $end); $periods = $this->getCategoryPeriodOverview($category, $oldest, $end);
$path = route('categories.show', [$category->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); $path = route('categories.show', [$category->id, $start->format('Y-m-d'), $end->format('Y-m-d')]);
@@ -103,7 +105,7 @@ class ShowController extends Controller
$groups = $collector->getPaginatedGroups(); $groups = $collector->getPaginatedGroups();
$groups->setPath($path); $groups->setPath($path);
return prefixView('categories.show', compact('category','attachments', 'groups', 'periods', 'subTitle', 'subTitleIcon', 'start', 'end')); return prefixView('categories.show', compact('category', 'attachments', 'groups', 'periods', 'subTitle', 'subTitleIcon', 'start', 'end'));
} }
/** /**
@@ -118,19 +120,19 @@ class ShowController extends Controller
{ {
// default values: // default values:
$subTitleIcon = 'fa-bookmark'; $subTitleIcon = 'fa-bookmark';
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$start = null; $start = null;
$end = null; $end = null;
$periods = new Collection; $periods = new Collection;
$subTitle = (string) trans('firefly.all_journals_for_category', ['name' => $category->name]); $subTitle = (string)trans('firefly.all_journals_for_category', ['name' => $category->name]);
$first = $this->repository->firstUseDate($category); $first = $this->repository->firstUseDate($category);
/** @var Carbon $start */ /** @var Carbon $start */
$start = $first ?? today(config('app.timezone')); $start = $first ?? today(config('app.timezone'));
$end = today(config('app.timezone')); $end = today(config('app.timezone'));
$path = route('categories.show.all', [$category->id]); $path = route('categories.show.all', [$category->id]);
$attachments = $this->repository->getAttachments($category); $attachments = $this->repository->getAttachments($category);
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
@@ -141,6 +143,6 @@ class ShowController extends Controller
$groups = $collector->getPaginatedGroups(); $groups = $collector->getPaginatedGroups();
$groups->setPath($path); $groups->setPath($path);
return prefixView('categories.show', compact('category','attachments', 'groups', 'periods', 'subTitle', 'subTitleIcon', 'start', 'end')); return prefixView('categories.show', compact('category', 'attachments', 'groups', 'periods', 'subTitle', 'subTitleIcon', 'start', 'end'));
} }
} }

View File

@@ -76,6 +76,7 @@ class AccountController extends Controller
} }
); );
} }
/** /**
* Shows the balances for all the user's expense accounts (on the front page). * Shows the balances for all the user's expense accounts (on the front page).
* *
@@ -113,10 +114,10 @@ class AccountController extends Controller
// loop the end balances. This is an array for each account ($expenses) // loop the end balances. This is an array for each account ($expenses)
foreach ($endBalances as $accountId => $expenses) { foreach ($endBalances as $accountId => $expenses) {
$accountId = (int) $accountId; $accountId = (int)$accountId;
// loop each expense entry (each entry can be a different currency). // loop each expense entry (each entry can be a different currency).
foreach ($expenses as $currencyId => $endAmount) { foreach ($expenses as $currencyId => $endAmount) {
$currencyId = (int) $currencyId; $currencyId = (int)$currencyId;
// see if there is an accompanying start amount. // see if there is an accompanying start amount.
// grab the difference and find the currency. // grab the difference and find the currency.
@@ -128,7 +129,7 @@ class AccountController extends Controller
$tempData[] = [ $tempData[] = [
'name' => $accountNames[$accountId], 'name' => $accountNames[$accountId],
'difference' => $diff, 'difference' => $diff,
'diff_float' => (float) $diff, 'diff_float' => (float)$diff,
'currency_id' => $currencyId, 'currency_id' => $currencyId,
]; ];
} }
@@ -147,7 +148,7 @@ class AccountController extends Controller
foreach ($currencies as $currencyId => $currency) { foreach ($currencies as $currencyId => $currency) {
$dataSet $dataSet
= [ = [
'label' => (string) trans('firefly.spent'), 'label' => (string)trans('firefly.spent'),
'type' => 'bar', 'type' => 'bar',
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
@@ -169,6 +170,22 @@ class AccountController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* Expenses per budget for all time, as shown on account overview.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
$end = Carbon::now();
return $this->expenseBudget($account, $start, $end);
}
/** /**
* Expenses per budget, as shown on account overview. * Expenses per budget, as shown on account overview.
* *
@@ -197,7 +214,7 @@ class AccountController extends Controller
$budgetIds = []; $budgetIds = [];
/** @var array $journal */ /** @var array $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
$budgetId = (int) $journal['budget_id']; $budgetId = (int)$journal['budget_id'];
$key = sprintf('%d-%d', $budgetId, $journal['currency_id']); $key = sprintf('%d-%d', $budgetId, $journal['currency_id']);
$budgetIds[] = $budgetId; $budgetIds[] = $budgetId;
if (!isset($result[$key])) { if (!isset($result[$key])) {
@@ -217,7 +234,7 @@ class AccountController extends Controller
foreach ($result as $row) { foreach ($result as $row) {
$budgetId = $row['budget_id']; $budgetId = $row['budget_id'];
$name = $names[$budgetId]; $name = $names[$budgetId];
$label = (string) trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]); $label = (string)trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
$chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']]; $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']];
} }
@@ -228,19 +245,19 @@ class AccountController extends Controller
} }
/** /**
* Expenses per budget for all time, as shown on account overview. * Expenses grouped by category for account.
* *
* @param AccountRepositoryInterface $repository * @param AccountRepositoryInterface $repository
* @param Account $account * @param Account $account
* *
* @return JsonResponse * @return JsonResponse
*/ */
public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{ {
$start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth(); $start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
$end = Carbon::now(); $end = Carbon::now();
return $this->expenseBudget($account, $start, $end); return $this->expenseCategory($account, $start, $end);
} }
/** /**
@@ -276,7 +293,7 @@ class AccountController extends Controller
if (!isset($result[$key])) { if (!isset($result[$key])) {
$result[$key] = [ $result[$key] = [
'total' => '0', 'total' => '0',
'category_id' => (int) $journal['category_id'], 'category_id' => (int)$journal['category_id'],
'currency_name' => $journal['currency_name'], 'currency_name' => $journal['currency_name'],
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
'currency_code' => $journal['currency_code'], 'currency_code' => $journal['currency_code'],
@@ -289,7 +306,7 @@ class AccountController extends Controller
foreach ($result as $row) { foreach ($result as $row) {
$categoryId = $row['category_id']; $categoryId = $row['category_id'];
$name = $names[$categoryId] ?? '(unknown)'; $name = $names[$categoryId] ?? '(unknown)';
$label = (string) trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]); $label = (string)trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
$chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']]; $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']];
} }
@@ -299,22 +316,6 @@ class AccountController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* Expenses grouped by category for account.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
$end = Carbon::now();
return $this->expenseCategory($account, $start, $end);
}
/** /**
* Shows the balances for all the user's frontpage accounts. * Shows the balances for all the user's frontpage accounts.
* *
@@ -339,6 +340,22 @@ class AccountController extends Controller
return response()->json($this->accountBalanceChart($accounts, $start, $end)); return response()->json($this->accountBalanceChart($accounts, $start, $end));
} }
/**
* Shows the income grouped by category for an account, in all time.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
$end = Carbon::now();
return $this->incomeCategory($account, $start, $end);
}
/** /**
* Shows all income per account for each category. * Shows all income per account for each category.
* *
@@ -376,7 +393,7 @@ class AccountController extends Controller
'category_id' => $journal['category_id'], 'category_id' => $journal['category_id'],
'currency_name' => $journal['currency_name'], 'currency_name' => $journal['currency_name'],
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
'currency_code' => $journal['currency_code'], 'currency_code' => $journal['currency_code'],
]; ];
} }
$result[$key]['total'] = bcadd($journal['amount'], $result[$key]['total']); $result[$key]['total'] = bcadd($journal['amount'], $result[$key]['total']);
@@ -386,7 +403,7 @@ class AccountController extends Controller
foreach ($result as $row) { foreach ($result as $row) {
$categoryId = $row['category_id']; $categoryId = $row['category_id'];
$name = $names[$categoryId] ?? '(unknown)'; $name = $names[$categoryId] ?? '(unknown)';
$label = (string) trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]); $label = (string)trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
$chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']]; $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']];
} }
$data = $this->generator->multiCurrencyPieChart($chartData); $data = $this->generator->multiCurrencyPieChart($chartData);
@@ -395,22 +412,6 @@ class AccountController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* Shows the income grouped by category for an account, in all time.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
$end = Carbon::now();
return $this->incomeCategory($account, $start, $end);
}
/** /**
* Shows overview of account during a single period. * Shows overview of account during a single period.
* *
@@ -450,6 +451,61 @@ class AccountController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* @param Carbon $start
* @param Carbon $end
* @param Account $account
* @param TransactionCurrency $currency
*
* @return array
*/
private function periodByCurrency(Carbon $start, Carbon $end, Account $account, TransactionCurrency $currency): array
{
$locale = app('steam')->getLocale();
$step = $this->calculateStep($start, $end);
$result = [
'label' => sprintf('%s (%s)', $account->name, $currency->symbol),
'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code,
'entries' => [],
];
$entries = [];
$current = clone $start;
switch ($step) {
default:
break;
case '1D':
// per day the entire period, balance for every day.
$format = (string)trans('config.month_and_day', [], $locale);
$range = app('steam')->balanceInRange($account, $start, $end, $currency);
$previous = array_values($range)[0];
while ($end >= $current) {
$theDate = $current->format('Y-m-d');
$balance = $range[$theDate] ?? $previous;
$label = $current->formatLocalized($format);
$entries[$label] = (float)$balance;
$previous = $balance;
$current->addDay();
}
break;
// @codeCoverageIgnoreStart
case '1W':
case '1M':
case '1Y':
while ($end >= $current) {
$balance = (float)app('steam')->balance($account, $current, $currency);
$label = app('navigation')->periodShow($current, $step);
$entries[$label] = $balance;
$current = app('navigation')->addPeriod($current, $step, 0);
}
break;
// @codeCoverageIgnoreEnd
}
$result['entries'] = $entries;
return $result;
}
/** /**
* Shows the balances for a given set of dates and accounts. * Shows the balances for a given set of dates and accounts.
* *
@@ -465,6 +521,7 @@ class AccountController extends Controller
{ {
return response()->json($this->accountBalanceChart($accounts, $start, $end)); return response()->json($this->accountBalanceChart($accounts, $start, $end));
} }
/** /**
* Shows the balances for all the user's revenue accounts. * Shows the balances for all the user's revenue accounts.
* *
@@ -502,10 +559,10 @@ class AccountController extends Controller
// loop the end balances. This is an array for each account ($expenses) // loop the end balances. This is an array for each account ($expenses)
foreach ($endBalances as $accountId => $expenses) { foreach ($endBalances as $accountId => $expenses) {
$accountId = (int) $accountId; $accountId = (int)$accountId;
// loop each expense entry (each entry can be a different currency). // loop each expense entry (each entry can be a different currency).
foreach ($expenses as $currencyId => $endAmount) { foreach ($expenses as $currencyId => $endAmount) {
$currencyId = (int) $currencyId; $currencyId = (int)$currencyId;
// see if there is an accompanying start amount. // see if there is an accompanying start amount.
// grab the difference and find the currency. // grab the difference and find the currency.
@@ -517,7 +574,7 @@ class AccountController extends Controller
$tempData[] = [ $tempData[] = [
'name' => $accountNames[$accountId], 'name' => $accountNames[$accountId],
'difference' => $diff, 'difference' => $diff,
'diff_float' => (float) $diff, 'diff_float' => (float)$diff,
'currency_id' => $currencyId, 'currency_id' => $currencyId,
]; ];
} }
@@ -536,7 +593,7 @@ class AccountController extends Controller
foreach ($currencies as $currencyId => $currency) { foreach ($currencies as $currencyId => $currency) {
$dataSet $dataSet
= [ = [
'label' => (string) trans('firefly.earned'), 'label' => (string)trans('firefly.earned'),
'type' => 'bar', 'type' => 'bar',
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
@@ -557,59 +614,4 @@ class AccountController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* @param Carbon $start
* @param Carbon $end
* @param Account $account
* @param TransactionCurrency $currency
*
* @return array
*/
private function periodByCurrency(Carbon $start, Carbon $end, Account $account, TransactionCurrency $currency): array
{
$locale = app('steam')->getLocale();
$step = $this->calculateStep($start, $end);
$result = [
'label' => sprintf('%s (%s)', $account->name, $currency->symbol),
'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code,
'entries' => [],
];
$entries = [];
$current = clone $start;
switch ($step) {
default:
break;
case '1D':
// per day the entire period, balance for every day.
$format = (string) trans('config.month_and_day', [], $locale);
$range = app('steam')->balanceInRange($account, $start, $end, $currency);
$previous = array_values($range)[0];
while ($end >= $current) {
$theDate = $current->format('Y-m-d');
$balance = $range[$theDate] ?? $previous;
$label = $current->formatLocalized($format);
$entries[$label] = (float) $balance;
$previous = $balance;
$current->addDay();
}
break;
// @codeCoverageIgnoreStart
case '1W':
case '1M':
case '1Y':
while ($end >= $current) {
$balance = (float) app('steam')->balance($account, $current, $currency);
$label = app('navigation')->periodShow($current, $step);
$entries[$label] = $balance;
$current = app('navigation')->addPeriod($current, $step, 0);
}
break;
// @codeCoverageIgnoreEnd
}
$result['entries'] = $entries;
return $result;
}
} }

View File

@@ -50,6 +50,7 @@ class BillController extends Controller
parent::__construct(); parent::__construct();
$this->generator = app(GeneratorInterface::class); $this->generator = app(GeneratorInterface::class);
} }
/** /**
* Shows all bills and whether or not they've been paid this month (pie chart). * Shows all bills and whether or not they've been paid this month (pie chart).
* *
@@ -78,13 +79,15 @@ class BillController extends Controller
foreach ($paid as $currencyId => $amount) { foreach ($paid as $currencyId => $amount) {
$currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull($currencyId); $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull($currencyId);
$label = (string) trans('firefly.paid_in_currency', ['currency' => $currencies[$currencyId]->name]); $label = (string)trans('firefly.paid_in_currency', ['currency' => $currencies[$currencyId]->name]);
$chartData[$label] = ['amount' => $amount, 'currency_symbol' => $currencies[$currencyId]->symbol, 'currency_code' => $currencies[$currencyId]->code]; $chartData[$label] = ['amount' => $amount, 'currency_symbol' => $currencies[$currencyId]->symbol,
'currency_code' => $currencies[$currencyId]->code];
} }
foreach ($unpaid as $currencyId => $amount) { foreach ($unpaid as $currencyId => $amount) {
$currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull($currencyId); $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull($currencyId);
$label = (string) trans('firefly.unpaid_in_currency', ['currency' => $currencies[$currencyId]->name]); $label = (string)trans('firefly.unpaid_in_currency', ['currency' => $currencies[$currencyId]->name]);
$chartData[$label] = ['amount' => $amount, 'currency_symbol' => $currencies[$currencyId]->symbol, 'currency_code' => $currencies[$currencyId]->code]; $chartData[$label] = ['amount' => $amount, 'currency_symbol' => $currencies[$currencyId]->symbol,
'currency_code' => $currencies[$currencyId]->code];
} }
$data = $this->generator->multiCurrencyPieChart($chartData); $data = $this->generator->multiCurrencyPieChart($chartData);
@@ -92,6 +95,7 @@ class BillController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* Shows overview for a single bill. * Shows overview for a single bill.
* *
@@ -105,7 +109,7 @@ class BillController extends Controller
$cache->addProperty('chart.bill.single'); $cache->addProperty('chart.bill.single');
$cache->addProperty($bill->id); $cache->addProperty($bill->id);
if ($cache->has()) { if ($cache->has()) {
return response()->json($cache->get()); // @codeCoverageIgnore return response()->json($cache->get()); // @codeCoverageIgnore
} }
$locale = app('steam')->getLocale(); $locale = app('steam')->getLocale();
@@ -117,24 +121,28 @@ class BillController extends Controller
usort( usort(
$journals, $journals,
static function (array $left, array $right) { static function (array $left, array $right) {
if($left['date']->gt($right['date'])) { if ($left['date']->gt($right['date'])) {
return 1; return 1;
} }
if($left['date']->lt($right['date'])) { if ($left['date']->lt($right['date'])) {
return -1; return -1;
} }
return 0; return 0;
} }
); );
$chartData = [ $chartData = [
['type' => 'line', 'label' => (string) trans('firefly.min-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'currency_code' => $bill->transactionCurrency->code, 'entries' => []], ['type' => 'line', 'label' => (string)trans('firefly.min-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol,
['type' => 'line', 'label' => (string) trans('firefly.max-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'currency_code' => $bill->transactionCurrency->code, 'entries' => []], 'currency_code' => $bill->transactionCurrency->code, 'entries' => []],
['type' => 'bar', 'label' => (string) trans('firefly.journal-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'currency_code' => $bill->transactionCurrency->code, 'entries' => []], ['type' => 'line', 'label' => (string)trans('firefly.max-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol,
'currency_code' => $bill->transactionCurrency->code, 'entries' => []],
['type' => 'bar', 'label' => (string)trans('firefly.journal-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol,
'currency_code' => $bill->transactionCurrency->code, 'entries' => []],
]; ];
foreach ($journals as $journal) { foreach ($journals as $journal) {
$date = $journal['date']->formatLocalized((string) trans('config.month_and_day', [], $locale)); $date = $journal['date']->formatLocalized((string)trans('config.month_and_day', [], $locale));
$chartData[0]['entries'][$date] = $bill->amount_min; // minimum amount of bill $chartData[0]['entries'][$date] = $bill->amount_min; // minimum amount of bill
$chartData[1]['entries'][$date] = $bill->amount_max; // maximum amount of bill $chartData[1]['entries'][$date] = $bill->amount_max; // maximum amount of bill

View File

@@ -77,6 +77,7 @@ class BudgetController extends Controller
} }
); );
} }
/** /**
* Shows overview of a single budget. * Shows overview of a single budget.
* *
@@ -141,6 +142,7 @@ class BudgetController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* Shows the amount left in a specific budget limit. * Shows the amount left in a specific budget limit.
* *
@@ -167,7 +169,7 @@ class BudgetController extends Controller
$cache->addProperty($budget->id); $cache->addProperty($budget->id);
if ($cache->has()) { if ($cache->has()) {
return response()->json($cache->get()); // @codeCoverageIgnore return response()->json($cache->get()); // @codeCoverageIgnore
} }
$locale = app('steam')->getLocale(); $locale = app('steam')->getLocale();
$entries = []; $entries = [];
@@ -192,6 +194,7 @@ class BudgetController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* Shows how much is spent per asset account. * Shows how much is spent per asset account.
* *
@@ -259,6 +262,7 @@ class BudgetController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* Shows how much is spent per category. * Shows how much is spent per category.
* *
@@ -322,6 +326,7 @@ class BudgetController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* Shows how much is spent per expense account. * Shows how much is spent per expense account.
* *
@@ -388,6 +393,7 @@ class BudgetController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* Shows a budget list with spent/left/overspent. * Shows a budget list with spent/left/overspent.
* *
@@ -419,6 +425,7 @@ class BudgetController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* Shows a budget overview chart (spent and budgeted). * Shows a budget overview chart (spent and budgeted).
* *
@@ -477,13 +484,13 @@ class BudgetController extends Controller
// get budget limit in this period for this currency. // get budget limit in this period for this currency.
$limit = $this->blRepository->find($budget, $currency, $currentStart, $currentEnd); $limit = $this->blRepository->find($budget, $currency, $currentStart, $currentEnd);
if (null !== $limit) { if (null !== $limit) {
$chartData[1]['entries'][$title] = round((float) $limit->amount, $currency->decimal_places); $chartData[1]['entries'][$title] = round((float)$limit->amount, $currency->decimal_places);
} }
// get spent amount in this period for this currency. // get spent amount in this period for this currency.
$sum = $this->opsRepository->sumExpenses($currentStart, $currentEnd, $accounts, new Collection([$budget]), $currency); $sum = $this->opsRepository->sumExpenses($currentStart, $currentEnd, $accounts, new Collection([$budget]), $currency);
$amount = app('steam')->positive($sum[$currency->id]['sum'] ?? '0'); $amount = app('steam')->positive($sum[$currency->id]['sum'] ?? '0');
$chartData[0]['entries'][$title] = round((float) $amount, $currency->decimal_places); $chartData[0]['entries'][$title] = round((float)$amount, $currency->decimal_places);
$currentStart = clone $currentEnd; $currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay(); $currentStart->addDay()->startOfDay();
@@ -494,6 +501,7 @@ class BudgetController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* Shows a chart for transactions without a budget. * Shows a chart for transactions without a budget.
* *
@@ -527,7 +535,7 @@ class BudgetController extends Controller
$title = $currentStart->formatLocalized($titleFormat); $title = $currentStart->formatLocalized($titleFormat);
$sum = $this->nbRepository->sumExpenses($currentStart, $currentEnd, $accounts, $currency); $sum = $this->nbRepository->sumExpenses($currentStart, $currentEnd, $accounts, $currency);
$amount = app('steam')->positive($sum[$currency->id]['sum'] ?? '0'); $amount = app('steam')->positive($sum[$currency->id]['sum'] ?? '0');
$chartData[$title] = round((float) $amount, $currency->decimal_places); $chartData[$title] = round((float)$amount, $currency->decimal_places);
$currentStart = app('navigation')->addPeriod($currentStart, $preferredRange, 0); $currentStart = app('navigation')->addPeriod($currentStart, $preferredRange, 0);
} }

View File

@@ -42,6 +42,7 @@ use Illuminate\Support\Collection;
class BudgetReportController extends Controller class BudgetReportController extends Controller
{ {
use AugumentData, TransactionCalculation; use AugumentData, TransactionCalculation;
/** @var GeneratorInterface Chart generation methods. */ /** @var GeneratorInterface Chart generation methods. */
private $generator; private $generator;
@@ -199,7 +200,7 @@ class BudgetReportController extends Controller
$chartData[$spentKey] = $chartData[$spentKey] ?? [ $chartData[$spentKey] = $chartData[$spentKey] ?? [
'label' => sprintf( 'label' => sprintf(
'%s (%s)', '%s (%s)',
(string) trans('firefly.spent_in_specific_budget', ['budget' => $budget->name]), (string)trans('firefly.spent_in_specific_budget', ['budget' => $budget->name]),
$currency['currency_name'] $currency['currency_name']
), ),
'type' => 'bar', 'type' => 'bar',
@@ -224,6 +225,29 @@ class BudgetReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->formatLocalized($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
/** /**
* Chart that groups expenses by the account. * Chart that groups expenses by the account.
* *
@@ -260,27 +284,4 @@ class BudgetReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->formatLocalized($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
} }

View File

@@ -60,6 +60,7 @@ class CategoryController extends Controller
// create chart generator: // create chart generator:
$this->generator = app(GeneratorInterface::class); $this->generator = app(GeneratorInterface::class);
} }
/** /**
* Show an overview for a category for all time, per month/week/year. * Show an overview for a category for all time, per month/week/year.
* TODO test method, for category refactor. * TODO test method, for category refactor.
@@ -92,6 +93,22 @@ class CategoryController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* @return Carbon
*/
private function getDate(): Carbon
{
$carbon = null;
try {
$carbon = today(config('app.timezone'));
} catch (Exception $e) {
$e->getMessage();
}
return $carbon;
}
/** /**
* Shows the category chart on the front page. * Shows the category chart on the front page.
* TODO test method, for category refactor. * TODO test method, for category refactor.
@@ -112,8 +129,8 @@ class CategoryController extends Controller
} }
$frontPageGenerator = new FrontpageChartGenerator($start, $end); $frontPageGenerator = new FrontpageChartGenerator($start, $end);
$chartData = $frontPageGenerator->generate(); $chartData = $frontPageGenerator->generate();
$data = $this->generator->multiSet($chartData); $data = $this->generator->multiSet($chartData);
$cache->store($data); $cache->store($data);
return response()->json($data); return response()->json($data);
@@ -147,6 +164,94 @@ class CategoryController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* Generate report chart for either with or without category.
*
* @param Collection $accounts
* @param Carbon $start
* @param Carbon $end
* @param Category $category
*
* @return array
*/
private function reportPeriodChart(Collection $accounts, Carbon $start, Carbon $end, ?Category $category): array
{
$income = [];
$expenses = [];
$categoryId = 0;
if (null === $category) {
/** @var NoCategoryRepositoryInterface $noCatRepository */
$noCatRepository = app(NoCategoryRepositoryInterface::class);
// this gives us all currencies
$expenses = $noCatRepository->listExpenses($start, $end, $accounts);
$income = $noCatRepository->listIncome($start, $end, $accounts);
}
if (null !== $category) {
/** @var OperationsRepositoryInterface $opsRepository */
$opsRepository = app(OperationsRepositoryInterface::class);
$categoryId = (int)$category->id;
// this gives us all currencies
$collection = new Collection([$category]);
$expenses = $opsRepository->listExpenses($start, $end, null, $collection);
$income = $opsRepository->listIncome($start, $end, null, $collection);
}
$currencies = array_unique(array_merge(array_keys($income), array_keys($expenses)));
$periods = app('navigation')->listOfPeriods($start, $end);
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$chartData = [];
// make empty data array:
// double foreach (bad) to make empty array:
foreach ($currencies as $currencyId) {
$currencyInfo = $expenses[$currencyId] ?? $income[$currencyId];
$outKey = sprintf('%d-out', $currencyId);
$inKey = sprintf('%d-in', $currencyId);
$chartData[$outKey]
= [
'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currencyInfo['currency_name']),
'entries' => [],
'type' => 'bar',
'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
];
$chartData[$inKey]
= [
'label' => sprintf('%s (%s)', (string)trans('firefly.earned'), $currencyInfo['currency_name']),
'entries' => [],
'type' => 'bar',
'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
];
// loop empty periods:
foreach (array_keys($periods) as $period) {
$label = $periods[$period];
$chartData[$outKey]['entries'][$label] = '0';
$chartData[$inKey]['entries'][$label] = '0';
}
// loop income and expenses for this category.:
$outSet = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
foreach ($outSet['transaction_journals'] as $journal) {
$amount = app('steam')->positive($journal['amount']);
$date = $journal['date']->formatLocalized($format);
$chartData[$outKey]['entries'][$date] = $chartData[$outKey]['entries'][$date] ?? '0';
$chartData[$outKey]['entries'][$date] = bcadd($amount, $chartData[$outKey]['entries'][$date]);
}
$inSet = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
foreach ($inSet['transaction_journals'] as $journal) {
$amount = app('steam')->positive($journal['amount']);
$date = $journal['date']->formatLocalized($format);
$chartData[$inKey]['entries'][$date] = $chartData[$inKey]['entries'][$date] ?? '0';
$chartData[$inKey]['entries'][$date] = bcadd($amount, $chartData[$inKey]['entries'][$date]);
}
}
return $this->generator->multiSet($chartData);
}
/** /**
* Chart for period for transactions without a category. * Chart for period for transactions without a category.
* TODO test me. * TODO test me.
@@ -210,106 +315,4 @@ class CategoryController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* @return Carbon
*/
private function getDate(): Carbon
{
$carbon = null;
try {
$carbon = today(config('app.timezone'));
} catch (Exception $e) {
$e->getMessage();
}
return $carbon;
}
/**
* Generate report chart for either with or without category.
*
* @param Collection $accounts
* @param Carbon $start
* @param Carbon $end
* @param Category $category
*
* @return array
*/
private function reportPeriodChart(Collection $accounts, Carbon $start, Carbon $end, ?Category $category): array
{
$income = [];
$expenses = [];
$categoryId = 0;
if (null === $category) {
/** @var NoCategoryRepositoryInterface $noCatRepository */
$noCatRepository = app(NoCategoryRepositoryInterface::class);
// this gives us all currencies
$expenses = $noCatRepository->listExpenses($start, $end, $accounts);
$income = $noCatRepository->listIncome($start, $end, $accounts);
}
if (null !== $category) {
/** @var OperationsRepositoryInterface $opsRepository */
$opsRepository = app(OperationsRepositoryInterface::class);
$categoryId = (int) $category->id;
// this gives us all currencies
$collection = new Collection([$category]);
$expenses = $opsRepository->listExpenses($start, $end, null, $collection);
$income = $opsRepository->listIncome($start, $end, null, $collection);
}
$currencies = array_unique(array_merge(array_keys($income), array_keys($expenses)));
$periods = app('navigation')->listOfPeriods($start, $end);
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$chartData = [];
// make empty data array:
// double foreach (bad) to make empty array:
foreach ($currencies as $currencyId) {
$currencyInfo = $expenses[$currencyId] ?? $income[$currencyId];
$outKey = sprintf('%d-out', $currencyId);
$inKey = sprintf('%d-in', $currencyId);
$chartData[$outKey]
= [
'label' => sprintf('%s (%s)', (string) trans('firefly.spent'), $currencyInfo['currency_name']),
'entries' => [],
'type' => 'bar',
'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
];
$chartData[$inKey]
= [
'label' => sprintf('%s (%s)', (string) trans('firefly.earned'), $currencyInfo['currency_name']),
'entries' => [],
'type' => 'bar',
'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
];
// loop empty periods:
foreach (array_keys($periods) as $period) {
$label = $periods[$period];
$chartData[$outKey]['entries'][$label] = '0';
$chartData[$inKey]['entries'][$label] = '0';
}
// loop income and expenses for this category.:
$outSet = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
foreach ($outSet['transaction_journals'] as $journal) {
$amount = app('steam')->positive($journal['amount']);
$date = $journal['date']->formatLocalized($format);
$chartData[$outKey]['entries'][$date] = $chartData[$outKey]['entries'][$date] ?? '0';
$chartData[$outKey]['entries'][$date] = bcadd($amount, $chartData[$outKey]['entries'][$date]);
}
$inSet = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
foreach ($inSet['transaction_journals'] as $journal) {
$amount = app('steam')->positive($journal['amount']);
$date = $journal['date']->formatLocalized($format);
$chartData[$inKey]['entries'][$date] = $chartData[$inKey]['entries'][$date] ?? '0';
$chartData[$inKey]['entries'][$date] = bcadd($amount, $chartData[$inKey]['entries'][$date]);
}
}
return $this->generator->multiSet($chartData);
}
} }

View File

@@ -267,7 +267,7 @@ class CategoryReportController extends Controller
$chartData[$spentKey] = $chartData[$spentKey] ?? [ $chartData[$spentKey] = $chartData[$spentKey] ?? [
'label' => sprintf( 'label' => sprintf(
'%s (%s)', '%s (%s)',
(string) trans('firefly.spent_in_specific_category', ['category' => $category->name]), (string)trans('firefly.spent_in_specific_category', ['category' => $category->name]),
$currency['currency_name'] $currency['currency_name']
), ),
'type' => 'bar', 'type' => 'bar',
@@ -294,7 +294,7 @@ class CategoryReportController extends Controller
$chartData[$spentKey] = $chartData[$spentKey] ?? [ $chartData[$spentKey] = $chartData[$spentKey] ?? [
'label' => sprintf( 'label' => sprintf(
'%s (%s)', '%s (%s)',
(string) trans('firefly.earned_in_specific_category', ['category' => $category->name]), (string)trans('firefly.earned_in_specific_category', ['category' => $category->name]),
$currency['currency_name'] $currency['currency_name']
), ),
'type' => 'bar', 'type' => 'bar',
@@ -319,6 +319,31 @@ class CategoryReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->formatLocalized($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
/** /**
* @param Collection $accounts * @param Collection $accounts
* @param Collection $categories * @param Collection $categories
@@ -390,29 +415,4 @@ class CategoryReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->formatLocalized($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
} }

View File

@@ -199,7 +199,7 @@ class DoubleReportController extends Controller
$chartData[$spentKey] = $chartData[$spentKey] ?? [ $chartData[$spentKey] = $chartData[$spentKey] ?? [
'label' => sprintf( 'label' => sprintf(
'%s (%s)', '%s (%s)',
(string) trans('firefly.spent_in_specific_double', ['account' => $name]), (string)trans('firefly.spent_in_specific_double', ['account' => $name]),
$currency['currency_name'] $currency['currency_name']
), ),
'type' => 'bar', 'type' => 'bar',
@@ -225,7 +225,7 @@ class DoubleReportController extends Controller
$chartData[$earnedKey] = $chartData[$earnedKey] ?? [ $chartData[$earnedKey] = $chartData[$earnedKey] ?? [
'label' => sprintf( 'label' => sprintf(
'%s (%s)', '%s (%s)',
(string) trans('firefly.earned_in_specific_double', ['account' => $name]), (string)trans('firefly.earned_in_specific_double', ['account' => $name]),
$currency['currency_name'] $currency['currency_name']
), ),
'type' => 'bar', 'type' => 'bar',
@@ -247,6 +247,57 @@ class DoubleReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* TODO this method is double.
*
* @param Collection $accounts
* @param int $id
* @param string $name
* @param null|string $iban
*
* @return string
*/
private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
{
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name && $account->id !== $id) {
return $account->name;
}
if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
return $account->iban;
}
}
return $name;
}
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->formatLocalized($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
/** /**
* @param Collection $accounts * @param Collection $accounts
* @param Collection $others * @param Collection $others
@@ -366,54 +417,4 @@ class DoubleReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* TODO this method is double.
*
* @param Collection $accounts
* @param int $id
* @param string $name
* @param null|string $iban
*
* @return string
*/
private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
{
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name && $account->id !== $id) {
return $account->name;
}
if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
return $account->iban;
}
}
return $name;
}
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->formatLocalized($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
} }

View File

@@ -42,6 +42,7 @@ use Illuminate\Support\Collection;
class ExpenseReportController extends Controller class ExpenseReportController extends Controller
{ {
use AugumentData, TransactionCalculation; use AugumentData, TransactionCalculation;
/** @var AccountRepositoryInterface The account repository */ /** @var AccountRepositoryInterface The account repository */
protected $accountRepository; protected $accountRepository;
/** @var GeneratorInterface Chart generation methods. */ /** @var GeneratorInterface Chart generation methods. */
@@ -64,6 +65,7 @@ class ExpenseReportController extends Controller
} }
); );
} }
/** /**
* Main chart that shows income and expense for a combination of expense/revenue accounts. * Main chart that shows income and expense for a combination of expense/revenue accounts.
* *
@@ -110,27 +112,27 @@ class ExpenseReportController extends Controller
/** @var Account $exp */ /** @var Account $exp */
$exp = $combination->first(); $exp = $combination->first();
$chartData[$exp->id . '-in'] = [ $chartData[$exp->id . '-in'] = [
'label' => sprintf('%s (%s)', $name, (string) trans('firefly.income')), 'label' => sprintf('%s (%s)', $name, (string)trans('firefly.income')),
'type' => 'bar', 'type' => 'bar',
'yAxisID' => 'y-axis-0', 'yAxisID' => 'y-axis-0',
'entries' => [], 'entries' => [],
]; ];
$chartData[$exp->id . '-out'] = [ $chartData[$exp->id . '-out'] = [
'label' => sprintf('%s (%s)', $name, (string) trans('firefly.expenses')), 'label' => sprintf('%s (%s)', $name, (string)trans('firefly.expenses')),
'type' => 'bar', 'type' => 'bar',
'yAxisID' => 'y-axis-0', 'yAxisID' => 'y-axis-0',
'entries' => [], 'entries' => [],
]; ];
// total in, total out: // total in, total out:
$chartData[$exp->id . '-total-in'] = [ $chartData[$exp->id . '-total-in'] = [
'label' => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_income')), 'label' => sprintf('%s (%s)', $name, (string)trans('firefly.sum_of_income')),
'type' => 'line', 'type' => 'line',
'fill' => false, 'fill' => false,
'yAxisID' => 'y-axis-1', 'yAxisID' => 'y-axis-1',
'entries' => [], 'entries' => [],
]; ];
$chartData[$exp->id . '-total-out'] = [ $chartData[$exp->id . '-total-out'] = [
'label' => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_expenses')), 'label' => sprintf('%s (%s)', $name, (string)trans('firefly.sum_of_expenses')),
'type' => 'line', 'type' => 'line',
'fill' => false, 'fill' => false,
'yAxisID' => 'y-axis-1', 'yAxisID' => 'y-axis-1',

View File

@@ -39,6 +39,7 @@ use Illuminate\Support\Collection;
class PiggyBankController extends Controller class PiggyBankController extends Controller
{ {
use DateCalculation; use DateCalculation;
/** @var GeneratorInterface Chart generation methods. */ /** @var GeneratorInterface Chart generation methods. */
protected $generator; protected $generator;
@@ -74,9 +75,9 @@ class PiggyBankController extends Controller
if ($cache->has()) { if ($cache->has()) {
return response()->json($cache->get()); // @codeCoverageIgnore return response()->json($cache->get()); // @codeCoverageIgnore
} }
$set = $repository->getEvents($piggyBank); $set = $repository->getEvents($piggyBank);
$set = $set->reverse(); $set = $set->reverse();
$locale =app('steam')->getLocale(); $locale = app('steam')->getLocale();
// get first event or start date of piggy bank or today // get first event or start date of piggy bank or today
$startDate = $piggyBank->start_date ?? today(config('app.timezone')); $startDate = $piggyBank->start_date ?? today(config('app.timezone'));
@@ -100,7 +101,7 @@ class PiggyBankController extends Controller
} }
); );
$currentSum = $filtered->sum('amount'); $currentSum = $filtered->sum('amount');
$label = $oldest->formatLocalized((string) trans('config.month_and_day', [], $locale)); $label = $oldest->formatLocalized((string)trans('config.month_and_day', [], $locale));
$chartData[$label] = $currentSum; $chartData[$label] = $currentSum;
$oldest = app('navigation')->addPeriod($oldest, $step, 0); $oldest = app('navigation')->addPeriod($oldest, $step, 0);
} }
@@ -111,7 +112,7 @@ class PiggyBankController extends Controller
} }
); );
$finalSum = $finalFiltered->sum('amount'); $finalSum = $finalFiltered->sum('amount');
$finalLabel = $today->formatLocalized((string) trans('config.month_and_day', [], $locale)); $finalLabel = $today->formatLocalized((string)trans('config.month_and_day', [], $locale));
$chartData[$finalLabel] = $finalSum; $chartData[$finalLabel] = $finalSum;
$data = $this->generator->singleSet($piggyBank->name, $chartData); $data = $this->generator->singleSet($piggyBank->name, $chartData);

View File

@@ -43,6 +43,7 @@ use Log;
class ReportController extends Controller class ReportController extends Controller
{ {
use BasicDataSupport, ChartGeneration; use BasicDataSupport, ChartGeneration;
/** @var GeneratorInterface Chart generation methods. */ /** @var GeneratorInterface Chart generation methods. */
protected $generator; protected $generator;
@@ -79,7 +80,7 @@ class ReportController extends Controller
if ($cache->has()) { if ($cache->has()) {
return response()->json($cache->get()); // @codeCoverageIgnore return response()->json($cache->get()); // @codeCoverageIgnore
} }
$locale = app('steam')->getLocale(); $locale = app('steam')->getLocale();
$current = clone $start; $current = clone $start;
$chartData = []; $chartData = [];
/** @var NetWorthInterface $helper */ /** @var NetWorthInterface $helper */
@@ -111,13 +112,13 @@ class ReportController extends Controller
/** @var array $netWorthItem */ /** @var array $netWorthItem */
foreach ($result as $netWorthItem) { foreach ($result as $netWorthItem) {
$currencyId = $netWorthItem['currency']->id; $currencyId = $netWorthItem['currency']->id;
$label = $current->formatLocalized((string) trans('config.month_and_day', [], $locale)); $label = $current->formatLocalized((string)trans('config.month_and_day', [], $locale));
if (!isset($chartData[$currencyId])) { if (!isset($chartData[$currencyId])) {
$chartData[$currencyId] = [ $chartData[$currencyId] = [
'label' => 'Net worth in ' . $netWorthItem['currency']->name, 'label' => 'Net worth in ' . $netWorthItem['currency']->name,
'type' => 'line', 'type' => 'line',
'currency_symbol' => $netWorthItem['currency']->symbol, 'currency_symbol' => $netWorthItem['currency']->symbol,
'currency_code' => $netWorthItem['currency']->code, 'currency_code' => $netWorthItem['currency']->code,
'entries' => [], 'entries' => [],
]; ];
} }
@@ -175,13 +176,13 @@ class ReportController extends Controller
/** @var array $journal */ /** @var array $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
$period = $journal['date']->format($format); $period = $journal['date']->format($format);
$currencyId = (int) $journal['currency_id']; $currencyId = (int)$journal['currency_id'];
$data[$currencyId] = $data[$currencyId] ?? [ $data[$currencyId] = $data[$currencyId] ?? [
'currency_id' => $currencyId, 'currency_id' => $currencyId,
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
'currency_code' => $journal['currency_code'], 'currency_code' => $journal['currency_code'],
'currency_name' => $journal['currency_name'], 'currency_name' => $journal['currency_name'],
'currency_decimal_places' => (int) $journal['currency_decimal_places'], 'currency_decimal_places' => (int)$journal['currency_decimal_places'],
]; ];
$data[$currencyId][$period] = $data[$currencyId][$period] ?? [ $data[$currencyId][$period] = $data[$currencyId][$period] ?? [
'period' => $period, 'period' => $period,
@@ -213,7 +214,7 @@ class ReportController extends Controller
/** @var array $currency */ /** @var array $currency */
foreach ($data as $currency) { foreach ($data as $currency) {
$income = [ $income = [
'label' => (string) trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]),
'type' => 'bar', 'type' => 'bar',
'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
'currency_id' => $currency['currency_id'], 'currency_id' => $currency['currency_id'],
@@ -222,7 +223,7 @@ class ReportController extends Controller
'entries' => [], 'entries' => [],
]; ];
$expense = [ $expense = [
'label' => (string) trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]),
'type' => 'bar', 'type' => 'bar',
'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
'currency_id' => $currency['currency_id'], 'currency_id' => $currency['currency_id'],
@@ -236,8 +237,8 @@ class ReportController extends Controller
while ($currentStart <= $end) { while ($currentStart <= $end) {
$key = $currentStart->format($format); $key = $currentStart->format($format);
$title = $currentStart->formatLocalized($titleFormat); $title = $currentStart->formatLocalized($titleFormat);
$income['entries'][$title] = round((float) ($currency[$key]['earned'] ?? '0'), $currency['currency_decimal_places']); $income['entries'][$title] = round((float)($currency[$key]['earned'] ?? '0'), $currency['currency_decimal_places']);
$expense['entries'][$title] = round((float) ($currency[$key]['spent'] ?? '0'), $currency['currency_decimal_places']); $expense['entries'][$title] = round((float)($currency[$key]['spent'] ?? '0'), $currency['currency_decimal_places']);
$currentStart = app('navigation')->addPeriod($currentStart, $preferredRange, 0); $currentStart = app('navigation')->addPeriod($currentStart, $preferredRange, 0);
} }

View File

@@ -38,6 +38,7 @@ use Illuminate\Support\Collection;
class TagReportController extends Controller class TagReportController extends Controller
{ {
use AugumentData, TransactionCalculation; use AugumentData, TransactionCalculation;
/** @var GeneratorInterface Chart generation methods. */ /** @var GeneratorInterface Chart generation methods. */
protected $generator; protected $generator;
@@ -171,6 +172,7 @@ class TagReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* @param Collection $accounts * @param Collection $accounts
* @param Collection $tags * @param Collection $tags
@@ -268,7 +270,7 @@ class TagReportController extends Controller
$chartData[$spentKey] = $chartData[$spentKey] ?? [ $chartData[$spentKey] = $chartData[$spentKey] ?? [
'label' => sprintf( 'label' => sprintf(
'%s (%s)', '%s (%s)',
(string) trans('firefly.spent_in_specific_tag', ['tag' => $tag->tag]), (string)trans('firefly.spent_in_specific_tag', ['tag' => $tag->tag]),
$currency['currency_name'] $currency['currency_name']
), ),
'type' => 'bar', 'type' => 'bar',
@@ -295,7 +297,7 @@ class TagReportController extends Controller
$chartData[$spentKey] = $chartData[$spentKey] ?? [ $chartData[$spentKey] = $chartData[$spentKey] ?? [
'label' => sprintf( 'label' => sprintf(
'%s (%s)', '%s (%s)',
(string) trans('firefly.earned_in_specific_tag', ['tag' => $tag->tag]), (string)trans('firefly.earned_in_specific_tag', ['tag' => $tag->tag]),
$currency['currency_name'] $currency['currency_name']
), ),
'type' => 'bar', 'type' => 'bar',
@@ -320,6 +322,31 @@ class TagReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->formatLocalized($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
/** /**
* @param Collection $accounts * @param Collection $accounts
* @param Collection $tags * @param Collection $tags
@@ -425,6 +452,7 @@ class TagReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/** /**
* @param Collection $accounts * @param Collection $accounts
* @param Collection $tags * @param Collection $tags
@@ -458,28 +486,4 @@ class TagReportController extends Controller
return response()->json($data); return response()->json($data);
} }
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->formatLocalized($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
} }

View File

@@ -56,8 +56,8 @@ class TransactionController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return JsonResponse * @return JsonResponse
* @throws FireflyException
*/ */
public function budgets(Carbon $start, Carbon $end) public function budgets(Carbon $start, Carbon $end)
{ {
@@ -80,8 +80,8 @@ class TransactionController extends Controller
// group by category. // group by category.
/** @var array $journal */ /** @var array $journal */
foreach ($result as $journal) { foreach ($result as $journal) {
$budget = $journal['budget_name'] ?? (string) trans('firefly.no_budget'); $budget = $journal['budget_name'] ?? (string)trans('firefly.no_budget');
$title = sprintf('%s (%s)', $budget, $journal['currency_symbol']); $title = sprintf('%s (%s)', $budget, $journal['currency_symbol']);
$data[$title] = $data[$title] ?? [ $data[$title] = $data[$title] ?? [
'amount' => '0', 'amount' => '0',
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
@@ -100,8 +100,8 @@ class TransactionController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return JsonResponse * @return JsonResponse
* @throws FireflyException
*/ */
public function categories(string $objectType, Carbon $start, Carbon $end) public function categories(string $objectType, Carbon $start, Carbon $end)
{ {
@@ -137,8 +137,8 @@ class TransactionController extends Controller
// group by category. // group by category.
/** @var array $journal */ /** @var array $journal */
foreach ($result as $journal) { foreach ($result as $journal) {
$category = $journal['category_name'] ?? (string) trans('firefly.no_category'); $category = $journal['category_name'] ?? (string)trans('firefly.no_category');
$title = sprintf('%s (%s)', $category, $journal['currency_symbol']); $title = sprintf('%s (%s)', $category, $journal['currency_symbol']);
$data[$title] = $data[$title] ?? [ $data[$title] = $data[$title] ?? [
'amount' => '0', 'amount' => '0',
'currency_symbol' => $journal['currency_symbol'], 'currency_symbol' => $journal['currency_symbol'],
@@ -158,8 +158,8 @@ class TransactionController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return JsonResponse * @return JsonResponse
* @throws FireflyException
*/ */
public function destinationAccounts(string $objectType, Carbon $start, Carbon $end) public function destinationAccounts(string $objectType, Carbon $start, Carbon $end)
{ {
@@ -215,8 +215,8 @@ class TransactionController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return JsonResponse * @return JsonResponse
* @throws FireflyException
*/ */
public function sourceAccounts(string $objectType, Carbon $start, Carbon $end) public function sourceAccounts(string $objectType, Carbon $start, Carbon $end)
{ {

View File

@@ -27,13 +27,16 @@ use Artisan;
use Carbon\Carbon; use Carbon\Carbon;
use DB; use DB;
use Exception; use Exception;
use FireflyConfig;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Middleware\IsDemoUser; use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Support\Http\Controllers\GetConfigurationData; use FireflyIII\Support\Http\Controllers\GetConfigurationData;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Routing\Redirector; use Illuminate\Routing\Redirector;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
use Illuminate\View\View;
use Log; use Log;
use Monolog\Handler\RotatingFileHandler; use Monolog\Handler\RotatingFileHandler;
use Route as RouteFacade; use Route as RouteFacade;
@@ -113,7 +116,7 @@ class DebugController extends Controller
* *
* @param Request $request * @param Request $request
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Factory|View
* *
*/ */
public function index(Request $request) public function index(Request $request)
@@ -132,7 +135,7 @@ class DebugController extends Controller
$userAgent = $request->header('user-agent'); $userAgent = $request->header('user-agent');
$trustedProxies = config('firefly.trusted_proxies'); $trustedProxies = config('firefly.trusted_proxies');
$displayErrors = ini_get('display_errors'); $displayErrors = ini_get('display_errors');
$errorReporting = $this->errorReporting((int) ini_get('error_reporting')); $errorReporting = $this->errorReporting((int)ini_get('error_reporting'));
$appEnv = config('app.env'); $appEnv = config('app.env');
$appDebug = var_export(config('app.debug'), true); $appDebug = var_export(config('app.debug'), true);
$logChannel = config('logging.default'); $logChannel = config('logging.default');
@@ -144,12 +147,12 @@ class DebugController extends Controller
// expected + found DB version: // expected + found DB version:
$expectedDBversion = config('firefly.db_version'); $expectedDBversion = config('firefly.db_version');
$foundDBversion = \FireflyConfig::get('db_version',1)->data; $foundDBversion = FireflyConfig::get('db_version', 1)->data;
// some new vars. // some new vars.
$telemetry = true === config('firefly.send_telemetry') && true === config('firefly.feature_flags.telemetry'); $telemetry = true === config('firefly.send_telemetry') && true === config('firefly.feature_flags.telemetry');
$defaultLanguage = (string) config('firefly.default_language'); $defaultLanguage = (string)config('firefly.default_language');
$defaultLocale = (string) config('firefly.default_locale'); $defaultLocale = (string)config('firefly.default_locale');
$userLanguage = app('steam')->getLanguage(); $userLanguage = app('steam')->getLanguage();
$userLocale = app('steam')->getLocale(); $userLocale = app('steam')->getLocale();
$isDocker = env('IS_DOCKER', false); $isDocker = env('IS_DOCKER', false);
@@ -248,7 +251,7 @@ class DebugController extends Controller
$return = '&nbsp;'; $return = '&nbsp;';
/** @var Route $route */ /** @var Route $route */
foreach ($set as $route) { foreach ($set as $route) {
$name = (string) $route->getName(); $name = (string)$route->getName();
if (in_array('GET', $route->methods(), true)) { if (in_array('GET', $route->methods(), true)) {
$found = false; $found = false;
foreach ($ignore as $string) { foreach ($ignore as $string) {

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Export; namespace FireflyIII\Http\Controllers\Export;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Middleware\IsDemoUser; use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
@@ -53,7 +54,7 @@ class IndexController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-life-bouy'); app('view')->share('mainTitleIcon', 'fa-life-bouy');
app('view')->share('title', (string) trans('firefly.export_data_title')); app('view')->share('title', (string)trans('firefly.export_data_title'));
$this->journalRepository = app(JournalRepositoryInterface::class); $this->journalRepository = app(JournalRepositoryInterface::class);
$this->middleware(IsDemoUser::class)->except(['index']); $this->middleware(IsDemoUser::class)->except(['index']);
@@ -63,8 +64,8 @@ class IndexController extends Controller
} }
/** /**
* @throws CannotInsertRecord
* @return LaravelResponse * @return LaravelResponse
* @throws CannotInsertRecord
*/ */
public function export(): LaravelResponse public function export(): LaravelResponse
{ {

View File

@@ -96,6 +96,7 @@ class HomeController extends Controller
return response()->json(['ok' => 'ok']); return response()->json(['ok' => 'ok']);
} }
/** /**
* Show index. * Show index.
* *

View File

@@ -76,6 +76,7 @@ class AutoCompleteController extends Controller
// give another key for consistency // give another key for consistency
$array[$index]['name'] = sprintf('#%d: %s', $item['transaction_group_id'], $item['description']); $array[$index]['name'] = sprintf('#%d: %s', $item['transaction_group_id'], $item['description']);
} }
return response()->json($array); return response()->json($array);
} }

View File

@@ -125,6 +125,7 @@ class BoxController extends Controller
return response()->json($return); return response()->json($return);
} }
/** /**
* Current total balance. * Current total balance.
* *
@@ -250,7 +251,7 @@ class BoxController extends Controller
); );
$netWorthSet = $netWorthHelper->getNetWorthByCurrency($filtered, $date); $netWorthSet = $netWorthHelper->getNetWorthByCurrency($filtered, $date);
$return = []; $return = [];
foreach ($netWorthSet as $data) { foreach ($netWorthSet as $data) {
/** @var TransactionCurrency $currency */ /** @var TransactionCurrency $currency */
$currency = $data['currency']; $currency = $data['currency'];

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Json; namespace FireflyIII\Http\Controllers\Json;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;

View File

@@ -177,6 +177,7 @@ class RecurrenceController extends Controller
]; ];
} }
Log::debug('Dropdown is', $result); Log::debug('Dropdown is', $result);
return response()->json($result); return response()->json($result);
} }
} }

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Json; namespace FireflyIII\Http\Controllers\Json;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -87,6 +88,7 @@ class RuleController extends Controller
Log::error(sprintf('Cannot render rules.partials.trigger: %s', $e->getMessage())); Log::error(sprintf('Cannot render rules.partials.trigger: %s', $e->getMessage()));
$view = 'Could not render view.'; $view = 'Could not render view.';
} }
return response()->json(['html' => $view]); return response()->json(['html' => $view]);
} }

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\ObjectGroup; namespace FireflyIII\Http\Controllers\ObjectGroup;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\ObjectGroup;
use FireflyIII\Repositories\ObjectGroup\ObjectGroupRepositoryInterface; use FireflyIII\Repositories\ObjectGroup\ObjectGroupRepositoryInterface;
@@ -47,7 +48,7 @@ class DeleteController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-envelope-o'); app('view')->share('mainTitleIcon', 'fa-envelope-o');
app('view')->share('title', (string) trans('firefly.object_groups_page_title')); app('view')->share('title', (string)trans('firefly.object_groups_page_title'));
$this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository = app(ObjectGroupRepositoryInterface::class);
@@ -63,7 +64,7 @@ class DeleteController extends Controller
*/ */
public function delete(ObjectGroup $objectGroup) public function delete(ObjectGroup $objectGroup)
{ {
$subTitle = (string) trans('firefly.delete_object_group', ['title' => $objectGroup->title]); $subTitle = (string)trans('firefly.delete_object_group', ['title' => $objectGroup->title]);
$piggyBanks = $objectGroup->piggyBanks()->count(); $piggyBanks = $objectGroup->piggyBanks()->count();
// put previous url in session // put previous url in session
@@ -79,7 +80,7 @@ class DeleteController extends Controller
*/ */
public function destroy(ObjectGroup $objectGroup): RedirectResponse public function destroy(ObjectGroup $objectGroup): RedirectResponse
{ {
session()->flash('success', (string) trans('firefly.deleted_object_group', ['title' => $objectGroup->title])); session()->flash('success', (string)trans('firefly.deleted_object_group', ['title' => $objectGroup->title]));
app('preferences')->mark(); app('preferences')->mark();
$this->repository->destroy($objectGroup); $this->repository->destroy($objectGroup);

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\ObjectGroup; namespace FireflyIII\Http\Controllers\ObjectGroup;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\ObjectGroupFormRequest; use FireflyIII\Http\Requests\ObjectGroupFormRequest;
use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\ObjectGroup;
@@ -47,7 +48,7 @@ class EditController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-envelope-o'); app('view')->share('mainTitleIcon', 'fa-envelope-o');
app('view')->share('title', (string) trans('firefly.object_groups_page_title')); app('view')->share('title', (string)trans('firefly.object_groups_page_title'));
$this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository = app(ObjectGroupRepositoryInterface::class);
@@ -63,7 +64,7 @@ class EditController extends Controller
*/ */
public function edit(ObjectGroup $objectGroup) public function edit(ObjectGroup $objectGroup)
{ {
$subTitle = (string) trans('firefly.edit_object_group', ['title' => $objectGroup->title]); $subTitle = (string)trans('firefly.edit_object_group', ['title' => $objectGroup->title]);
$subTitleIcon = 'fa-pencil'; $subTitleIcon = 'fa-pencil';
if (true !== session('object-groups.edit.fromUpdate')) { if (true !== session('object-groups.edit.fromUpdate')) {
@@ -73,23 +74,24 @@ class EditController extends Controller
return prefixView('object-groups.edit', compact('subTitle', 'subTitleIcon', 'objectGroup')); return prefixView('object-groups.edit', compact('subTitle', 'subTitleIcon', 'objectGroup'));
} }
/** /**
* Update a piggy bank. * Update a piggy bank.
* *
* @param ObjectGroupFormRequest $request * @param ObjectGroupFormRequest $request
* @param ObjectGroup $objectGroup * @param ObjectGroup $objectGroup
*/ */
public function update(ObjectGroupFormRequest $request, ObjectGroup $objectGroup) public function update(ObjectGroupFormRequest $request, ObjectGroup $objectGroup)
{ {
$data = $request->getObjectGroupData(); $data = $request->getObjectGroupData();
$piggyBank = $this->repository->update($objectGroup, $data); $piggyBank = $this->repository->update($objectGroup, $data);
session()->flash('success', (string) trans('firefly.updated_object_group', ['title' => $objectGroup->title])); session()->flash('success', (string)trans('firefly.updated_object_group', ['title' => $objectGroup->title]));
app('preferences')->mark(); app('preferences')->mark();
$redirect = redirect($this->getPreviousUri('object-groups.edit.uri')); $redirect = redirect($this->getPreviousUri('object-groups.edit.uri'));
if (1 === (int) $request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
session()->put('object-groups.edit.fromUpdate', true); session()->put('object-groups.edit.fromUpdate', true);

View File

@@ -23,10 +23,14 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\ObjectGroup; namespace FireflyIII\Http\Controllers\ObjectGroup;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\ObjectGroup;
use FireflyIII\Repositories\ObjectGroup\ObjectGroupRepositoryInterface; use FireflyIII\Repositories\ObjectGroup\ObjectGroupRepositoryInterface;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\View\View;
use Log; use Log;
/** /**
@@ -49,7 +53,7 @@ class IndexController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-envelope-o'); app('view')->share('mainTitleIcon', 'fa-envelope-o');
app('view')->share('title', (string) trans('firefly.object_groups_page_title')); app('view')->share('title', (string)trans('firefly.object_groups_page_title'));
$this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository = app(ObjectGroupRepositoryInterface::class);
return $next($request); return $next($request);
@@ -58,13 +62,13 @@ class IndexController extends Controller
} }
/** /**
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Application|Factory|View
*/ */
public function index() public function index()
{ {
$this->repository->deleteEmpty(); $this->repository->deleteEmpty();
$this->repository->resetOrder(); $this->repository->resetOrder();
$subTitle = (string) trans('firefly.object_groups_index'); $subTitle = (string)trans('firefly.object_groups_index');
$objectGroups = $this->repository->get(); $objectGroups = $this->repository->get();
return prefixView('object-groups.index', compact('subTitle', 'objectGroups')); return prefixView('object-groups.index', compact('subTitle', 'objectGroups'));
@@ -76,7 +80,7 @@ class IndexController extends Controller
public function setOrder(Request $request, ObjectGroup $objectGroup) public function setOrder(Request $request, ObjectGroup $objectGroup)
{ {
Log::debug(sprintf('Found object group #%d "%s"', $objectGroup->id, $objectGroup->title)); Log::debug(sprintf('Found object group #%d "%s"', $objectGroup->id, $objectGroup->title));
$newOrder = (int) $request->get('order'); $newOrder = (int)$request->get('order');
$this->repository->setOrder($objectGroup, $newOrder); $this->repository->setOrder($objectGroup, $newOrder);
return response()->json([]); return response()->json([]);

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\PiggyBank; namespace FireflyIII\Http\Controllers\PiggyBank;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
@@ -54,7 +55,7 @@ class AmountController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.piggyBanks')); app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye'); app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->piggyRepos = app(PiggyBankRepositoryInterface::class); $this->piggyRepos = app(PiggyBankRepositoryInterface::class);
@@ -124,7 +125,7 @@ class AmountController extends Controller
$this->piggyRepos->createEvent($piggyBank, $amount); $this->piggyRepos->createEvent($piggyBank, $amount);
session()->flash( session()->flash(
'success', 'success',
(string) trans( (string)trans(
'firefly.added_amount_to_piggy', 'firefly.added_amount_to_piggy',
['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name] ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name]
) )
@@ -137,7 +138,7 @@ class AmountController extends Controller
Log::error('Cannot add ' . $amount . ' because canAddAmount returned false.'); Log::error('Cannot add ' . $amount . ' because canAddAmount returned false.');
session()->flash( session()->flash(
'error', 'error',
(string) trans( (string)trans(
'firefly.cannot_add_amount_piggy', 'firefly.cannot_add_amount_piggy',
['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => e($piggyBank->name)] ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => e($piggyBank->name)]
) )
@@ -166,7 +167,7 @@ class AmountController extends Controller
$this->piggyRepos->removeAmount($piggyBank, $amount); $this->piggyRepos->removeAmount($piggyBank, $amount);
session()->flash( session()->flash(
'success', 'success',
(string) trans( (string)trans(
'firefly.removed_amount_from_piggy', 'firefly.removed_amount_from_piggy',
['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name] ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name]
) )
@@ -175,11 +176,11 @@ class AmountController extends Controller
return redirect(route('piggy-banks.index')); return redirect(route('piggy-banks.index'));
} }
$amount = number_format((float) $request->get('amount'), 12, '.', ''); $amount = number_format((float)$request->get('amount'), 12, '.', '');
session()->flash( session()->flash(
'error', 'error',
(string) trans( (string)trans(
'firefly.cannot_remove_from_piggy', 'firefly.cannot_remove_from_piggy',
['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => e($piggyBank->name)] ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => e($piggyBank->name)]
) )

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\PiggyBank; namespace FireflyIII\Http\Controllers\PiggyBank;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\PiggyBankStoreRequest; use FireflyIII\Http\Requests\PiggyBankStoreRequest;
@@ -51,7 +52,7 @@ class CreateController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.piggyBanks')); app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye'); app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->attachments = app(AttachmentHelperInterface::class); $this->attachments = app(AttachmentHelperInterface::class);
@@ -69,7 +70,7 @@ class CreateController extends Controller
*/ */
public function create() public function create()
{ {
$subTitle = (string) trans('firefly.new_piggy_bank'); $subTitle = (string)trans('firefly.new_piggy_bank');
$subTitleIcon = 'fa-plus'; $subTitleIcon = 'fa-plus';
// put previous url in session if not redirect from store (not "create another"). // put previous url in session if not redirect from store (not "create another").
@@ -80,6 +81,7 @@ class CreateController extends Controller
return prefixView('piggy-banks.create', compact('subTitle', 'subTitleIcon')); return prefixView('piggy-banks.create', compact('subTitle', 'subTitleIcon'));
} }
/** /**
* Store a new piggy bank. * Store a new piggy bank.
* *
@@ -95,7 +97,7 @@ class CreateController extends Controller
} }
$piggyBank = $this->piggyRepos->store($data); $piggyBank = $this->piggyRepos->store($data);
session()->flash('success', (string) trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name])); session()->flash('success', (string)trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name]));
app('preferences')->mark(); app('preferences')->mark();
// store attachment(s): // store attachment(s):
@@ -105,7 +107,7 @@ class CreateController extends Controller
$this->attachments->saveAttachmentsForModel($piggyBank, $files); $this->attachments->saveAttachmentsForModel($piggyBank, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info', (string) trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -113,7 +115,7 @@ class CreateController extends Controller
} }
$redirect = redirect($this->getPreviousUri('piggy-banks.create.uri')); $redirect = redirect($this->getPreviousUri('piggy-banks.create.uri'));
if (1 === (int) $request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
session()->put('piggy-banks.create.fromStore', true); session()->put('piggy-banks.create.fromStore', true);

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\PiggyBank; namespace FireflyIII\Http\Controllers\PiggyBank;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
@@ -49,7 +50,7 @@ class DeleteController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.piggyBanks')); app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye'); app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->piggyRepos = app(PiggyBankRepositoryInterface::class); $this->piggyRepos = app(PiggyBankRepositoryInterface::class);
@@ -68,7 +69,7 @@ class DeleteController extends Controller
*/ */
public function delete(PiggyBank $piggyBank) public function delete(PiggyBank $piggyBank)
{ {
$subTitle = (string) trans('firefly.delete_piggy_bank', ['name' => $piggyBank->name]); $subTitle = (string)trans('firefly.delete_piggy_bank', ['name' => $piggyBank->name]);
// put previous url in session // put previous url in session
$this->rememberPreviousUri('piggy-banks.delete.uri'); $this->rememberPreviousUri('piggy-banks.delete.uri');
@@ -85,7 +86,7 @@ class DeleteController extends Controller
*/ */
public function destroy(PiggyBank $piggyBank): RedirectResponse public function destroy(PiggyBank $piggyBank): RedirectResponse
{ {
session()->flash('success', (string) trans('firefly.deleted_piggy_bank', ['name' => $piggyBank->name])); session()->flash('success', (string)trans('firefly.deleted_piggy_bank', ['name' => $piggyBank->name]));
app('preferences')->mark(); app('preferences')->mark();
$this->piggyRepos->destroy($piggyBank); $this->piggyRepos->destroy($piggyBank);

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\PiggyBank; namespace FireflyIII\Http\Controllers\PiggyBank;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\PiggyBankUpdateRequest; use FireflyIII\Http\Requests\PiggyBankUpdateRequest;
@@ -52,7 +53,7 @@ class EditController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.piggyBanks')); app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye'); app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->attachments = app(AttachmentHelperInterface::class); $this->attachments = app(AttachmentHelperInterface::class);
@@ -72,7 +73,7 @@ class EditController extends Controller
*/ */
public function edit(PiggyBank $piggyBank) public function edit(PiggyBank $piggyBank)
{ {
$subTitle = (string) trans('firefly.update_piggy_title', ['name' => $piggyBank->name]); $subTitle = (string)trans('firefly.update_piggy_title', ['name' => $piggyBank->name]);
$subTitleIcon = 'fa-pencil'; $subTitleIcon = 'fa-pencil';
$targetDate = null; $targetDate = null;
$startDate = null; $startDate = null;
@@ -103,11 +104,12 @@ class EditController extends Controller
return prefixView('piggy-banks.edit', compact('subTitle', 'subTitleIcon', 'piggyBank', 'preFilled')); return prefixView('piggy-banks.edit', compact('subTitle', 'subTitleIcon', 'piggyBank', 'preFilled'));
} }
/** /**
* Update a piggy bank. * Update a piggy bank.
* *
* @param PiggyBankUpdateRequest $request * @param PiggyBankUpdateRequest $request
* @param PiggyBank $piggyBank * @param PiggyBank $piggyBank
* *
* @return RedirectResponse|Redirector * @return RedirectResponse|Redirector
*/ */
@@ -116,7 +118,7 @@ class EditController extends Controller
$data = $request->getPiggyBankData(); $data = $request->getPiggyBankData();
$piggyBank = $this->piggyRepos->update($piggyBank, $data); $piggyBank = $this->piggyRepos->update($piggyBank, $data);
session()->flash('success', (string) trans('firefly.updated_piggy_bank', ['name' => $piggyBank->name])); session()->flash('success', (string)trans('firefly.updated_piggy_bank', ['name' => $piggyBank->name]));
app('preferences')->mark(); app('preferences')->mark();
// store new attachment(s): // store new attachment(s):
@@ -126,7 +128,7 @@ class EditController extends Controller
$this->attachments->saveAttachmentsForModel($piggyBank, $files); $this->attachments->saveAttachmentsForModel($piggyBank, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info', (string) trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -134,7 +136,7 @@ class EditController extends Controller
} }
$redirect = redirect($this->getPreviousUri('piggy-banks.edit.uri')); $redirect = redirect($this->getPreviousUri('piggy-banks.edit.uri'));
if (1 === (int) $request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
session()->put('piggy-banks.edit.fromUpdate', true); session()->put('piggy-banks.edit.fromUpdate', true);

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\PiggyBank; namespace FireflyIII\Http\Controllers\PiggyBank;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
@@ -42,6 +43,7 @@ use Symfony\Component\HttpFoundation\ParameterBag;
class IndexController extends Controller class IndexController extends Controller
{ {
use OrganisesObjectGroups; use OrganisesObjectGroups;
private PiggyBankRepositoryInterface $piggyRepos; private PiggyBankRepositoryInterface $piggyRepos;
/** /**
@@ -55,7 +57,7 @@ class IndexController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.piggyBanks')); app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye'); app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->piggyRepos = app(PiggyBankRepositoryInterface::class); $this->piggyRepos = app(PiggyBankRepositoryInterface::class);
@@ -99,7 +101,7 @@ class IndexController extends Controller
/** @var PiggyBank $piggy */ /** @var PiggyBank $piggy */
foreach ($collection as $piggy) { foreach ($collection as $piggy) {
$array = $transformer->transform($piggy); $array = $transformer->transform($piggy);
$groupOrder = (int) $array['object_group_order']; $groupOrder = (int)$array['object_group_order'];
// make group array if necessary: // make group array if necessary:
$piggyBanks[$groupOrder] = $piggyBanks[$groupOrder] ?? [ $piggyBanks[$groupOrder] = $piggyBanks[$groupOrder] ?? [
'object_group_id' => $array['object_group_id'] ?? 0, 'object_group_id' => $array['object_group_id'] ?? 0,
@@ -108,7 +110,7 @@ class IndexController extends Controller
]; ];
$account = $accountTransformer->transform($piggy->account); $account = $accountTransformer->transform($piggy->account);
$accountId = (int) $account['id']; $accountId = (int)$account['id'];
$array['attachments'] = $this->piggyRepos->getAttachments($piggy); $array['attachments'] = $this->piggyRepos->getAttachments($piggy);
if (!isset($accounts[$accountId])) { if (!isset($accounts[$accountId])) {
// create new: // create new:
@@ -163,10 +165,10 @@ class IndexController extends Controller
// current_amount // current_amount
// left_to_save // left_to_save
// save_per_month // save_per_month
$sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string) $piggy['target_amount']); $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string)$piggy['target_amount']);
$sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string) $piggy['current_amount']); $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string)$piggy['current_amount']);
$sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string) $piggy['left_to_save']); $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string)$piggy['left_to_save']);
$sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string) $piggy['save_per_month']); $sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string)$piggy['save_per_month']);
} }
} }
foreach ($piggyBanks as $groupOrder => $group) { foreach ($piggyBanks as $groupOrder => $group) {
@@ -187,8 +189,8 @@ class IndexController extends Controller
*/ */
public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse
{ {
$objectGroupTitle = (string) $request->get('objectGroupTitle'); $objectGroupTitle = (string)$request->get('objectGroupTitle');
$newOrder = (int) $request->get('order'); $newOrder = (int)$request->get('order');
$this->piggyRepos->setOrder($piggyBank, $newOrder); $this->piggyRepos->setOrder($piggyBank, $newOrder);
if ('' !== $objectGroupTitle) { if ('' !== $objectGroupTitle) {
$this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle); $this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle);

View File

@@ -23,6 +23,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\PiggyBank; namespace FireflyIII\Http\Controllers\PiggyBank;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
@@ -50,7 +51,7 @@ class ShowController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.piggyBanks')); app('view')->share('title', (string)trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye'); app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->piggyRepos = app(PiggyBankRepositoryInterface::class); $this->piggyRepos = app(PiggyBankRepositoryInterface::class);

View File

@@ -44,9 +44,9 @@ use Illuminate\View\View;
*/ */
class CreateController extends Controller class CreateController extends Controller
{ {
private AttachmentHelperInterface $attachments;
private BudgetRepositoryInterface $budgetRepos; private BudgetRepositoryInterface $budgetRepos;
private RecurringRepositoryInterface $recurring; private RecurringRepositoryInterface $recurring;
private AttachmentHelperInterface $attachments;
/** /**
* CreateController constructor. * CreateController constructor.
@@ -61,8 +61,8 @@ class CreateController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-paint-brush'); app('view')->share('mainTitleIcon', 'fa-paint-brush');
app('view')->share('title', (string) trans('firefly.recurrences')); app('view')->share('title', (string)trans('firefly.recurrences'));
app('view')->share('subTitle', (string) trans('firefly.create_new_recurrence')); app('view')->share('subTitle', (string)trans('firefly.create_new_recurrence'));
$this->recurring = app(RecurringRepositoryInterface::class); $this->recurring = app(RecurringRepositoryInterface::class);
$this->budgetRepos = app(BudgetRepositoryInterface::class); $this->budgetRepos = app(BudgetRepositoryInterface::class);
@@ -73,6 +73,52 @@ class CreateController extends Controller
); );
} }
/**
* Create a new recurring transaction.
*
* @param Request $request
*
* @return Factory|View
*/
public function create(Request $request)
{
$budgets = app('expandedform')->makeSelectListWithEmpty($this->budgetRepos->getActiveBudgets());
$defaultCurrency = app('amount')->getDefaultCurrency();
$tomorrow = today(config('app.timezone'));
$oldRepetitionType = $request->old('repetition_type');
$tomorrow->addDay();
// put previous url in session if not redirect from store (not "create another").
if (true !== session('recurring.create.fromStore')) {
$this->rememberPreviousUri('recurring.create.uri');
}
$request->session()->forget('recurring.create.fromStore');
$repetitionEnds = [
'forever' => (string)trans('firefly.repeat_forever'),
'until_date' => (string)trans('firefly.repeat_until_date'),
'times' => (string)trans('firefly.repeat_times'),
];
$weekendResponses = [
RecurrenceRepetition::WEEKEND_DO_NOTHING => (string)trans('firefly.do_nothing'),
RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string)trans('firefly.skip_transaction'),
RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string)trans('firefly.jump_to_friday'),
RecurrenceRepetition::WEEKEND_TO_MONDAY => (string)trans('firefly.jump_to_monday'),
];
$hasOldInput = null !== $request->old('_token'); // flash some data
$preFilled = [
'first_date' => $tomorrow->format('Y-m-d'),
'transaction_type' => $hasOldInput ? $request->old('transaction_type') : 'withdrawal',
'active' => $hasOldInput ? (bool)$request->old('active') : true,
'apply_rules' => $hasOldInput ? (bool)$request->old('apply_rules') : true,
];
$request->session()->flash('preFilled', $preFilled);
return prefixView(
'recurring.create',
compact('tomorrow', 'oldRepetitionType', 'weekendResponses', 'preFilled', 'repetitionEnds', 'defaultCurrency', 'budgets')
);
}
/** /**
* @param Request $request * @param Request $request
* @param TransactionJournal $journal * @param TransactionJournal $journal
@@ -91,15 +137,15 @@ class CreateController extends Controller
} }
$request->session()->forget('recurring.create.fromStore'); $request->session()->forget('recurring.create.fromStore');
$repetitionEnds = [ $repetitionEnds = [
'forever' => (string) trans('firefly.repeat_forever'), 'forever' => (string)trans('firefly.repeat_forever'),
'until_date' => (string) trans('firefly.repeat_until_date'), 'until_date' => (string)trans('firefly.repeat_until_date'),
'times' => (string) trans('firefly.repeat_times'), 'times' => (string)trans('firefly.repeat_times'),
]; ];
$weekendResponses = [ $weekendResponses = [
RecurrenceRepetition::WEEKEND_DO_NOTHING => (string) trans('firefly.do_nothing'), RecurrenceRepetition::WEEKEND_DO_NOTHING => (string)trans('firefly.do_nothing'),
RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string) trans('firefly.skip_transaction'), RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string)trans('firefly.skip_transaction'),
RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string) trans('firefly.jump_to_friday'), RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string)trans('firefly.jump_to_friday'),
RecurrenceRepetition::WEEKEND_TO_MONDAY => (string) trans('firefly.jump_to_monday'), RecurrenceRepetition::WEEKEND_TO_MONDAY => (string)trans('firefly.jump_to_monday'),
]; ];
/** @var Transaction $source */ /** @var Transaction $source */
@@ -130,8 +176,8 @@ class CreateController extends Controller
'transaction_type' => $request->old('transaction_type'), 'transaction_type' => $request->old('transaction_type'),
'category' => $request->old('category'), 'category' => $request->old('category'),
'budget_id' => $request->old('budget_id'), 'budget_id' => $request->old('budget_id'),
'active' => (bool) $request->old('active'), 'active' => (bool)$request->old('active'),
'apply_rules' => (bool) $request->old('apply_rules'), 'apply_rules' => (bool)$request->old('apply_rules'),
]; ];
} }
if (false === $hasOldInput) { if (false === $hasOldInput) {
@@ -162,51 +208,6 @@ class CreateController extends Controller
); );
} }
/**
* Create a new recurring transaction.
*
* @param Request $request
*
* @return Factory|View
*/
public function create(Request $request)
{
$budgets = app('expandedform')->makeSelectListWithEmpty($this->budgetRepos->getActiveBudgets());
$defaultCurrency = app('amount')->getDefaultCurrency();
$tomorrow = today(config('app.timezone'));
$oldRepetitionType = $request->old('repetition_type');
$tomorrow->addDay();
// put previous url in session if not redirect from store (not "create another").
if (true !== session('recurring.create.fromStore')) {
$this->rememberPreviousUri('recurring.create.uri');
}
$request->session()->forget('recurring.create.fromStore');
$repetitionEnds = [
'forever' => (string) trans('firefly.repeat_forever'),
'until_date' => (string) trans('firefly.repeat_until_date'),
'times' => (string) trans('firefly.repeat_times'),
];
$weekendResponses = [
RecurrenceRepetition::WEEKEND_DO_NOTHING => (string) trans('firefly.do_nothing'),
RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string) trans('firefly.skip_transaction'),
RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string) trans('firefly.jump_to_friday'),
RecurrenceRepetition::WEEKEND_TO_MONDAY => (string) trans('firefly.jump_to_monday'),
];
$hasOldInput = null !== $request->old('_token'); // flash some data
$preFilled = [
'first_date' => $tomorrow->format('Y-m-d'),
'transaction_type' => $hasOldInput ? $request->old('transaction_type') : 'withdrawal',
'active' => $hasOldInput ? (bool) $request->old('active') : true,
'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : true,
];
$request->session()->flash('preFilled', $preFilled);
return prefixView(
'recurring.create',
compact('tomorrow', 'oldRepetitionType', 'weekendResponses', 'preFilled', 'repetitionEnds', 'defaultCurrency', 'budgets')
);
}
/** /**
* Store a recurring transaction. * Store a recurring transaction.
* *
@@ -225,7 +226,7 @@ class CreateController extends Controller
return redirect(route('recurring.create'))->withInput(); return redirect(route('recurring.create'))->withInput();
} }
$request->session()->flash('success', (string) trans('firefly.stored_new_recurrence', ['title' => $recurrence->title])); $request->session()->flash('success', (string)trans('firefly.stored_new_recurrence', ['title' => $recurrence->title]));
app('preferences')->mark(); app('preferences')->mark();
// store attachment(s): // store attachment(s):
@@ -235,7 +236,7 @@ class CreateController extends Controller
$this->attachments->saveAttachmentsForModel($recurrence, $files); $this->attachments->saveAttachmentsForModel($recurrence, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info', (string) trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -243,7 +244,7 @@ class CreateController extends Controller
} }
$redirect = redirect($this->getPreviousUri('recurring.create.uri')); $redirect = redirect($this->getPreviousUri('recurring.create.uri'));
if (1 === (int) $request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
// set value so create routine will not overwrite URL: // set value so create routine will not overwrite URL:
$request->session()->put('recurring.create.fromStore', true); $request->session()->put('recurring.create.fromStore', true);

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Recurring; namespace FireflyIII\Http\Controllers\Recurring;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Recurrence; use FireflyIII\Models\Recurrence;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
@@ -52,7 +53,7 @@ class DeleteController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-paint-brush'); app('view')->share('mainTitleIcon', 'fa-paint-brush');
app('view')->share('title', (string) trans('firefly.recurrences')); app('view')->share('title', (string)trans('firefly.recurrences'));
$this->recurring = app(RecurringRepositoryInterface::class); $this->recurring = app(RecurringRepositoryInterface::class);
@@ -70,7 +71,7 @@ class DeleteController extends Controller
*/ */
public function delete(Recurrence $recurrence) public function delete(Recurrence $recurrence)
{ {
$subTitle = (string) trans('firefly.delete_recurring', ['title' => $recurrence->title]); $subTitle = (string)trans('firefly.delete_recurring', ['title' => $recurrence->title]);
// put previous url in session // put previous url in session
$this->rememberPreviousUri('recurrences.delete.uri'); $this->rememberPreviousUri('recurrences.delete.uri');
@@ -91,7 +92,7 @@ class DeleteController extends Controller
public function destroy(RecurringRepositoryInterface $repository, Request $request, Recurrence $recurrence) public function destroy(RecurringRepositoryInterface $repository, Request $request, Recurrence $recurrence)
{ {
$repository->destroy($recurrence); $repository->destroy($recurrence);
$request->session()->flash('success', (string) trans('firefly.' . 'recurrence_deleted', ['title' => $recurrence->title])); $request->session()->flash('success', (string)trans('firefly.' . 'recurrence_deleted', ['title' => $recurrence->title]));
app('preferences')->mark(); app('preferences')->mark();
return redirect($this->getPreviousUri('recurrences.delete.uri')); return redirect($this->getPreviousUri('recurrences.delete.uri'));

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Recurring; namespace FireflyIII\Http\Controllers\Recurring;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
@@ -44,9 +45,9 @@ use Symfony\Component\HttpFoundation\ParameterBag;
*/ */
class EditController extends Controller class EditController extends Controller
{ {
private AttachmentHelperInterface $attachments;
private BudgetRepositoryInterface $budgetRepos; private BudgetRepositoryInterface $budgetRepos;
private RecurringRepositoryInterface $recurring; private RecurringRepositoryInterface $recurring;
private AttachmentHelperInterface $attachments;
/** /**
* EditController constructor. * EditController constructor.
@@ -61,12 +62,13 @@ class EditController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-paint-brush'); app('view')->share('mainTitleIcon', 'fa-paint-brush');
app('view')->share('title', (string) trans('firefly.recurrences')); app('view')->share('title', (string)trans('firefly.recurrences'));
app('view')->share('subTitle', (string) trans('firefly.recurrences')); app('view')->share('subTitle', (string)trans('firefly.recurrences'));
$this->recurring = app(RecurringRepositoryInterface::class); $this->recurring = app(RecurringRepositoryInterface::class);
$this->budgetRepos = app(BudgetRepositoryInterface::class); $this->budgetRepos = app(BudgetRepositoryInterface::class);
$this->attachments = app(AttachmentHelperInterface::class); $this->attachments = app(AttachmentHelperInterface::class);
return $next($request); return $next($request);
} }
); );
@@ -86,7 +88,7 @@ class EditController extends Controller
{ {
// TODO should be in repos // TODO should be in repos
$count = $recurrence->recurrenceTransactions()->count(); $count = $recurrence->recurrenceTransactions()->count();
if(0 === $count) { if (0 === $count) {
throw new FireflyException('This recurring transaction has no meta-data. You will have to delete it and recreate it. Sorry!'); throw new FireflyException('This recurring transaction has no meta-data. You will have to delete it and recreate it. Sorry!');
} }
@@ -112,9 +114,9 @@ class EditController extends Controller
$repetitionEnd = 'forever'; $repetitionEnd = 'forever';
$repetitionEnds = [ $repetitionEnds = [
'forever' => (string) trans('firefly.repeat_forever'), 'forever' => (string)trans('firefly.repeat_forever'),
'until_date' => (string) trans('firefly.repeat_until_date'), 'until_date' => (string)trans('firefly.repeat_until_date'),
'times' => (string) trans('firefly.repeat_times'), 'times' => (string)trans('firefly.repeat_times'),
]; ];
if (null !== $recurrence->repeat_until) { if (null !== $recurrence->repeat_until) {
$repetitionEnd = 'until_date'; // @codeCoverageIgnore $repetitionEnd = 'until_date'; // @codeCoverageIgnore
@@ -124,17 +126,17 @@ class EditController extends Controller
} }
$weekendResponses = [ $weekendResponses = [
RecurrenceRepetition::WEEKEND_DO_NOTHING => (string) trans('firefly.do_nothing'), RecurrenceRepetition::WEEKEND_DO_NOTHING => (string)trans('firefly.do_nothing'),
RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string) trans('firefly.skip_transaction'), RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string)trans('firefly.skip_transaction'),
RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string) trans('firefly.jump_to_friday'), RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string)trans('firefly.jump_to_friday'),
RecurrenceRepetition::WEEKEND_TO_MONDAY => (string) trans('firefly.jump_to_monday'), RecurrenceRepetition::WEEKEND_TO_MONDAY => (string)trans('firefly.jump_to_monday'),
]; ];
$hasOldInput = null !== $request->old('_token'); $hasOldInput = null !== $request->old('_token');
$preFilled = [ $preFilled = [
'transaction_type' => strtolower($recurrence->transactionType->type), 'transaction_type' => strtolower($recurrence->transactionType->type),
'active' => $hasOldInput ? (bool) $request->old('active') : $recurrence->active, 'active' => $hasOldInput ? (bool)$request->old('active') : $recurrence->active,
'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : $recurrence->apply_rules, 'apply_rules' => $hasOldInput ? (bool)$request->old('apply_rules') : $recurrence->apply_rules,
'deposit_source_id' => $array['transactions'][0]['source_id'], 'deposit_source_id' => $array['transactions'][0]['source_id'],
'withdrawal_destination_id' => $array['transactions'][0]['destination_id'], 'withdrawal_destination_id' => $array['transactions'][0]['destination_id'],
]; ];
@@ -162,7 +164,7 @@ class EditController extends Controller
$this->recurring->update($recurrence, $data); $this->recurring->update($recurrence, $data);
$request->session()->flash('success', (string) trans('firefly.updated_recurrence', ['title' => $recurrence->title])); $request->session()->flash('success', (string)trans('firefly.updated_recurrence', ['title' => $recurrence->title]));
// store new attachment(s): // store new attachment(s):
$files = $request->hasFile('attachments') ? $request->file('attachments') : null; $files = $request->hasFile('attachments') ? $request->file('attachments') : null;
@@ -170,7 +172,7 @@ class EditController extends Controller
$this->attachments->saveAttachmentsForModel($recurrence, $files); $this->attachments->saveAttachmentsForModel($recurrence, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info', (string) trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
@@ -178,7 +180,7 @@ class EditController extends Controller
} }
app('preferences')->mark(); app('preferences')->mark();
$redirect = redirect($this->getPreviousUri('recurrences.edit.uri')); $redirect = redirect($this->getPreviousUri('recurrences.edit.uri'));
if (1 === (int) $request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {
// set value so edit routine will not overwrite URL: // set value so edit routine will not overwrite URL:
$request->session()->put('recurrences.edit.fromUpdate', true); $request->session()->put('recurrences.edit.fromUpdate', true);

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Recurring; namespace FireflyIII\Http\Controllers\Recurring;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
@@ -42,6 +43,7 @@ use Symfony\Component\HttpFoundation\ParameterBag;
class IndexController extends Controller class IndexController extends Controller
{ {
use GetConfigurationData; use GetConfigurationData;
private RecurringRepositoryInterface $recurringRepos; private RecurringRepositoryInterface $recurringRepos;
/** /**
@@ -57,7 +59,7 @@ class IndexController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-paint-brush'); app('view')->share('mainTitleIcon', 'fa-paint-brush');
app('view')->share('title', (string) trans('firefly.recurrences')); app('view')->share('title', (string)trans('firefly.recurrences'));
$this->recurringRepos = app(RecurringRepositoryInterface::class); $this->recurringRepos = app(RecurringRepositoryInterface::class);
@@ -72,20 +74,20 @@ class IndexController extends Controller
* *
* @param Request $request * @param Request $request
* *
* @return Factory|View
* @throws FireflyException * @throws FireflyException
* *
* @return Factory|View
*/ */
public function index(Request $request) public function index(Request $request)
{ {
$page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$collection = $this->recurringRepos->get(); $collection = $this->recurringRepos->get();
$today = today(config('app.timezone')); $today = today(config('app.timezone'));
$year = today(config('app.timezone')); $year = today(config('app.timezone'));
// split collection // split collection
$total = $collection->count(); $total = $collection->count();
$recurrences = $collection->slice(($page - 1) * $pageSize, $pageSize); $recurrences = $collection->slice(($page - 1) * $pageSize, $pageSize);
/** @var RecurrenceTransformer $transformer */ /** @var RecurrenceTransformer $transformer */

View File

@@ -41,6 +41,7 @@ use Symfony\Component\HttpFoundation\ParameterBag;
class ShowController extends Controller class ShowController extends Controller
{ {
use GetConfigurationData; use GetConfigurationData;
/** @var RecurringRepositoryInterface Recurring repository */ /** @var RecurringRepositoryInterface Recurring repository */
private $recurring; private $recurring;
@@ -58,7 +59,7 @@ class ShowController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('mainTitleIcon', 'fa-paint-brush'); app('view')->share('mainTitleIcon', 'fa-paint-brush');
app('view')->share('title', (string) trans('firefly.recurrences')); app('view')->share('title', (string)trans('firefly.recurrences'));
$this->recurring = app(RecurringRepositoryInterface::class); $this->recurring = app(RecurringRepositoryInterface::class);
@@ -66,13 +67,14 @@ class ShowController extends Controller
} }
); );
} }
/** /**
* Show a single recurring transaction. * Show a single recurring transaction.
* *
* @param Recurrence $recurrence * @param Recurrence $recurrence
* *
* @throws FireflyException
* @return Factory|View * @return Factory|View
* @throws FireflyException
*/ */
public function show(Recurrence $recurrence) public function show(Recurrence $recurrence)
{ {
@@ -92,8 +94,8 @@ class ShowController extends Controller
} }
} }
$subTitle = (string) trans('firefly.overview_for_recurrence', ['title' => $recurrence->title]); $subTitle = (string)trans('firefly.overview_for_recurrence', ['title' => $recurrence->title]);
return prefixView('recurring.show', compact('recurrence', 'subTitle', 'array', 'groups','today')); return prefixView('recurring.show', compact('recurrence', 'subTitle', 'array', 'groups', 'today'));
} }
} }

View File

@@ -56,6 +56,7 @@ class BalanceController extends Controller
} }
); );
} }
/** /**
* Show overview of budget balances. * Show overview of budget balances.
* *

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Report; namespace FireflyIII\Http\Controllers\Report;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Helpers\Report\ReportHelperInterface; use FireflyIII\Helpers\Report\ReportHelperInterface;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;

View File

@@ -265,7 +265,7 @@ class BudgetController extends Controller
$total = $sums[$currencyId]['sum'] ?? '0'; $total = $sums[$currencyId]['sum'] ?? '0';
$pct = '0'; $pct = '0';
if (0 !== bccomp($sum, '0') && 0 !== bccomp($total, '9')) { if (0 !== bccomp($sum, '0') && 0 !== bccomp($total, '9')) {
$pct = round((float) bcmul(bcdiv($sum, $total), '100')); $pct = round((float)bcmul(bcdiv($sum, $total), '100'));
} }
$report[$budgetId]['currencies'][$currencyId]['sum_pct'] = $pct; $report[$budgetId]['currencies'][$currencyId]['sum_pct'] = $pct;
} }

View File

@@ -44,8 +44,8 @@ class CategoryController extends Controller
{ {
use BasicDataSupport; use BasicDataSupport;
private OperationsRepositoryInterface $opsRepository;
private NoCategoryRepositoryInterface $noCatRepository; private NoCategoryRepositoryInterface $noCatRepository;
private OperationsRepositoryInterface $opsRepository;
/** /**
* ExpenseReportController constructor. * ExpenseReportController constructor.
@@ -131,16 +131,16 @@ class CategoryController extends Controller
/** @var array $category */ /** @var array $category */
foreach ($currency['categories'] as $category) { foreach ($currency['categories'] as $category) {
foreach ($category['transaction_journals'] as $journal) { foreach ($category['transaction_journals'] as $journal) {
$destinationId = $journal['destination_account_id']; $destinationId = $journal['destination_account_id'];
$report[$destinationId]['currencies'][$currencyId] $report[$destinationId]['currencies'][$currencyId]
= $report[$destinationId]['currencies'][$currencyId] = $report[$destinationId]['currencies'][$currencyId]
?? [ ?? [
'currency_id' => $currency['currency_id'], 'currency_id' => $currency['currency_id'],
'currency_symbol' => $currency['currency_symbol'], 'currency_symbol' => $currency['currency_symbol'],
'currency_name' => $currency['currency_name'], 'currency_name' => $currency['currency_name'],
'currency_decimal_places' => $currency['currency_decimal_places'], 'currency_decimal_places' => $currency['currency_decimal_places'],
'categories' => [], 'categories' => [],
]; ];
$report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']] $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]
= $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']] = $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]
?? ??

View File

@@ -291,6 +291,31 @@ class DoubleController extends Controller
return prefixView('reports.double.partials.accounts', compact('sums', 'report')); return prefixView('reports.double.partials.accounts', compact('sums', 'report'));
} }
/**
* TODO this method is double.
*
* @param Collection $accounts
* @param int $id
* @param string $name
* @param string|null $iban
*
* @return string
*/
private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
{
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name && $account->id !== $id) {
return $account->name;
}
if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
return $account->iban;
}
}
return $name;
}
/** /**
* @param Collection $accounts * @param Collection $accounts
* @param Collection $double * @param Collection $double
@@ -490,29 +515,4 @@ class DoubleController extends Controller
return $result; return $result;
} }
/**
* TODO this method is double.
*
* @param Collection $accounts
* @param int $id
* @param string $name
* @param string|null $iban
*
* @return string
*/
private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
{
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name && $account->id !== $id) {
return $account->name;
}
if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
return $account->iban;
}
}
return $name;
}
} }

View File

@@ -57,6 +57,7 @@ class OperationsController extends Controller
} }
); );
} }
/** /**
* View of income and expense. * View of income and expense.
* *

View File

@@ -125,16 +125,16 @@ class TagController extends Controller
/** @var array $category */ /** @var array $category */
foreach ($currency['tags'] as $tag) { foreach ($currency['tags'] as $tag) {
foreach ($tag['transaction_journals'] as $journal) { foreach ($tag['transaction_journals'] as $journal) {
$destinationId = $journal['destination_account_id']; $destinationId = $journal['destination_account_id'];
$report[$destinationId]['currencies'][$currencyId] $report[$destinationId]['currencies'][$currencyId]
= $report[$destinationId]['currencies'][$currencyId] = $report[$destinationId]['currencies'][$currencyId]
?? [ ?? [
'currency_id' => $currency['currency_id'], 'currency_id' => $currency['currency_id'],
'currency_symbol' => $currency['currency_symbol'], 'currency_symbol' => $currency['currency_symbol'],
'currency_name' => $currency['currency_name'], 'currency_name' => $currency['currency_name'],
'currency_decimal_places' => $currency['currency_decimal_places'], 'currency_decimal_places' => $currency['currency_decimal_places'],
'tags' => [], 'tags' => [],
]; ];
$report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']] $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']]
= $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']] = $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']]
?? ??

View File

@@ -63,7 +63,7 @@ class ReportController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.reports')); app('view')->share('title', (string)trans('firefly.reports'));
app('view')->share('mainTitleIcon', 'fa-bar-chart'); app('view')->share('mainTitleIcon', 'fa-bar-chart');
app('view')->share('subTitleIcon', 'fa-calendar'); app('view')->share('subTitleIcon', 'fa-calendar');
$this->helper = app(ReportHelperInterface::class); $this->helper = app(ReportHelperInterface::class);
@@ -81,14 +81,14 @@ class ReportController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return Factory|View|string * @return Factory|View|string
* *
* @throws FireflyException
*/ */
public function auditReport(Collection $accounts, Carbon $start, Carbon $end) public function auditReport(Collection $accounts, Carbon $start, Carbon $end)
{ {
if ($end < $start) { if ($end < $start) {
return prefixView('error')->with('message', (string) trans('firefly.end_after_start_date')); // @codeCoverageIgnore return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore
} }
$this->repository->cleanupBudgets(); $this->repository->cleanupBudgets();
@@ -117,14 +117,14 @@ class ReportController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return Factory|View|string * @return Factory|View|string
* *
* @throws FireflyException
*/ */
public function budgetReport(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end) public function budgetReport(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end)
{ {
if ($end < $start) { if ($end < $start) {
return prefixView('error')->with('message', (string) trans('firefly.end_after_start_date')); // @codeCoverageIgnore return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore
} }
$this->repository->cleanupBudgets(); $this->repository->cleanupBudgets();
@@ -154,14 +154,14 @@ class ReportController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return Factory|View|string * @return Factory|View|string
* *
* @throws FireflyException
*/ */
public function categoryReport(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) public function categoryReport(Collection $accounts, Collection $categories, Carbon $start, Carbon $end)
{ {
if ($end < $start) { if ($end < $start) {
return prefixView('error')->with('message', (string) trans('firefly.end_after_start_date')); // @codeCoverageIgnore return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore
} }
$this->repository->cleanupBudgets(); $this->repository->cleanupBudgets();
@@ -190,14 +190,14 @@ class ReportController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return Factory|View|string * @return Factory|View|string
* *
* @throws FireflyException
*/ */
public function defaultReport(Collection $accounts, Carbon $start, Carbon $end) public function defaultReport(Collection $accounts, Carbon $start, Carbon $end)
{ {
if ($end < $start) { if ($end < $start) {
return prefixView('error')->with('message', (string) trans('firefly.end_after_start_date')); return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date'));
} }
$this->repository->cleanupBudgets(); $this->repository->cleanupBudgets();
@@ -227,8 +227,8 @@ class ReportController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return Factory|View|string * @return Factory|View|string
* @throws FireflyException
*/ */
public function doubleReport(Collection $accounts, Collection $expense, Carbon $start, Carbon $end) public function doubleReport(Collection $accounts, Collection $expense, Carbon $start, Carbon $end)
{ {
@@ -330,10 +330,10 @@ class ReportController extends Controller
* *
* @param ReportFormRequest $request * @param ReportFormRequest $request
* *
* @throws FireflyException
*
* @return RedirectResponse|Redirector * @return RedirectResponse|Redirector
* *
* @throws FireflyException
*
*/ */
public function postIndex(ReportFormRequest $request) public function postIndex(ReportFormRequest $request)
{ {
@@ -349,37 +349,37 @@ class ReportController extends Controller
if (0 === $request->getAccountList()->count()) { if (0 === $request->getAccountList()->count()) {
Log::debug('Account count is zero'); Log::debug('Account count is zero');
session()->flash('error', (string) trans('firefly.select_at_least_one_account')); session()->flash('error', (string)trans('firefly.select_at_least_one_account'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }
if ('category' === $reportType && 0 === $request->getCategoryList()->count()) { if ('category' === $reportType && 0 === $request->getCategoryList()->count()) {
session()->flash('error', (string) trans('firefly.select_at_least_one_category')); session()->flash('error', (string)trans('firefly.select_at_least_one_category'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }
if ('budget' === $reportType && 0 === $request->getBudgetList()->count()) { if ('budget' === $reportType && 0 === $request->getBudgetList()->count()) {
session()->flash('error', (string) trans('firefly.select_at_least_one_budget')); session()->flash('error', (string)trans('firefly.select_at_least_one_budget'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }
if ('tag' === $reportType && 0 === $request->getTagList()->count()) { if ('tag' === $reportType && 0 === $request->getTagList()->count()) {
session()->flash('error', (string) trans('firefly.select_at_least_one_tag')); session()->flash('error', (string)trans('firefly.select_at_least_one_tag'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }
if ('double' === $reportType && 0 === $request->getDoubleList()->count()) { if ('double' === $reportType && 0 === $request->getDoubleList()->count()) {
session()->flash('error', (string) trans('firefly.select_at_least_one_expense')); session()->flash('error', (string)trans('firefly.select_at_least_one_expense'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }
if ($request->getEndDate() < $request->getStartDate()) { if ($request->getEndDate() < $request->getStartDate()) {
return prefixView('error')->with('message', (string) trans('firefly.end_after_start_date')); return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date'));
} }
switch ($reportType) { switch ($reportType) {
@@ -406,6 +406,7 @@ class ReportController extends Controller
return redirect($uri); return redirect($uri);
} }
/** /**
* Get a tag report. * Get a tag report.
* *
@@ -414,13 +415,13 @@ class ReportController extends Controller
* @param Carbon $start * @param Carbon $start
* @param Carbon $end * @param Carbon $end
* *
* @throws FireflyException
* @return Factory|View|string * @return Factory|View|string
* @throws FireflyException
*/ */
public function tagReport(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) public function tagReport(Collection $accounts, Collection $tags, Carbon $start, Carbon $end)
{ {
if ($end < $start) { if ($end < $start) {
return prefixView('error')->with('message', (string) trans('firefly.end_after_start_date')); // @codeCoverageIgnore return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore
} }
$this->repository->cleanupBudgets(); $this->repository->cleanupBudgets();

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Rule; namespace FireflyIII\Http\Controllers\Rule;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Rule; use FireflyIII\Models\Rule;
use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Repositories\Rule\RuleRepositoryInterface;

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Rule; namespace FireflyIII\Http\Controllers\Rule;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\RuleFormRequest; use FireflyIII\Http\Requests\RuleFormRequest;
use FireflyIII\Models\Rule; use FireflyIII\Models\Rule;

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Rule; namespace FireflyIII\Http\Controllers\Rule;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\SelectTransactionsRequest; use FireflyIII\Http\Requests\SelectTransactionsRequest;
@@ -101,6 +102,7 @@ class SelectController extends Controller
return redirect()->route('rules.index'); return redirect()->route('rules.index');
} }
/** /**
* View to select transactions by a rule. * View to select transactions by a rule.
* *

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\RuleGroup; namespace FireflyIII\Http\Controllers\RuleGroup;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\RuleGroupFormRequest; use FireflyIII\Http\Requests\RuleGroupFormRequest;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
@@ -49,7 +50,7 @@ class CreateController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('title', (string)trans('firefly.rules'));
app('view')->share('mainTitleIcon', 'fa-random'); app('view')->share('mainTitleIcon', 'fa-random');
$this->repository = app(RuleGroupRepositoryInterface::class); $this->repository = app(RuleGroupRepositoryInterface::class);
@@ -67,7 +68,7 @@ class CreateController extends Controller
public function create() public function create()
{ {
$subTitleIcon = 'fa-clone'; $subTitleIcon = 'fa-clone';
$subTitle = (string) trans('firefly.make_new_rule_group'); $subTitle = (string)trans('firefly.make_new_rule_group');
// put previous url in session if not redirect from store (not "create another"). // put previous url in session if not redirect from store (not "create another").
if (true !== session('rule-groups.create.fromStore')) { if (true !== session('rule-groups.create.fromStore')) {
@@ -90,11 +91,11 @@ class CreateController extends Controller
$data = $request->getRuleGroupData(); $data = $request->getRuleGroupData();
$ruleGroup = $this->repository->store($data); $ruleGroup = $this->repository->store($data);
session()->flash('success', (string) trans('firefly.created_new_rule_group', ['title' => $ruleGroup->title])); session()->flash('success', (string)trans('firefly.created_new_rule_group', ['title' => $ruleGroup->title]));
app('preferences')->mark(); app('preferences')->mark();
$redirect = redirect($this->getPreviousUri('rule-groups.create.uri')); $redirect = redirect($this->getPreviousUri('rule-groups.create.uri'));
if (1 === (int) $request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
session()->put('rule-groups.create.fromStore', true); session()->put('rule-groups.create.fromStore', true);

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\RuleGroup; namespace FireflyIII\Http\Controllers\RuleGroup;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\RuleGroup; use FireflyIII\Models\RuleGroup;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
@@ -50,7 +51,7 @@ class DeleteController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('title', (string)trans('firefly.rules'));
app('view')->share('mainTitleIcon', 'fa-random'); app('view')->share('mainTitleIcon', 'fa-random');
$this->repository = app(RuleGroupRepositoryInterface::class); $this->repository = app(RuleGroupRepositoryInterface::class);
@@ -59,6 +60,7 @@ class DeleteController extends Controller
} }
); );
} }
/** /**
* Delete a rule group. * Delete a rule group.
* *
@@ -68,7 +70,7 @@ class DeleteController extends Controller
*/ */
public function delete(RuleGroup $ruleGroup) public function delete(RuleGroup $ruleGroup)
{ {
$subTitle = (string) trans('firefly.delete_rule_group', ['title' => $ruleGroup->title]); $subTitle = (string)trans('firefly.delete_rule_group', ['title' => $ruleGroup->title]);
// put previous url in session // put previous url in session
$this->rememberPreviousUri('rule-groups.delete.uri'); $this->rememberPreviousUri('rule-groups.delete.uri');
@@ -89,10 +91,10 @@ class DeleteController extends Controller
$title = $ruleGroup->title; $title = $ruleGroup->title;
/** @var RuleGroup $moveTo */ /** @var RuleGroup $moveTo */
$moveTo = $this->repository->find((int) $request->get('move_rules_before_delete')); $moveTo = $this->repository->find((int)$request->get('move_rules_before_delete'));
$this->repository->destroy($ruleGroup, $moveTo); $this->repository->destroy($ruleGroup, $moveTo);
session()->flash('success', (string) trans('firefly.deleted_rule_group', ['title' => $title])); session()->flash('success', (string)trans('firefly.deleted_rule_group', ['title' => $title]));
app('preferences')->mark(); app('preferences')->mark();
return redirect($this->getPreviousUri('rule-groups.delete.uri')); return redirect($this->getPreviousUri('rule-groups.delete.uri'));

View File

@@ -70,8 +70,8 @@ class EditController extends Controller
*/ */
public function down(RuleGroup $ruleGroup) public function down(RuleGroup $ruleGroup)
{ {
$maxOrder =$this->repository->maxOrder(); $maxOrder = $this->repository->maxOrder();
$order = (int)$ruleGroup->order; $order = (int)$ruleGroup->order;
if ($order < $maxOrder) { if ($order < $maxOrder) {
$newOrder = $order + 1; $newOrder = $order + 1;
$this->repository->setOrder($ruleGroup, $newOrder); $this->repository->setOrder($ruleGroup, $newOrder);
@@ -79,6 +79,7 @@ class EditController extends Controller
return redirect(route('rules.index')); return redirect(route('rules.index'));
} }
/** /**
* Edit a rule group. * Edit a rule group.
* *

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\RuleGroup; namespace FireflyIII\Http\Controllers\RuleGroup;
use Carbon\Carbon; use Carbon\Carbon;
use Exception; use Exception;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
@@ -52,7 +53,7 @@ class ExecutionController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('title', (string)trans('firefly.rules'));
app('view')->share('mainTitleIcon', 'fa-random'); app('view')->share('mainTitleIcon', 'fa-random');
$this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
@@ -61,6 +62,7 @@ class ExecutionController extends Controller
} }
); );
} }
/** /**
* Execute the given rulegroup on a set of existing transactions. * Execute the given rulegroup on a set of existing transactions.
* *
@@ -93,7 +95,7 @@ class ExecutionController extends Controller
$newRuleEngine->fire(); $newRuleEngine->fire();
// Tell the user that the job is queued // Tell the user that the job is queued
session()->flash('success', (string) trans('firefly.applied_rule_group_selection', ['title' => $ruleGroup->title])); session()->flash('success', (string)trans('firefly.applied_rule_group_selection', ['title' => $ruleGroup->title]));
return redirect()->route('rules.index'); return redirect()->route('rules.index');
} }
@@ -109,7 +111,7 @@ class ExecutionController extends Controller
{ {
$first = session('first')->format('Y-m-d'); $first = session('first')->format('Y-m-d');
$today = Carbon::now()->format('Y-m-d'); $today = Carbon::now()->format('Y-m-d');
$subTitle = (string) trans('firefly.apply_rule_group_selection', ['title' => $ruleGroup->title]); $subTitle = (string)trans('firefly.apply_rule_group_selection', ['title' => $ruleGroup->title]);
return prefixView('rules.rule-group.select-transactions', compact('first', 'today', 'ruleGroup', 'subTitle')); return prefixView('rules.rule-group.select-transactions', compact('first', 'today', 'ruleGroup', 'subTitle'));
} }

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\System; namespace FireflyIII\Http\Controllers\System;
use Log; use Log;
/** /**
@@ -35,6 +36,7 @@ class CronController
public function cron() public function cron()
{ {
Log::error('The cron endpoint has moved to GET /api/v1/cron/[token]'); Log::error('The cron endpoint has moved to GET /api/v1/cron/[token]');
return response('The cron endpoint has moved to GET /api/v1/cron/[token]', 500); return response('The cron endpoint has moved to GET /api/v1/cron/[token]', 500);
} }
} }

View File

@@ -22,17 +22,22 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\System; namespace FireflyIII\Http\Controllers\System;
use Artisan; use Artisan;
use Cache; use Cache;
use Exception; use Exception;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Preferences;
use FireflyIII\Support\Http\Controllers\GetConfigurationData; use FireflyIII\Support\Http\Controllers\GetConfigurationData;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\View\View;
use Laravel\Passport\Passport; use Laravel\Passport\Passport;
use Log; use Log;
use phpseclib3\Crypt\RSA;
/** /**
* Class InstallController * Class InstallController
* *
@@ -45,10 +50,11 @@ class InstallController extends Controller
public const FORBIDDEN_ERROR = 'Internal PHP function "proc_close" is disabled for your installation. Auto-migration is not possible.'; public const FORBIDDEN_ERROR = 'Internal PHP function "proc_close" is disabled for your installation. Auto-migration is not possible.';
public const BASEDIR_ERROR = 'Firefly III cannot execute the upgrade commands. It is not allowed to because of an open_basedir restriction.'; public const BASEDIR_ERROR = 'Firefly III cannot execute the upgrade commands. It is not allowed to because of an open_basedir restriction.';
public const OTHER_ERROR = 'An unknown error prevented Firefly III from executing the upgrade commands. Sorry.'; public const OTHER_ERROR = 'An unknown error prevented Firefly III from executing the upgrade commands. Sorry.';
private array $upgradeCommands;
private string $lastError; private string $lastError;
private array $upgradeCommands;
/** @noinspection MagicMethodsValidityInspection */ /** @noinspection MagicMethodsValidityInspection */
/** @noinspection PhpMissingParentConstructorInspection */ /** @noinspection PhpMissingParentConstructorInspection */
/** /**
* InstallController constructor. * InstallController constructor.
*/ */
@@ -110,7 +116,7 @@ class InstallController extends Controller
/** /**
* Show index. * Show index.
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return Factory|View
*/ */
public function index() public function index()
{ {
@@ -123,40 +129,6 @@ class InstallController extends Controller
return prefixView('install.index'); return prefixView('install.index');
} }
/**
* Create specific RSA keys.
*/
public function keys(): void
{
// switch on PHP version.
$result = version_compare(phpversion(), '8.0');
Log::info(sprintf('PHP version is %s', $result));
if (-1 === $result) {
Log::info('Will run PHP7 code.');
// PHP 7
$rsa = new \phpseclib\Crypt\RSA;
$keys = $rsa->createKey(4096);
}
if ($result >= 0) {
Log::info('Will run PHP8 code.');
// PHP 8
$keys = \phpseclib3\Crypt\RSA::createKey(4096);
}
[$publicKey, $privateKey] = [
Passport::keyPath('oauth-public.key'),
Passport::keyPath('oauth-private.key'),
];
if (file_exists($publicKey) || file_exists($privateKey)) {
return;
}
file_put_contents($publicKey, Arr::get($keys, 'publickey'));
file_put_contents($privateKey, Arr::get($keys, 'privatekey'));
}
/** /**
* @param Request $request * @param Request $request
* *
@@ -238,4 +210,38 @@ class InstallController extends Controller
return true; return true;
} }
/**
* Create specific RSA keys.
*/
public function keys(): void
{
// switch on PHP version.
$result = version_compare(phpversion(), '8.0');
Log::info(sprintf('PHP version is %s', $result));
if (-1 === $result) {
Log::info('Will run PHP7 code.');
// PHP 7
$rsa = new \phpseclib\Crypt\RSA;
$keys = $rsa->createKey(4096);
}
if ($result >= 0) {
Log::info('Will run PHP8 code.');
// PHP 8
$keys = RSA::createKey(4096);
}
[$publicKey, $privateKey] = [
Passport::keyPath('oauth-public.key'),
Passport::keyPath('oauth-private.key'),
];
if (file_exists($publicKey) || file_exists($privateKey)) {
return;
}
file_put_contents($publicKey, Arr::get($keys, 'publickey'));
file_put_contents($privateKey, Arr::get($keys, 'privatekey'));
}
} }

View File

@@ -43,7 +43,7 @@ class TagController extends Controller
{ {
use PeriodOverview; use PeriodOverview;
protected TagRepositoryInterface $repository; protected TagRepositoryInterface $repository;
private AttachmentHelperInterface $attachmentsHelper; private AttachmentHelperInterface $attachmentsHelper;
/** /**
@@ -56,11 +56,11 @@ class TagController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
app('view')->share('title', (string) trans('firefly.tags')); app('view')->share('title', (string)trans('firefly.tags'));
app('view')->share('mainTitleIcon', 'fa-tag'); app('view')->share('mainTitleIcon', 'fa-tag');
$this->attachmentsHelper = app(AttachmentHelperInterface::class); $this->attachmentsHelper = app(AttachmentHelperInterface::class);
$this->repository = app(TagRepositoryInterface::class); $this->repository = app(TagRepositoryInterface::class);
return $next($request); return $next($request);
} }
@@ -74,7 +74,7 @@ class TagController extends Controller
*/ */
public function create(Request $request) public function create(Request $request)
{ {
$subTitle = (string) trans('firefly.new_tag'); $subTitle = (string)trans('firefly.new_tag');
$subTitleIcon = 'fa-tag'; $subTitleIcon = 'fa-tag';
// location info: // location info:
@@ -106,7 +106,7 @@ class TagController extends Controller
*/ */
public function delete(Tag $tag) public function delete(Tag $tag)
{ {
$subTitle = (string) trans('breadcrumbs.delete_tag', ['tag' => $tag->tag]); $subTitle = (string)trans('breadcrumbs.delete_tag', ['tag' => $tag->tag]);
// put previous url in session // put previous url in session
$this->rememberPreviousUri('tags.delete.uri'); $this->rememberPreviousUri('tags.delete.uri');
@@ -126,7 +126,7 @@ class TagController extends Controller
$tagName = $tag->tag; $tagName = $tag->tag;
$this->repository->destroy($tag); $this->repository->destroy($tag);
session()->flash('success', (string) trans('firefly.deleted_tag', ['tag' => $tagName])); session()->flash('success', (string)trans('firefly.deleted_tag', ['tag' => $tagName]));
app('preferences')->mark(); app('preferences')->mark();
return redirect($this->getPreviousUri('tags.delete.uri')); return redirect($this->getPreviousUri('tags.delete.uri'));
@@ -141,7 +141,7 @@ class TagController extends Controller
*/ */
public function edit(Tag $tag) public function edit(Tag $tag)
{ {
$subTitle = (string) trans('firefly.edit_tag', ['tag' => $tag->tag]); $subTitle = (string)trans('firefly.edit_tag', ['tag' => $tag->tag]);
$subTitleIcon = 'fa-tag'; $subTitleIcon = 'fa-tag';
$location = $this->repository->getLocation($tag); $location = $this->repository->getLocation($tag);
@@ -177,7 +177,7 @@ class TagController extends Controller
public function index(TagRepositoryInterface $repository) public function index(TagRepositoryInterface $repository)
{ {
// start with oldest tag // start with oldest tag
$first = session('first', today()) ?? today(); $first = session('first', today()) ?? today();
$oldestTagDate = null === $repository->oldestTag() ? clone $first : $repository->oldestTag()->date; $oldestTagDate = null === $repository->oldestTag() ? clone $first : $repository->oldestTag()->date;
$newestTagDate = null === $repository->newestTag() ? today() : $repository->newestTag()->date; $newestTagDate = null === $repository->newestTag() ? today() : $repository->newestTag()->date;
$oldestTagDate->startOfYear(); $oldestTagDate->startOfYear();
@@ -202,20 +202,20 @@ class TagController extends Controller
{ {
$tags = $request->get('tags'); $tags = $request->get('tags');
if (null === $tags || !is_array($tags)) { if (null === $tags || !is_array($tags)) {
session()->flash('info', (string) trans('firefly.select_tags_to_delete')); session()->flash('info', (string)trans('firefly.select_tags_to_delete'));
return redirect(route('tags.index')); return redirect(route('tags.index'));
} }
$count = 0; $count = 0;
foreach ($tags as $tagId) { foreach ($tags as $tagId) {
$tagId = (int) $tagId; $tagId = (int)$tagId;
$tag = $this->repository->findNull($tagId); $tag = $this->repository->findNull($tagId);
if (null !== $tag) { if (null !== $tag) {
$this->repository->destroy($tag); $this->repository->destroy($tag);
$count++; $count++;
} }
} }
session()->flash('success', (string) trans_choice('firefly.deleted_x_tags', $count)); session()->flash('success', (string)trans_choice('firefly.deleted_x_tags', $count));
return redirect(route('tags.index')); return redirect(route('tags.index'));
} }
@@ -235,8 +235,8 @@ class TagController extends Controller
{ {
// default values: // default values:
$subTitleIcon = 'fa-tag'; $subTitleIcon = 'fa-tag';
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$start = $start ?? session('start'); $start = $start ?? session('start');
$end = $end ?? session('end'); $end = $end ?? session('end');
$location = $this->repository->getLocation($tag); $location = $this->repository->getLocation($tag);
@@ -278,10 +278,10 @@ class TagController extends Controller
{ {
// default values: // default values:
$subTitleIcon = 'fa-tag'; $subTitleIcon = 'fa-tag';
$page = (int) $request->get('page'); $page = (int)$request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$periods = []; $periods = [];
$subTitle = (string) trans('firefly.all_journals_for_tag', ['tag' => $tag->tag]); $subTitle = (string)trans('firefly.all_journals_for_tag', ['tag' => $tag->tag]);
$start = $this->repository->firstUseDate($tag) ?? today(config('app.timezone')); $start = $this->repository->firstUseDate($tag) ?? today(config('app.timezone'));
$end = $this->repository->lastUseDate($tag) ?? today(config('app.timezone')); $end = $this->repository->lastUseDate($tag) ?? today(config('app.timezone'));
$attachments = $this->repository->getAttachments($tag); $attachments = $this->repository->getAttachments($tag);
@@ -313,7 +313,7 @@ class TagController extends Controller
$result = $this->repository->store($data); $result = $this->repository->store($data);
Log::debug('Data after storage', $result->toArray()); Log::debug('Data after storage', $result->toArray());
session()->flash('success', (string) trans('firefly.created_tag', ['tag' => $data['tag']])); session()->flash('success', (string)trans('firefly.created_tag', ['tag' => $data['tag']]));
app('preferences')->mark(); app('preferences')->mark();
// store attachment(s): // store attachment(s):
@@ -323,14 +323,14 @@ class TagController extends Controller
$this->attachmentsHelper->saveAttachmentsForModel($result, $files); $this->attachmentsHelper->saveAttachmentsForModel($result, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info',(string)trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachmentsHelper->getMessages()->get('attachments')) > 0) { if (count($this->attachmentsHelper->getMessages()->get('attachments')) > 0) {
$request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); // @codeCoverageIgnore $request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); // @codeCoverageIgnore
} }
$redirect = redirect($this->getPreviousUri('tags.create.uri')); $redirect = redirect($this->getPreviousUri('tags.create.uri'));
if (1 === (int) $request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
session()->put('tags.create.fromStore', true); session()->put('tags.create.fromStore', true);
@@ -354,7 +354,7 @@ class TagController extends Controller
$data = $request->collectTagData(); $data = $request->collectTagData();
$tag = $this->repository->update($tag, $data); $tag = $this->repository->update($tag, $data);
session()->flash('success', (string) trans('firefly.updated_tag', ['tag' => $data['tag']])); session()->flash('success', (string)trans('firefly.updated_tag', ['tag' => $data['tag']]));
app('preferences')->mark(); app('preferences')->mark();
// store new attachment(s): // store new attachment(s):
@@ -364,14 +364,14 @@ class TagController extends Controller
$this->attachmentsHelper->saveAttachmentsForModel($tag, $files); $this->attachmentsHelper->saveAttachmentsForModel($tag, $files);
} }
if (null !== $files && auth()->user()->hasRole('demo')) { if (null !== $files && auth()->user()->hasRole('demo')) {
session()->flash('info',(string)trans('firefly.no_att_demo_user')); session()->flash('info', (string)trans('firefly.no_att_demo_user'));
} }
if (count($this->attachmentsHelper->getMessages()->get('attachments')) > 0) { if (count($this->attachmentsHelper->getMessages()->get('attachments')) > 0) {
$request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); // @codeCoverageIgnore $request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); // @codeCoverageIgnore
} }
$redirect = redirect($this->getPreviousUri('tags.edit.uri')); $redirect = redirect($this->getPreviousUri('tags.edit.uri'));
if (1 === (int) $request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
session()->put('tags.edit.fromUpdate', true); session()->put('tags.edit.fromUpdate', true);

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Transaction; namespace FireflyIII\Http\Controllers\Transaction;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\BulkEditJournalRequest; use FireflyIII\Http\Requests\BulkEditJournalRequest;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
@@ -38,6 +39,7 @@ class BulkController extends Controller
{ {
/** @var JournalRepositoryInterface Journals and transactions overview */ /** @var JournalRepositoryInterface Journals and transactions overview */
private $repository; private $repository;
/** /**
* BulkController constructor. * BulkController constructor.
* *
@@ -78,10 +80,11 @@ class BulkController extends Controller
// get list of budgets: // get list of budgets:
/** @var BudgetRepositoryInterface $budgetRepos */ /** @var BudgetRepositoryInterface $budgetRepos */
$budgetRepos = app(BudgetRepositoryInterface::class); $budgetRepos = app(BudgetRepositoryInterface::class);
$budgetList = app('expandedform')->makeSelectListWithEmpty($budgetRepos->getActiveBudgets()); $budgetList = app('expandedform')->makeSelectListWithEmpty($budgetRepos->getActiveBudgets());
return prefixView('transactions.bulk.edit', compact('journals', 'subTitle', 'budgetList')); return prefixView('transactions.bulk.edit', compact('journals', 'subTitle', 'budgetList'));
} }
/** /**
* Update all journals. * Update all journals.
* *
@@ -136,24 +139,6 @@ class BulkController extends Controller
return true; return true;
} }
/**
* @param TransactionJournal $journal
* @param bool $ignoreUpdate
* @param string $category
*
* @return bool
*/
private function updateJournalCategory(TransactionJournal $journal, bool $ignoreUpdate, string $category): bool
{
if (true === $ignoreUpdate) {
return false;
}
Log::debug(sprintf('Set budget to %s', $category));
$this->repository->updateCategory($journal, $category);
return true;
}
/** /**
* @param TransactionJournal $journal * @param TransactionJournal $journal
* @param string $action * @param string $action
@@ -172,6 +157,25 @@ class BulkController extends Controller
$new = array_unique(array_merge($tags, $existing)); $new = array_unique(array_merge($tags, $existing));
$this->repository->updateTags($journal, $new); $this->repository->updateTags($journal, $new);
} }
return true;
}
/**
* @param TransactionJournal $journal
* @param bool $ignoreUpdate
* @param string $category
*
* @return bool
*/
private function updateJournalCategory(TransactionJournal $journal, bool $ignoreUpdate, string $category): bool
{
if (true === $ignoreUpdate) {
return false;
}
Log::debug(sprintf('Set budget to %s', $category));
$this->repository->updateCategory($journal, $category);
return true; return true;
} }
} }

View File

@@ -38,9 +38,11 @@ use FireflyIII\Support\Http\Controllers\ModelInformation;
use FireflyIII\Support\Http\Controllers\UserNavigation; use FireflyIII\Support\Http\Controllers\UserNavigation;
use FireflyIII\Transformers\TransactionGroupTransformer; use FireflyIII\Transformers\TransactionGroupTransformer;
use FireflyIII\Validation\AccountValidator; use FireflyIII\Validation\AccountValidator;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Routing\Redirector; use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Log; use Log;
/** /**
@@ -52,8 +54,8 @@ class ConvertController extends Controller
{ {
use ModelInformation, UserNavigation; use ModelInformation, UserNavigation;
private JournalRepositoryInterface $repository;
private AccountRepositoryInterface $accountRepository; private AccountRepositoryInterface $accountRepository;
private JournalRepositoryInterface $repository;
/** /**
* ConvertController constructor. * ConvertController constructor.
@@ -76,13 +78,14 @@ class ConvertController extends Controller
} }
); );
} }
/** /**
* Show overview of a to be converted transaction. * Show overview of a to be converted transaction.
* *
* @param TransactionType $destinationType * @param TransactionType $destinationType
* @param TransactionGroup $group * @param TransactionGroup $group
* *
* @return RedirectResponse|Redirector|\Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return RedirectResponse|Redirector|Factory|View
* @throws Exception * @throws Exception
* *
*/ */
@@ -141,6 +144,137 @@ class ConvertController extends Controller
); );
} }
/**
* @return array
*/
private function getValidDepositSources(): array
{
// make repositories
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $this->accountRepository
->getActiveAccountsByType([AccountType::REVENUE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
$name = $account->name;
if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore
}
// maybe it's a liability thing:
if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_' . $account->accountType->type; // @codeCoverageIgnore
}
if (AccountType::CASH === $account->accountType->type) {
// @codeCoverageIgnoreStart
$role = 'cash_account';
$name = sprintf('(%s)', trans('firefly.cash'));
// @codeCoverageIgnoreEnd
}
if (AccountType::REVENUE === $account->accountType->type) {
$role = 'revenue_account'; // @codeCoverageIgnore
}
$key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $name;
}
return $grouped;
}
/**
* @return array
*/
private function getValidWithdrawalDests(): array
{
// make repositories
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $this->accountRepository->getActiveAccountsByType(
[AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]
);
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
$name = $account->name;
if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore
}
// maybe it's a liability thing:
if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_' . $account->accountType->type; // @codeCoverageIgnore
}
if (AccountType::CASH === $account->accountType->type) {
// @codeCoverageIgnoreStart
$role = 'cash_account';
$name = sprintf('(%s)', trans('firefly.cash'));
// @codeCoverageIgnoreEnd
}
if (AccountType::EXPENSE === $account->accountType->type) {
$role = 'expense_account'; // @codeCoverageIgnore
}
$key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $name;
}
return $grouped;
}
/**
* @return array
* @throws Exception
*/
private function getLiabilities(): array
{
// make repositories
$accountList = $this->accountRepository->getActiveAccountsByType([AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$defaultCurrency = app('amount')->getDefaultCurrency();
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today());
$currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = 'l_' . $account->accountType->type;
$key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')';
}
return $grouped;
}
/**
* @return array
* @throws Exception
*/
private function getAssetAccounts(): array
{
// make repositories
$accountList = $this->accountRepository->getActiveAccountsByType([AccountType::ASSET]);
$defaultCurrency = app('amount')->getDefaultCurrency();
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today());
$currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore
}
$key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')';
}
return $grouped;
}
/** /**
* Do the conversion. * Do the conversion.
* *
@@ -232,135 +366,4 @@ class ConvertController extends Controller
return $journal; return $journal;
} }
/**
* @return array
* @throws Exception
*/
private function getAssetAccounts(): array
{
// make repositories
$accountList = $this->accountRepository->getActiveAccountsByType([AccountType::ASSET]);
$defaultCurrency = app('amount')->getDefaultCurrency();
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today());
$currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore
}
$key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')';
}
return $grouped;
}
/**
* @return array
* @throws Exception
*/
private function getLiabilities(): array
{
// make repositories
$accountList = $this->accountRepository->getActiveAccountsByType([AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$defaultCurrency = app('amount')->getDefaultCurrency();
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today());
$currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = 'l_' . $account->accountType->type;
$key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')';
}
return $grouped;
}
/**
* @return array
*/
private function getValidDepositSources(): array
{
// make repositories
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $this->accountRepository
->getActiveAccountsByType([AccountType::REVENUE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
$name = $account->name;
if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore
}
// maybe it's a liability thing:
if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_' . $account->accountType->type; // @codeCoverageIgnore
}
if (AccountType::CASH === $account->accountType->type) {
// @codeCoverageIgnoreStart
$role = 'cash_account';
$name = sprintf('(%s)', trans('firefly.cash'));
// @codeCoverageIgnoreEnd
}
if (AccountType::REVENUE === $account->accountType->type) {
$role = 'revenue_account'; // @codeCoverageIgnore
}
$key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $name;
}
return $grouped;
}
/**
* @return array
*/
private function getValidWithdrawalDests(): array
{
// make repositories
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $this->accountRepository->getActiveAccountsByType(
[AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]
);
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
$name = $account->name;
if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore
}
// maybe it's a liability thing:
if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_' . $account->accountType->type; // @codeCoverageIgnore
}
if (AccountType::CASH === $account->accountType->type) {
// @codeCoverageIgnoreStart
$role = 'cash_account';
$name = sprintf('(%s)', trans('firefly.cash'));
// @codeCoverageIgnoreEnd
}
if (AccountType::EXPENSE === $account->accountType->type) {
$role = 'expense_account'; // @codeCoverageIgnore
}
$key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $name;
}
return $grouped;
}
} }

View File

@@ -49,7 +49,7 @@ class CreateController extends Controller
$this->middleware( $this->middleware(
static function ($request, $next) { static function ($request, $next) {
app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('title', (string)trans('firefly.transactions'));
app('view')->share('mainTitleIcon', 'fa-exchange'); app('view')->share('mainTitleIcon', 'fa-exchange');
return $next($request); return $next($request);
@@ -75,7 +75,7 @@ class CreateController extends Controller
app('preferences')->mark(); app('preferences')->mark();
$title = $newGroup->title ?? $newGroup->transactionJournals->first()->description; $title = $newGroup->title ?? $newGroup->transactionJournals->first()->description;
$link = route('transactions.show', [$newGroup->id]); $link = route('transactions.show', [$newGroup->id]);
session()->flash('success', trans('firefly.stored_journal', ['description' => $title])); session()->flash('success', trans('firefly.stored_journal', ['description' => $title]));
session()->flash('success_uri', $link); session()->flash('success_uri', $link);
@@ -93,14 +93,14 @@ class CreateController extends Controller
{ {
app('preferences')->mark(); app('preferences')->mark();
$sourceId = (int) request()->get('source'); $sourceId = (int)request()->get('source');
$destinationId = (int) request()->get('destination'); $destinationId = (int)request()->get('destination');
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$cash = $repository->getCashAccount(); $cash = $repository->getCashAccount();
$preFilled = session()->has('preFilled') ? session('preFilled') : []; $preFilled = session()->has('preFilled') ? session('preFilled') : [];
$subTitle = (string) trans('breadcrumbs.create_new_transaction'); $subTitle = (string)trans('breadcrumbs.create_new_transaction');
$subTitleIcon = 'fa-plus'; $subTitleIcon = 'fa-plus';
$optionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data; $optionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data;
$allowedOpposingTypes = config('firefly.allowed_opposing_types'); $allowedOpposingTypes = config('firefly.allowed_opposing_types');
@@ -112,6 +112,7 @@ class CreateController extends Controller
$previousUri = str_replace($search, '', $previousUri); $previousUri = str_replace($search, '', $previousUri);
session()->put('preFilled', $preFilled); session()->put('preFilled', $preFilled);
return prefixView( return prefixView(
'transactions.create', 'transactions.create',
compact( compact(

Some files were not shown because too many files have changed in this diff Show More