Various code cleanup and fixed alignments.

This commit is contained in:
James Cole 2024-01-01 14:43:56 +01:00
parent 1368aafe5f
commit f963ac63f1
No known key found for this signature in database
GPG Key ID: B49A324B7EAD6D80
443 changed files with 3668 additions and 3672 deletions

View File

@ -22,7 +22,7 @@
$current = __DIR__; $current = __DIR__;
$paths = [ $paths = [
$current . '/../../app/Api', $current . '/../../app',
// $current . '/../../config', // $current . '/../../config',
// $current . '/../../database', // $current . '/../../database',
// $current . '/../../routes', // $current . '/../../routes',

View File

@ -118,7 +118,7 @@ class CorrectOpeningBalanceCurrencies extends Command
if ((int)$journal->transaction_currency_id !== $currency->id) { if ((int)$journal->transaction_currency_id !== $currency->id) {
$journal->transaction_currency_id = $currency->id; $journal->transaction_currency_id = $currency->id;
$journal->save(); $journal->save();
$count = 1; $count = 1;
} }
/** @var Transaction $transaction */ /** @var Transaction $transaction */
@ -126,7 +126,7 @@ class CorrectOpeningBalanceCurrencies extends Command
if ($transaction->transaction_currency_id !== $currency->id) { if ($transaction->transaction_currency_id !== $currency->id) {
$transaction->transaction_currency_id = $currency->id; $transaction->transaction_currency_id = $currency->id;
$transaction->save(); $transaction->save();
$count = 1; $count = 1;
} }
} }

View File

@ -37,7 +37,7 @@ class CreateAccessTokens extends Command
protected $description = 'Creates user access tokens which are used for command line access to personal data.'; protected $description = 'Creates user access tokens which are used for command line access to personal data.';
protected $signature = 'firefly-iii:create-access-tokens'; protected $signature = 'firefly-iii:create-access-tokens';
/** /**
* Execute the console command. * Execute the console command.
@ -50,8 +50,8 @@ class CreateAccessTokens extends Command
/** @var UserRepositoryInterface $repository */ /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
$count = 0; $count = 0;
$users = $repository->all(); $users = $repository->all();
/** @var User $user */ /** @var User $user */
foreach ($users as $user) { foreach ($users as $user) {

View File

@ -36,7 +36,7 @@ class CreateLinkTypes extends Command
protected $description = 'Creates all link types.'; protected $description = 'Creates all link types.';
protected $signature = 'firefly-iii:create-link-types'; protected $signature = 'firefly-iii:create-link-types';
/** /**
* Execute the console command. * Execute the console command.
@ -51,7 +51,7 @@ class CreateLinkTypes extends Command
'Reimbursement' => ['(partially) reimburses', 'is (partially) reimbursed by'], 'Reimbursement' => ['(partially) reimburses', 'is (partially) reimbursed by'],
]; ];
foreach ($set as $name => $values) { foreach ($set as $name => $values) {
$link = LinkType::where('name', $name) $link = LinkType::where('name', $name)
->first() ->first()
; ;
if (null === $link) { if (null === $link) {

View File

@ -46,7 +46,7 @@ class DeleteEmptyGroups extends Command
public function handle(): int public function handle(): int
{ {
$groupIds $groupIds
= TransactionGroup::leftJoin('transaction_journals', 'transaction_groups.id', '=', 'transaction_journals.transaction_group_id') = TransactionGroup::leftJoin('transaction_journals', 'transaction_groups.id', '=', 'transaction_journals.transaction_group_id')
->whereNull('transaction_journals.id')->get(['transaction_groups.id'])->pluck('id')->toArray() ->whereNull('transaction_journals.id')->get(['transaction_groups.id'])->pluck('id')->toArray()
; ;

View File

@ -38,7 +38,7 @@ class DeleteEmptyJournals extends Command
protected $description = 'Delete empty and uneven transaction journals.'; protected $description = 'Delete empty and uneven transaction journals.';
protected $signature = 'firefly-iii:delete-empty-journals'; protected $signature = 'firefly-iii:delete-empty-journals';
/** /**
* Execute the console command. * Execute the console command.
@ -56,7 +56,7 @@ class DeleteEmptyJournals extends Command
*/ */
private function deleteUnevenJournals(): void private function deleteUnevenJournals(): void
{ {
$set = Transaction::whereNull('deleted_at') $set = Transaction::whereNull('deleted_at')
->groupBy('transactions.transaction_journal_id') ->groupBy('transactions.transaction_journal_id')
->get([\DB::raw('COUNT(transactions.transaction_journal_id) as the_count'), 'transaction_journal_id']) // @phpstan-ignore-line ->get([\DB::raw('COUNT(transactions.transaction_journal_id) as the_count'), 'transaction_journal_id']) // @phpstan-ignore-line
; ;

View File

@ -37,7 +37,7 @@ class DeleteOrphanedTransactions extends Command
protected $description = 'Deletes orphaned transactions.'; protected $description = 'Deletes orphaned transactions.';
protected $signature = 'firefly-iii:delete-orphaned-transactions'; protected $signature = 'firefly-iii:delete-orphaned-transactions';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -37,7 +37,7 @@ class DeleteZeroAmount extends Command
protected $description = 'Delete transactions with zero amount.'; protected $description = 'Delete transactions with zero amount.';
protected $signature = 'firefly-iii:delete-zero-amount'; protected $signature = 'firefly-iii:delete-zero-amount';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -62,17 +62,17 @@ class EnableCurrencies extends Command
private function correctCurrencies(UserGroup $userGroup): void private function correctCurrencies(UserGroup $userGroup): void
{ {
/** @var CurrencyRepositoryInterface $repos */ /** @var CurrencyRepositoryInterface $repos */
$repos = app(CurrencyRepositoryInterface::class); $repos = app(CurrencyRepositoryInterface::class);
// first check if the user has any default currency (not necessarily the case, so can be forced). // first check if the user has any default currency (not necessarily the case, so can be forced).
$defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($userGroup); $defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($userGroup);
Log::debug(sprintf('Now correcting currencies for user group #%d', $userGroup->id)); Log::debug(sprintf('Now correcting currencies for user group #%d', $userGroup->id));
$found = [$defaultCurrency->id]; $found = [$defaultCurrency->id];
// get all meta entries // get all meta entries
/** @var Collection $meta */ /** @var Collection $meta */
$meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id')
->where('accounts.user_group_id', $userGroup->id) ->where('accounts.user_group_id', $userGroup->id)
->where('account_meta.name', 'currency_id')->groupBy('data')->get(['data']) ->where('account_meta.name', 'currency_id')->groupBy('data')->get(['data'])
; ;
@ -81,7 +81,7 @@ class EnableCurrencies extends Command
} }
// get all from journals: // get all from journals:
$journals = TransactionJournal::where('user_group_id', $userGroup->id) $journals = TransactionJournal::where('user_group_id', $userGroup->id)
->groupBy('transaction_currency_id')->get(['transaction_currency_id']) ->groupBy('transaction_currency_id')->get(['transaction_currency_id'])
; ;
foreach ($journals as $entry) { foreach ($journals as $entry) {
@ -89,7 +89,7 @@ class EnableCurrencies extends Command
} }
// get all from transactions // get all from transactions
$transactions = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') $transactions = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.user_group_id', $userGroup->id) ->where('transaction_journals.user_group_id', $userGroup->id)
->groupBy('transactions.transaction_currency_id', 'transactions.foreign_currency_id') ->groupBy('transactions.transaction_currency_id', 'transactions.foreign_currency_id')
->get(['transactions.transaction_currency_id', 'transactions.foreign_currency_id']) ->get(['transactions.transaction_currency_id', 'transactions.foreign_currency_id'])
@ -100,7 +100,7 @@ class EnableCurrencies extends Command
} }
// get all from budget limits // get all from budget limits
$limits = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') $limits = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->groupBy('transaction_currency_id') ->groupBy('transaction_currency_id')
->get(['budget_limits.transaction_currency_id']) ->get(['budget_limits.transaction_currency_id'])
; ;
@ -108,8 +108,8 @@ class EnableCurrencies extends Command
$found[] = $entry->transaction_currency_id; $found[] = $entry->transaction_currency_id;
} }
$found = array_values(array_unique($found)); $found = array_values(array_unique($found));
$found = array_values( $found = array_values(
array_filter( array_filter(
$found, $found,
static function (int $currencyId) { static function (int $currencyId) {
@ -118,7 +118,7 @@ class EnableCurrencies extends Command
) )
); );
$valid = new Collection(); $valid = new Collection();
/** @var int $currencyId */ /** @var int $currencyId */
foreach ($found as $currencyId) { foreach ($found as $currencyId) {
@ -127,7 +127,7 @@ class EnableCurrencies extends Command
$valid->push($currency); $valid->push($currency);
} }
} }
$ids = $valid->pluck('id')->toArray(); $ids = $valid->pluck('id')->toArray();
Log::debug(sprintf('Found currencies for user group #%d: %s', $userGroup->id, implode(', ', $ids))); Log::debug(sprintf('Found currencies for user group #%d: %s', $userGroup->id, implode(', ', $ids)));
$userGroup->currencies()->sync($ids); $userGroup->currencies()->sync($ids);

View File

@ -60,7 +60,7 @@ class FixAccountTypes extends Command
$this->expected = config('firefly.source_dests'); $this->expected = config('firefly.source_dests');
$expected = config('firefly.source_dests'); $expected = config('firefly.source_dests');
$query = TransactionJournal::leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id') $query = TransactionJournal::leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id')
->leftJoin( ->leftJoin(
'transactions as source', 'transactions as source',
static function (JoinClause $join): void { static function (JoinClause $join): void {
@ -94,7 +94,7 @@ class FixAccountTypes extends Command
} }
}); });
$resultSet = $query->get( $resultSet = $query->get(
[ [
'transaction_journals.id', 'transaction_journals.id',
// 'transaction_type_id as type_id', // 'transaction_type_id as type_id',
@ -138,7 +138,7 @@ class FixAccountTypes extends Command
private function inspectJournal(TransactionJournal $journal): void private function inspectJournal(TransactionJournal $journal): void
{ {
app('log')->debug(sprintf('Now inspecting journal #%d', $journal->id)); app('log')->debug(sprintf('Now inspecting journal #%d', $journal->id));
$transactions = $journal->transactions()->count(); $transactions = $journal->transactions()->count();
if (2 !== $transactions) { if (2 !== $transactions) {
app('log')->debug(sprintf('Journal has %d transactions, so can\'t fix.', $transactions)); app('log')->debug(sprintf('Journal has %d transactions, so can\'t fix.', $transactions));
$this->friendlyError(sprintf('Cannot inspect transaction journal #%d because it has %d transaction(s) instead of 2.', $journal->id, $transactions)); $this->friendlyError(sprintf('Cannot inspect transaction journal #%d because it has %d transaction(s) instead of 2.', $journal->id, $transactions));
@ -165,7 +165,7 @@ class FixAccountTypes extends Command
return; return;
} }
$expectedTypes = $this->expected[$type][$sourceAccountType]; $expectedTypes = $this->expected[$type][$sourceAccountType];
if (!in_array($destAccountType, $expectedTypes, true)) { if (!in_array($destAccountType, $expectedTypes, true)) {
app('log')->debug(sprintf('[b] Going to fix journal #%d', $journal->id)); app('log')->debug(sprintf('[b] Going to fix journal #%d', $journal->id));
$this->fixJournal($journal, $type, $sourceTransaction, $destTransaction); $this->fixJournal($journal, $type, $sourceTransaction, $destTransaction);
@ -187,9 +187,9 @@ class FixAccountTypes extends Command
app('log')->debug(sprintf('Going to fix journal #%d', $journal->id)); app('log')->debug(sprintf('Going to fix journal #%d', $journal->id));
++$this->count; ++$this->count;
// variables: // variables:
$sourceType = $source->account->accountType->type; $sourceType = $source->account->accountType->type;
$destinationType = $dest->account->accountType->type; $destinationType = $dest->account->accountType->type;
$combination = sprintf('%s%s%s', $transactionType, $source->account->accountType->type, $dest->account->accountType->type); $combination = sprintf('%s%s%s', $transactionType, $source->account->accountType->type, $dest->account->accountType->type);
app('log')->debug(sprintf('Combination is "%s"', $combination)); app('log')->debug(sprintf('Combination is "%s"', $combination));
if ($this->shouldBeTransfer($transactionType, $sourceType, $destinationType)) { if ($this->shouldBeTransfer($transactionType, $sourceType, $destinationType)) {
@ -214,9 +214,9 @@ class FixAccountTypes extends Command
} }
// transaction has no valid source. // transaction has no valid source.
$validSources = array_keys($this->expected[$transactionType]); $validSources = array_keys($this->expected[$transactionType]);
$canCreateSource = $this->canCreateSource($validSources); $canCreateSource = $this->canCreateSource($validSources);
$hasValidSource = $this->hasValidAccountType($validSources, $sourceType); $hasValidSource = $this->hasValidAccountType($validSources, $sourceType);
if (!$hasValidSource && $canCreateSource) { if (!$hasValidSource && $canCreateSource) {
$this->giveNewRevenue($journal, $source); $this->giveNewRevenue($journal, $source);
@ -279,7 +279,7 @@ class FixAccountTypes extends Command
$withdrawal = TransactionType::whereType(TransactionType::WITHDRAWAL)->first(); $withdrawal = TransactionType::whereType(TransactionType::WITHDRAWAL)->first();
$journal->transactionType()->associate($withdrawal); $journal->transactionType()->associate($withdrawal);
$journal->save(); $journal->save();
$message = sprintf('Converted transaction #%d from a transfer to a withdrawal.', $journal->id); $message = sprintf('Converted transaction #%d from a transfer to a withdrawal.', $journal->id);
$this->friendlyInfo($message); $this->friendlyInfo($message);
app('log')->debug($message); app('log')->debug($message);
// check it again: // check it again:
@ -329,7 +329,7 @@ class FixAccountTypes extends Command
$oldSource = $source->account; $oldSource = $source->account;
$source->account()->associate($result); $source->account()->associate($result);
$source->save(); $source->save();
$message = sprintf( $message = sprintf(
'Transaction journal #%d, source account changed from #%d ("%s") to #%d ("%s").', 'Transaction journal #%d, source account changed from #%d ("%s") to #%d ("%s").',
$journal->id, $journal->id,
$oldSource->id, $oldSource->id,

View File

@ -62,7 +62,7 @@ class FixFrontpageAccounts extends Command
private function fixPreference(Preference $preference): void private function fixPreference(Preference $preference): void
{ {
$fixed = []; $fixed = [];
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
@ -70,7 +70,7 @@ class FixFrontpageAccounts extends Command
return; return;
} }
$repository->setUser($preference->user); $repository->setUser($preference->user);
$data = $preference->data; $data = $preference->data;
if (is_array($data)) { if (is_array($data)) {
/** @var string $accountId */ /** @var string $accountId */
foreach ($data as $accountId) { foreach ($data as $accountId) {

View File

@ -46,8 +46,8 @@ class FixGroupAccounts extends Command
*/ */
public function handle(): int public function handle(): int
{ {
$groups = []; $groups = [];
$res = TransactionJournal::groupBy('transaction_group_id') $res = TransactionJournal::groupBy('transaction_group_id')
->get(['transaction_group_id', \DB::raw('COUNT(transaction_group_id) as the_count')])// @phpstan-ignore-line ->get(['transaction_group_id', \DB::raw('COUNT(transaction_group_id) as the_count')])// @phpstan-ignore-line
; ;

View File

@ -39,7 +39,7 @@ class FixIbans extends Command
protected $description = 'Removes spaces from IBANs'; protected $description = 'Removes spaces from IBANs';
protected $signature = 'firefly-iii:fix-ibans'; protected $signature = 'firefly-iii:fix-ibans';
private int $count = 0; private int $count = 0;
/** /**
* Execute the console command. * Execute the console command.
@ -79,13 +79,13 @@ class FixIbans extends Command
/** @var Account $account */ /** @var Account $account */
foreach ($accounts as $account) { foreach ($accounts as $account) {
$userId = $account->user_id; $userId = $account->user_id;
$set[$userId] ??= []; $set[$userId] ??= [];
$iban = (string)$account->iban; $iban = (string)$account->iban;
if ('' === $iban) { if ('' === $iban) {
continue; continue;
} }
$type = $account->accountType->type; $type = $account->accountType->type;
if (in_array($type, [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE], true)) { if (in_array($type, [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE], true)) {
$type = 'liabilities'; $type = 'liabilities';
} }

View File

@ -37,8 +37,8 @@ class FixLongDescriptions extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
private const int MAX_LENGTH = 1000; private const int MAX_LENGTH = 1000;
protected $description = 'Fixes long descriptions in journals and groups.'; protected $description = 'Fixes long descriptions in journals and groups.';
protected $signature = 'firefly-iii:fix-long-descriptions'; protected $signature = 'firefly-iii:fix-long-descriptions';
/** /**
* Execute the console command. * Execute the console command.
@ -58,7 +58,7 @@ class FixLongDescriptions extends Command
} }
} }
$groups = TransactionGroup::get(['id', 'title']); $groups = TransactionGroup::get(['id', 'title']);
/** @var TransactionGroup $group */ /** @var TransactionGroup $group */
foreach ($groups as $group) { foreach ($groups as $group) {

View File

@ -40,9 +40,9 @@ class FixRecurringTransactions extends Command
{ {
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
protected $description = 'Fixes recurring transactions with the wrong transaction type.'; protected $description = 'Fixes recurring transactions with the wrong transaction type.';
protected $signature = 'firefly-iii:fix-recurring-transactions'; protected $signature = 'firefly-iii:fix-recurring-transactions';
private int $count = 0; private int $count = 0;
private RecurringRepositoryInterface $recurringRepos; private RecurringRepositoryInterface $recurringRepos;
private UserRepositoryInterface $userRepos; private UserRepositoryInterface $userRepos;

View File

@ -80,7 +80,7 @@ class FixTransactionTypes extends Command
private function fixJournal(TransactionJournal $journal): bool private function fixJournal(TransactionJournal $journal): bool
{ {
$type = $journal->transactionType->type; $type = $journal->transactionType->type;
try { try {
$source = $this->getSourceAccount($journal); $source = $this->getSourceAccount($journal);
@ -115,7 +115,7 @@ class FixTransactionTypes extends Command
*/ */
private function getSourceAccount(TransactionJournal $journal): Account private function getSourceAccount(TransactionJournal $journal): Account
{ {
$collection = $journal->transactions->filter( $collection = $journal->transactions->filter(
static function (Transaction $transaction) { static function (Transaction $transaction) {
return $transaction->amount < 0; return $transaction->amount < 0;
} }
@ -131,7 +131,7 @@ class FixTransactionTypes extends Command
$transaction = $collection->first(); $transaction = $collection->first();
/** @var null|Account $account */ /** @var null|Account $account */
$account = $transaction->account; $account = $transaction->account;
if (null === $account) { if (null === $account) {
throw new FireflyException(sprintf('300003: Journal #%d, transaction #%d has no source account.', $journal->id, $transaction->id)); throw new FireflyException(sprintf('300003: Journal #%d, transaction #%d has no source account.', $journal->id, $transaction->id));
} }
@ -144,7 +144,7 @@ class FixTransactionTypes extends Command
*/ */
private function getDestinationAccount(TransactionJournal $journal): Account private function getDestinationAccount(TransactionJournal $journal): Account
{ {
$collection = $journal->transactions->filter( $collection = $journal->transactions->filter(
static function (Transaction $transaction) { static function (Transaction $transaction) {
return $transaction->amount > 0; return $transaction->amount > 0;
} }
@ -160,7 +160,7 @@ class FixTransactionTypes extends Command
$transaction = $collection->first(); $transaction = $collection->first();
/** @var null|Account $account */ /** @var null|Account $account */
$account = $transaction->account; $account = $transaction->account;
if (null === $account) { if (null === $account) {
throw new FireflyException(sprintf('300006: Journal #%d, transaction #%d has no destination account.', $journal->id, $transaction->id)); throw new FireflyException(sprintf('300006: Journal #%d, transaction #%d has no destination account.', $journal->id, $transaction->id));
} }

View File

@ -100,13 +100,13 @@ class FixUnevenAmount extends Command
private function fixJournal(int $param): void private function fixJournal(int $param): void
{ {
// one of the transactions is bad. // one of the transactions is bad.
$journal = TransactionJournal::find($param); $journal = TransactionJournal::find($param);
if (null === $journal) { if (null === $journal) {
return; return;
} }
/** @var null|Transaction $source */ /** @var null|Transaction $source */
$source = $journal->transactions()->where('amount', '<', 0)->first(); $source = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $source) { if (null === $source) {
$this->friendlyError( $this->friendlyError(
@ -122,11 +122,11 @@ class FixUnevenAmount extends Command
return; return;
} }
$amount = bcmul('-1', $source->amount); $amount = bcmul('-1', $source->amount);
// fix amount of destination: // fix amount of destination:
/** @var null|Transaction $destination */ /** @var null|Transaction $destination */
$destination = $journal->transactions()->where('amount', '>', 0)->first(); $destination = $journal->transactions()->where('amount', '>', 0)->first();
if (null === $destination) { if (null === $destination) {
$this->friendlyError( $this->friendlyError(
@ -146,7 +146,7 @@ class FixUnevenAmount extends Command
$destination->amount = $amount; $destination->amount = $amount;
$destination->save(); $destination->save();
$message = sprintf('Corrected amount in transaction journal #%d', $param); $message = sprintf('Corrected amount in transaction journal #%d', $param);
$this->friendlyInfo($message); $this->friendlyInfo($message);
} }
} }

View File

@ -48,7 +48,7 @@ class RemoveBills extends Command
if (null === $withdrawal) { if (null === $withdrawal) {
return 0; return 0;
} }
$journals = TransactionJournal::whereNotNull('bill_id')->where('transaction_type_id', '!=', $withdrawal->id)->get(); $journals = TransactionJournal::whereNotNull('bill_id')->where('transaction_type_id', '!=', $withdrawal->id)->get();
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {

View File

@ -36,7 +36,7 @@ class RenameMetaFields extends Command
protected $description = 'Rename changed meta fields.'; protected $description = 'Rename changed meta fields.';
protected $signature = 'firefly-iii:rename-meta-fields'; protected $signature = 'firefly-iii:rename-meta-fields';
private int $count = 0; private int $count = 0;
/** /**
* Execute the console command. * Execute the console command.
@ -72,7 +72,7 @@ class RenameMetaFields extends Command
private function rename(string $original, string $update): void private function rename(string $original, string $update): void
{ {
$total = \DB::table('journal_meta') $total = \DB::table('journal_meta')
->where('name', '=', $original) ->where('name', '=', $original)
->update(['name' => $update]) ->update(['name' => $update])
; ;

View File

@ -46,7 +46,7 @@ class ExportData extends Command
protected $description = 'Command to export data from Firefly III.'; protected $description = 'Command to export data from Firefly III.';
protected $signature = 'firefly-iii:export-data protected $signature = 'firefly-iii:export-data
{--user=1 : The user ID that the export should run for.} {--user=1 : The user ID that the export should run for.}
{--token= : The user\'s access token.} {--token= : The user\'s access token.}
{--start= : First transaction to export. Defaults to your very first transaction. Only applies to transaction export.} {--start= : First transaction to export. Defaults to your very first transaction. Only applies to transaction export.}
@ -81,7 +81,7 @@ class ExportData extends Command
} }
// set up repositories. // set up repositories.
$this->stupidLaravel(); $this->stupidLaravel();
$user = $this->getUser(); $user = $this->getUser();
$this->journalRepository->setUser($user); $this->journalRepository->setUser($user);
$this->accountRepository->setUser($user); $this->accountRepository->setUser($user);
@ -96,7 +96,7 @@ class ExportData extends Command
// make export object and configure it. // make export object and configure it.
/** @var ExportDataGenerator $exporter */ /** @var ExportDataGenerator $exporter */
$exporter = app(ExportDataGenerator::class); $exporter = app(ExportDataGenerator::class);
$exporter->setUser($user); $exporter->setUser($user);
$exporter->setStart($options['start']); $exporter->setStart($options['start']);
@ -111,7 +111,7 @@ class ExportData extends Command
$exporter->setExportRules($options['export']['rules']); $exporter->setExportRules($options['export']['rules']);
$exporter->setExportBills($options['export']['bills']); $exporter->setExportBills($options['export']['bills']);
$exporter->setExportPiggies($options['export']['piggies']); $exporter->setExportPiggies($options['export']['piggies']);
$data = $exporter->export(); $data = $exporter->export();
if (0 === count($data)) { if (0 === count($data)) {
$this->friendlyError('You must export *something*. Use --export-transactions or another option. See docs.firefly-iii.org'); $this->friendlyError('You must export *something*. Use --export-transactions or another option. See docs.firefly-iii.org');
} }

View File

@ -41,8 +41,8 @@ class CreateGroupMemberships extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '560_create_group_memberships'; public const string CONFIG_NAME = '560_create_group_memberships';
protected $description = 'Update group memberships'; protected $description = 'Update group memberships';
protected $signature = 'firefly-iii:create-group-memberships'; protected $signature = 'firefly-iii:create-group-memberships';
/** /**
* Execute the console command. * Execute the console command.
@ -65,12 +65,12 @@ class CreateGroupMemberships extends Command
public static function createGroupMembership(User $user): void public static function createGroupMembership(User $user): void
{ {
// check if membership exists // check if membership exists
$userGroup = UserGroup::where('title', $user->email)->first(); $userGroup = UserGroup::where('title', $user->email)->first();
if (null === $userGroup) { if (null === $userGroup) {
$userGroup = UserGroup::create(['title' => $user->email]); $userGroup = UserGroup::create(['title' => $user->email]);
} }
$userRole = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); $userRole = UserRole::where('title', UserRoleEnum::OWNER->value)->first();
if (null === $userRole) { if (null === $userRole) {
throw new FireflyException('Firefly III could not find a user role. Please make sure all migrations have run.'); throw new FireflyException('Firefly III could not find a user role. Please make sure all migrations have run.');

View File

@ -39,7 +39,7 @@ class ReportEmptyObjects extends Command
protected $description = 'Reports on empty database objects.'; protected $description = 'Reports on empty database objects.';
protected $signature = 'firefly-iii:report-empty-objects'; protected $signature = 'firefly-iii:report-empty-objects';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -35,7 +35,7 @@ class ReportIntegrity extends Command
protected $description = 'Will report on the integrity of your database.'; protected $description = 'Will report on the integrity of your database.';
protected $signature = 'firefly-iii:report-integrity'; protected $signature = 'firefly-iii:report-integrity';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -83,7 +83,7 @@ class UpdateGroupInformation extends Command
return; return;
} }
$set = [ $set = [
Account::class, Account::class,
Attachment::class, Attachment::class,
AvailableBudget::class, AvailableBudget::class,

View File

@ -37,7 +37,7 @@ class CreateDatabase extends Command
protected $description = 'Tries to create the database if it doesn\'t exist yet.'; protected $description = 'Tries to create the database if it doesn\'t exist yet.';
protected $signature = 'firefly-iii:create-database'; protected $signature = 'firefly-iii:create-database';
/** /**
* Execute the console command. * Execute the console command.
@ -52,8 +52,8 @@ class CreateDatabase extends Command
return 0; return 0;
} }
// try to set up a raw connection: // try to set up a raw connection:
$exists = false; $exists = false;
$dsn = sprintf('mysql:host=%s;port=%d;charset=utf8mb4', env('DB_HOST', 'localhost'), env('DB_PORT', '3306')); $dsn = sprintf('mysql:host=%s;port=%d;charset=utf8mb4', env('DB_HOST', 'localhost'), env('DB_PORT', '3306'));
if ('' !== env('DB_SOCKET', '')) { if ('' !== env('DB_SOCKET', '')) {
$dsn = sprintf('mysql:unix_socket=%s;charset=utf8mb4', env('DB_SOCKET', '')); $dsn = sprintf('mysql:unix_socket=%s;charset=utf8mb4', env('DB_SOCKET', ''));
@ -78,7 +78,7 @@ class CreateDatabase extends Command
// only continue when no error. // only continue when no error.
// with PDO, try to list DB's ( // with PDO, try to list DB's (
/** @var array $stmt */ /** @var array $stmt */
$stmt = $pdo->query('SHOW DATABASES;'); $stmt = $pdo->query('SHOW DATABASES;');
// slightly more complex but less error-prone. // slightly more complex but less error-prone.
foreach ($stmt as $row) { foreach ($stmt as $row) {
$name = $row['Database'] ?? false; $name = $row['Database'] ?? false;

View File

@ -38,7 +38,7 @@ class CreateFirstUser extends Command
protected $description = 'Creates a new user and gives admin rights. Outputs the password on the command line. Strictly for testing.'; protected $description = 'Creates a new user and gives admin rights. Outputs the password on the command line. Strictly for testing.';
protected $signature = 'firefly-iii:create-first-user {email}'; protected $signature = 'firefly-iii:create-first-user {email}';
private UserRepositoryInterface $repository; private UserRepositoryInterface $repository;
/** /**
@ -52,7 +52,7 @@ class CreateFirstUser extends Command
return 1; return 1;
} }
$this->stupidLaravel(); $this->stupidLaravel();
$count = $this->repository->count(); $count = $this->repository->count();
if ($count > 0) { if ($count > 0) {
$this->friendlyError('Already have more than zero users in DB.'); $this->friendlyError('Already have more than zero users in DB.');

View File

@ -53,8 +53,8 @@ class ForceDecimalSize extends Command
{ {
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
protected $description = 'This command resizes DECIMAL columns in MySQL or PostgreSQL and correct amounts (only MySQL).'; protected $description = 'This command resizes DECIMAL columns in MySQL or PostgreSQL and correct amounts (only MySQL).';
protected $signature = 'firefly-iii:force-decimal-size'; protected $signature = 'firefly-iii:force-decimal-size';
private string $cast; private string $cast;
private array $classes private array $classes
= [ = [
@ -73,7 +73,7 @@ class ForceDecimalSize extends Command
private string $operator; private string $operator;
private string $regularExpression; private string $regularExpression;
private array $tables private array $tables
= [ = [
'accounts' => ['virtual_balance'], 'accounts' => ['virtual_balance'],
'auto_budgets' => ['amount'], 'auto_budgets' => ['amount'],
'available_budgets' => ['amount'], 'available_budgets' => ['amount'],
@ -233,7 +233,7 @@ class ForceDecimalSize extends Command
$regularExpression = $this->regularExpression; $regularExpression = $this->regularExpression;
/** @var Builder $query */ /** @var Builder $query */
$query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') $query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id') ->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id)) ->where('account_meta.data', json_encode((string)$currency->id))
; ;
@ -246,7 +246,7 @@ class ForceDecimalSize extends Command
); );
} }
}); });
$result = $query->get(['accounts.*']); $result = $query->get(['accounts.*']);
if (0 === $result->count()) { if (0 === $result->count()) {
$this->friendlyPositive(sprintf('All accounts in %s are OK', $currency->code)); $this->friendlyPositive(sprintf('All accounts in %s are OK', $currency->code));
@ -257,7 +257,7 @@ class ForceDecimalSize extends Command
foreach ($result as $account) { foreach ($result as $account) {
/** @var string $field */ /** @var string $field */
foreach ($fields as $field) { foreach ($fields as $field) {
$value = $account->{$field}; $value = $account->{$field};
if (null === $value) { if (null === $value) {
continue; continue;
} }
@ -282,7 +282,7 @@ class ForceDecimalSize extends Command
$regularExpression = $this->regularExpression; $regularExpression = $this->regularExpression;
/** @var Builder $query */ /** @var Builder $query */
$query = $class::where('transaction_currency_id', $currency->id)->where( $query = $class::where('transaction_currency_id', $currency->id)->where(
static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void {
/** @var string $field */ /** @var string $field */
foreach ($fields as $field) { foreach ($fields as $field) {
@ -295,7 +295,7 @@ class ForceDecimalSize extends Command
} }
); );
$result = $query->get(['*']); $result = $query->get(['*']);
if (0 === $result->count()) { if (0 === $result->count()) {
$this->friendlyPositive(sprintf('All %s in %s are OK', $table, $currency->code)); $this->friendlyPositive(sprintf('All %s in %s are OK', $table, $currency->code));
@ -306,7 +306,7 @@ class ForceDecimalSize extends Command
foreach ($result as $item) { foreach ($result as $item) {
/** @var string $field */ /** @var string $field */
foreach ($fields as $field) { foreach ($fields as $field) {
$value = $item->{$field}; $value = $item->{$field};
if (null === $value) { if (null === $value) {
continue; continue;
} }
@ -329,7 +329,7 @@ class ForceDecimalSize extends Command
$regularExpression = $this->regularExpression; $regularExpression = $this->regularExpression;
/** @var Builder $query */ /** @var Builder $query */
$query = PiggyBankEvent::leftJoin('piggy_banks', 'piggy_bank_events.piggy_bank_id', '=', 'piggy_banks.id') $query = PiggyBankEvent::leftJoin('piggy_banks', 'piggy_bank_events.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id') ->where('account_meta.name', 'currency_id')
@ -345,7 +345,7 @@ class ForceDecimalSize extends Command
}) })
; ;
$result = $query->get(['piggy_bank_events.*']); $result = $query->get(['piggy_bank_events.*']);
if (0 === $result->count()) { if (0 === $result->count()) {
$this->friendlyPositive(sprintf('All piggy bank events in %s are OK', $currency->code)); $this->friendlyPositive(sprintf('All piggy bank events in %s are OK', $currency->code));
@ -356,7 +356,7 @@ class ForceDecimalSize extends Command
foreach ($result as $item) { foreach ($result as $item) {
/** @var string $field */ /** @var string $field */
foreach ($fields as $field) { foreach ($fields as $field) {
$value = $item->{$field}; $value = $item->{$field};
if (null === $value) { if (null === $value) {
continue; continue;
} }
@ -382,7 +382,7 @@ class ForceDecimalSize extends Command
// select all piggy bank repetitions with this currency and issue. // select all piggy bank repetitions with this currency and issue.
/** @var Builder $query */ /** @var Builder $query */
$query = PiggyBankRepetition::leftJoin('piggy_banks', 'piggy_bank_repetitions.piggy_bank_id', '=', 'piggy_banks.id') $query = PiggyBankRepetition::leftJoin('piggy_banks', 'piggy_bank_repetitions.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id') ->where('account_meta.name', 'currency_id')
@ -398,7 +398,7 @@ class ForceDecimalSize extends Command
}) })
; ;
$result = $query->get(['piggy_bank_repetitions.*']); $result = $query->get(['piggy_bank_repetitions.*']);
if (0 === $result->count()) { if (0 === $result->count()) {
$this->friendlyPositive(sprintf('All piggy bank repetitions in %s', $currency->code)); $this->friendlyPositive(sprintf('All piggy bank repetitions in %s', $currency->code));
@ -409,7 +409,7 @@ class ForceDecimalSize extends Command
foreach ($result as $item) { foreach ($result as $item) {
/** @var string $field */ /** @var string $field */
foreach ($fields as $field) { foreach ($fields as $field) {
$value = $item->{$field}; $value = $item->{$field};
if (null === $value) { if (null === $value) {
continue; continue;
} }
@ -434,7 +434,7 @@ class ForceDecimalSize extends Command
$regularExpression = $this->regularExpression; $regularExpression = $this->regularExpression;
/** @var Builder $query */ /** @var Builder $query */
$query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') $query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id') ->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id)) ->where('account_meta.data', json_encode((string)$currency->id))
@ -449,7 +449,7 @@ class ForceDecimalSize extends Command
}) })
; ;
$result = $query->get(['piggy_banks.*']); $result = $query->get(['piggy_banks.*']);
if (0 === $result->count()) { if (0 === $result->count()) {
$this->friendlyPositive(sprintf('All piggy banks in %s are OK', $currency->code)); $this->friendlyPositive(sprintf('All piggy banks in %s are OK', $currency->code));
@ -460,7 +460,7 @@ class ForceDecimalSize extends Command
foreach ($result as $item) { foreach ($result as $item) {
/** @var string $field */ /** @var string $field */
foreach ($fields as $field) { foreach ($fields as $field) {
$value = $item->{$field}; $value = $item->{$field};
if (null === $value) { if (null === $value) {
continue; continue;
} }
@ -480,7 +480,7 @@ class ForceDecimalSize extends Command
{ {
// select all transactions with this currency and issue. // select all transactions with this currency and issue.
/** @var Builder $query */ /** @var Builder $query */
$query = Transaction::where('transaction_currency_id', $currency->id)->where( $query = Transaction::where('transaction_currency_id', $currency->id)->where(
DB::raw(sprintf('CAST(amount as %s)', $this->cast)), // @phpstan-ignore-line DB::raw(sprintf('CAST(amount as %s)', $this->cast)), // @phpstan-ignore-line
$this->operator, $this->operator,
DB::raw(sprintf($this->regularExpression, $currency->decimal_places)) DB::raw(sprintf($this->regularExpression, $currency->decimal_places))
@ -493,7 +493,7 @@ class ForceDecimalSize extends Command
/** @var Transaction $item */ /** @var Transaction $item */
foreach ($result as $item) { foreach ($result as $item) {
$value = $item->amount; $value = $item->amount;
if ('' === $value) { if ('' === $value) {
continue; continue;
} }
@ -506,7 +506,7 @@ class ForceDecimalSize extends Command
// select all transactions with this FOREIGN currency and issue. // select all transactions with this FOREIGN currency and issue.
/** @var Builder $query */ /** @var Builder $query */
$query = Transaction::where('foreign_currency_id', $currency->id)->where( $query = Transaction::where('foreign_currency_id', $currency->id)->where(
DB::raw(sprintf('CAST(foreign_amount as %s)', $this->cast)), // @phpstan-ignore-line DB::raw(sprintf('CAST(foreign_amount as %s)', $this->cast)), // @phpstan-ignore-line
$this->operator, $this->operator,
DB::raw(sprintf($this->regularExpression, $currency->decimal_places)) DB::raw(sprintf($this->regularExpression, $currency->decimal_places))
@ -521,7 +521,7 @@ class ForceDecimalSize extends Command
/** @var Transaction $item */ /** @var Transaction $item */
foreach ($result as $item) { foreach ($result as $item) {
$value = $item->foreign_amount; $value = $item->foreign_amount;
if (null === $value) { if (null === $value) {
continue; continue;
} }

View File

@ -42,7 +42,7 @@ class ForceMigration extends Command
protected $description = 'This command will force-run all database migrations.'; protected $description = 'This command will force-run all database migrations.';
protected $signature = 'firefly-iii:force-migrations protected $signature = 'firefly-iii:force-migrations
{--user=1 : The user ID.} {--user=1 : The user ID.}
{--token= : The user\'s access token.}'; {--token= : The user\'s access token.}';

View File

@ -33,7 +33,7 @@ class OutputVersion extends Command
{ {
protected $description = 'Outputs the Firefly III version'; protected $description = 'Outputs the Firefly III version';
protected $signature = 'firefly-iii:output-version'; protected $signature = 'firefly-iii:output-version';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -37,7 +37,7 @@ class ScanAttachments extends Command
protected $description = 'Rescan all attachments and re-set the correct MD5 hash and mime.'; protected $description = 'Rescan all attachments and re-set the correct MD5 hash and mime.';
protected $signature = 'firefly-iii:scan-attachments'; protected $signature = 'firefly-iii:scan-attachments';
/** /**
* Execute the console command. * Execute the console command.
@ -63,7 +63,7 @@ class ScanAttachments extends Command
app('log')->error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage())); app('log')->error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage()));
$decryptedContent = $encryptedContent; $decryptedContent = $encryptedContent;
} }
$tempFileName = tempnam(sys_get_temp_dir(), 'FireflyIII'); $tempFileName = tempnam(sys_get_temp_dir(), 'FireflyIII');
if (false === $tempFileName) { if (false === $tempFileName) {
app('log')->error(sprintf('Could not create temporary file for attachment #%d', $attachment->id)); app('log')->error(sprintf('Could not create temporary file for attachment #%d', $attachment->id));

View File

@ -36,7 +36,7 @@ class SetLatestVersion extends Command
protected $description = 'Set latest version in DB.'; protected $description = 'Set latest version in DB.';
protected $signature = 'firefly-iii:set-latest-version {--james-is-cool}'; protected $signature = 'firefly-iii:set-latest-version {--james-is-cool}';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -35,7 +35,7 @@ class UpgradeFireflyInstructions extends Command
protected $description = 'Instructions in case of upgrade trouble.'; protected $description = 'Instructions in case of upgrade trouble.';
protected $signature = 'firefly:instructions {task}'; protected $signature = 'firefly:instructions {task}';
/** /**
* Execute the console command. * Execute the console command.
@ -61,8 +61,8 @@ class UpgradeFireflyInstructions extends Command
$version = (string)config('firefly.version'); $version = (string)config('firefly.version');
/** @var array $config */ /** @var array $config */
$config = config('upgrade.text.upgrade'); $config = config('upgrade.text.upgrade');
$text = ''; $text = '';
/** @var string $compare */ /** @var string $compare */
foreach (array_keys($config) as $compare) { foreach (array_keys($config) as $compare) {
@ -99,8 +99,8 @@ class UpgradeFireflyInstructions extends Command
*/ */
private function showLogo(): void private function showLogo(): void
{ {
$today = date('m-d'); $today = date('m-d');
$month = date('m'); $month = date('m');
// variation in colors and effects just because I can! // variation in colors and effects just because I can!
// default is Ukraine flag: // default is Ukraine flag:
$colors = ['blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'default', 'default']; $colors = ['blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'default', 'default'];
@ -171,8 +171,8 @@ class UpgradeFireflyInstructions extends Command
$version = (string)config('firefly.version'); $version = (string)config('firefly.version');
/** @var array $config */ /** @var array $config */
$config = config('upgrade.text.install'); $config = config('upgrade.text.install');
$text = ''; $text = '';
/** @var string $compare */ /** @var string $compare */
foreach (array_keys($config) as $compare) { foreach (array_keys($config) as $compare) {

View File

@ -38,7 +38,7 @@ class VerifySecurityAlerts extends Command
protected $description = 'Verify security alerts'; protected $description = 'Verify security alerts';
protected $signature = 'firefly-iii:verify-security-alerts'; protected $signature = 'firefly-iii:verify-security-alerts';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -50,7 +50,7 @@ class ApplyRules extends Command
protected $description = 'This command will apply your rules and rule groups on a selection of your transactions.'; protected $description = 'This command will apply your rules and rule groups on a selection of your transactions.';
protected $signature protected $signature
= 'firefly-iii:apply-rules = 'firefly-iii:apply-rules
{--user=1 : The user ID.} {--user=1 : The user ID.}
{--token= : The user\'s access token.} {--token= : The user\'s access token.}
{--accounts= : A comma-separated list of asset accounts or liabilities to apply your rules to.} {--accounts= : A comma-separated list of asset accounts or liabilities to apply your rules to.}
@ -77,7 +77,7 @@ class ApplyRules extends Command
*/ */
public function handle(): int public function handle(): int
{ {
$start = microtime(true); $start = microtime(true);
$this->stupidLaravel(); $this->stupidLaravel();
if (!$this->verifyAccessToken()) { if (!$this->verifyAccessToken()) {
$this->friendlyError('Invalid access token.'); $this->friendlyError('Invalid access token.');
@ -89,19 +89,19 @@ class ApplyRules extends Command
$this->ruleRepository->setUser($this->getUser()); $this->ruleRepository->setUser($this->getUser());
$this->ruleGroupRepository->setUser($this->getUser()); $this->ruleGroupRepository->setUser($this->getUser());
$result = $this->verifyInput(); $result = $this->verifyInput();
if (false === $result) { if (false === $result) {
return 1; return 1;
} }
$this->allRules = $this->option('all_rules'); $this->allRules = $this->option('all_rules');
// always get all the rules of the user. // always get all the rules of the user.
$this->grabAllRules(); $this->grabAllRules();
// loop all groups and rules and indicate if they're included: // loop all groups and rules and indicate if they're included:
$rulesToApply = $this->getRulesToApply(); $rulesToApply = $this->getRulesToApply();
$count = $rulesToApply->count(); $count = $rulesToApply->count();
if (0 === $count) { if (0 === $count) {
$this->friendlyError('No rules or rule groups have been included.'); $this->friendlyError('No rules or rule groups have been included.');
$this->friendlyWarning('Make a selection using:'); $this->friendlyWarning('Make a selection using:');
@ -114,7 +114,7 @@ class ApplyRules extends Command
// create new rule engine: // create new rule engine:
/** @var RuleEngineInterface $ruleEngine */ /** @var RuleEngineInterface $ruleEngine */
$ruleEngine = app(RuleEngineInterface::class); $ruleEngine = app(RuleEngineInterface::class);
$ruleEngine->setRules($rulesToApply); $ruleEngine->setRules($rulesToApply);
$ruleEngine->setUser($this->getUser()); $ruleEngine->setUser($this->getUser());
@ -123,7 +123,7 @@ class ApplyRules extends Command
foreach ($this->accounts as $account) { foreach ($this->accounts as $account) {
$filterAccountList[] = $account->id; $filterAccountList[] = $account->id;
} }
$list = implode(',', $filterAccountList); $list = implode(',', $filterAccountList);
$ruleEngine->addOperator(['type' => 'account_id', 'value' => $list]); $ruleEngine->addOperator(['type' => 'account_id', 'value' => $list]);
// add the date as a filter: // add the date as a filter:
@ -137,7 +137,7 @@ class ApplyRules extends Command
$ruleEngine->fire(); $ruleEngine->fire();
$this->friendlyLine(''); $this->friendlyLine('');
$end = round(microtime(true) - $start, 2); $end = round(microtime(true) - $start, 2);
$this->friendlyPositive(sprintf('Done in %s seconds!', $end)); $this->friendlyPositive(sprintf('Done in %s seconds!', $end));
return 0; return 0;
@ -187,14 +187,14 @@ class ApplyRules extends Command
*/ */
private function verifyInputAccounts(): bool private function verifyInputAccounts(): bool
{ {
$accountString = $this->option('accounts'); $accountString = $this->option('accounts');
if (null === $accountString || '' === $accountString) { if (null === $accountString || '' === $accountString) {
$this->friendlyError('Please use the --accounts option to indicate the accounts to apply rules to.'); $this->friendlyError('Please use the --accounts option to indicate the accounts to apply rules to.');
return false; return false;
} }
$finalList = new Collection(); $finalList = new Collection();
$accountList = explode(',', $accountString); $accountList = explode(',', $accountString);
/** @var AccountRepositoryInterface $accountRepository */ /** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class); $accountRepository = app(AccountRepositoryInterface::class);
@ -212,7 +212,7 @@ class ApplyRules extends Command
return false; return false;
} }
$this->accounts = $finalList; $this->accounts = $finalList;
return true; return true;
} }
@ -224,7 +224,7 @@ class ApplyRules extends Command
// can be empty. // can be empty.
return true; return true;
} }
$ruleGroupList = explode(',', $ruleGroupString); $ruleGroupList = explode(',', $ruleGroupString);
foreach ($ruleGroupList as $ruleGroupId) { foreach ($ruleGroupList as $ruleGroupId) {
$ruleGroup = $this->ruleGroupRepository->find((int)$ruleGroupId); $ruleGroup = $this->ruleGroupRepository->find((int)$ruleGroupId);
@ -246,7 +246,7 @@ class ApplyRules extends Command
// can be empty. // can be empty.
return true; return true;
} }
$ruleList = explode(',', $ruleString); $ruleList = explode(',', $ruleString);
foreach ($ruleList as $ruleId) { foreach ($ruleList as $ruleId) {
$rule = $this->ruleRepository->find((int)$ruleId); $rule = $this->ruleRepository->find((int)$ruleId);
@ -264,13 +264,13 @@ class ApplyRules extends Command
private function verifyInputDates(): void private function verifyInputDates(): void
{ {
// parse start date. // parse start date.
$inputStart = today(config('app.timezone'))->startOfMonth(); $inputStart = today(config('app.timezone'))->startOfMonth();
$startString = $this->option('start_date'); $startString = $this->option('start_date');
if (null === $startString) { if (null === $startString) {
/** @var JournalRepositoryInterface $repository */ /** @var JournalRepositoryInterface $repository */
$repository = app(JournalRepositoryInterface::class); $repository = app(JournalRepositoryInterface::class);
$repository->setUser($this->getUser()); $repository->setUser($this->getUser());
$first = $repository->firstNull(); $first = $repository->firstNull();
if (null !== $first) { if (null !== $first) {
$inputStart = $first->date; $inputStart = $first->date;
} }
@ -280,8 +280,8 @@ class ApplyRules extends Command
} }
// parse end date // parse end date
$inputEnd = today(config('app.timezone')); $inputEnd = today(config('app.timezone'));
$endString = $this->option('end_date'); $endString = $this->option('end_date');
if (null !== $endString && '' !== $endString) { if (null !== $endString && '' !== $endString) {
$inputEnd = Carbon::createFromFormat('Y-m-d', $endString); $inputEnd = Carbon::createFromFormat('Y-m-d', $endString);
} }

View File

@ -43,14 +43,14 @@ class Cron extends Command
protected $description = 'Runs all Firefly III cron-job related commands. Configure a cron job according to the official Firefly III documentation.'; protected $description = 'Runs all Firefly III cron-job related commands. Configure a cron job according to the official Firefly III documentation.';
protected $signature = 'firefly-iii:cron protected $signature = 'firefly-iii:cron
{--F|force : Force the cron job(s) to execute.} {--F|force : Force the cron job(s) to execute.}
{--date= : Set the date in YYYY-MM-DD to make Firefly III think that\'s the current date.} {--date= : Set the date in YYYY-MM-DD to make Firefly III think that\'s the current date.}
'; ';
public function handle(): int public function handle(): int
{ {
$date = null; $date = null;
try { try {
$date = new Carbon($this->option('date')); $date = new Carbon($this->option('date'));

View File

@ -44,8 +44,8 @@ class AccountCurrencies extends Command
public const string CONFIG_NAME = '480_account_currencies'; public const string CONFIG_NAME = '480_account_currencies';
protected $description = 'Give all accounts proper currency info.'; protected $description = 'Give all accounts proper currency info.';
protected $signature = 'firefly-iii:account-currencies {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:account-currencies {--F|force : Force the execution of this command.}';
private AccountRepositoryInterface $accountRepos; private AccountRepositoryInterface $accountRepos;
private int $count; private int $count;
private UserRepositoryInterface $userRepos; private UserRepositoryInterface $userRepos;
@ -109,7 +109,7 @@ class AccountCurrencies extends Command
private function updateCurrenciesForUser(User $user): void private function updateCurrenciesForUser(User $user): void
{ {
$this->accountRepos->setUser($user); $this->accountRepos->setUser($user);
$accounts = $this->accountRepos->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET]); $accounts = $this->accountRepos->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET]);
// get user's currency preference: // get user's currency preference:
$defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($user->userGroup); $defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($user->userGroup);

View File

@ -36,9 +36,9 @@ class AppendBudgetLimitPeriods extends Command
public const string CONFIG_NAME = '550_budget_limit_periods'; public const string CONFIG_NAME = '550_budget_limit_periods';
protected $description = 'Append budget limits with their (estimated) timeframe.'; protected $description = 'Append budget limits with their (estimated) timeframe.';
protected $signature = 'firefly-iii:budget-limit-periods {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:budget-limit-periods {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -76,7 +76,7 @@ class AppendBudgetLimitPeriods extends Command
private function fixLimit(BudgetLimit $limit): void private function fixLimit(BudgetLimit $limit): void
{ {
$period = $this->getLimitPeriod($limit); $period = $this->getLimitPeriod($limit);
if (null === $period) { if (null === $period) {
$message = sprintf( $message = sprintf(
@ -93,7 +93,7 @@ class AppendBudgetLimitPeriods extends Command
$limit->period = $period; $limit->period = $period;
$limit->save(); $limit->save();
$msg = sprintf( $msg = sprintf(
'Budget limit #%d (%s - %s) period is "%s".', 'Budget limit #%d (%s - %s) period is "%s".',
$limit->id, $limit->id,
$limit->start_date->format('Y-m-d'), $limit->start_date->format('Y-m-d'),

View File

@ -40,9 +40,9 @@ class BackToJournals extends Command
public const string CONFIG_NAME = '480_back_to_journals'; public const string CONFIG_NAME = '480_back_to_journals';
protected $description = 'Move meta data back to journals, not individual transactions.'; protected $description = 'Move meta data back to journals, not individual transactions.';
protected $signature = 'firefly-iii:back-to-journals {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:back-to-journals {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -126,7 +126,7 @@ class BackToJournals extends Command
{ {
// grab category from first transaction // grab category from first transaction
/** @var null|Transaction $transaction */ /** @var null|Transaction $transaction */
$transaction = $journal->transactions->first(); $transaction = $journal->transactions->first();
if (null === $transaction) { if (null === $transaction) {
$this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id)); $this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id));
@ -134,7 +134,7 @@ class BackToJournals extends Command
} }
/** @var null|Budget $budget */ /** @var null|Budget $budget */
$budget = $transaction->budgets->first(); $budget = $transaction->budgets->first();
/** @var null|Budget $journalBudget */ /** @var null|Budget $journalBudget */
$journalBudget = $journal->budgets->first(); $journalBudget = $journal->budgets->first();
@ -159,7 +159,7 @@ class BackToJournals extends Command
$journals = new Collection(); $journals = new Collection();
$allIds = $this->getIdsForCategories(); $allIds = $this->getIdsForCategories();
$chunks = array_chunk($allIds, 500); $chunks = array_chunk($allIds, 500);
foreach ($chunks as $chunk) { foreach ($chunks as $chunk) {
$collected = TransactionJournal::whereIn('id', $chunk)->with(['transactions', 'categories', 'transactions.categories'])->get(); $collected = TransactionJournal::whereIn('id', $chunk)->with(['transactions', 'categories', 'transactions.categories'])->get();
$journals = $journals->merge($collected); $journals = $journals->merge($collected);
@ -192,7 +192,7 @@ class BackToJournals extends Command
{ {
// grab category from first transaction // grab category from first transaction
/** @var null|Transaction $transaction */ /** @var null|Transaction $transaction */
$transaction = $journal->transactions->first(); $transaction = $journal->transactions->first();
if (null === $transaction) { if (null === $transaction) {
$this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id)); $this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id));
@ -200,7 +200,7 @@ class BackToJournals extends Command
} }
/** @var null|Category $category */ /** @var null|Category $category */
$category = $transaction->categories->first(); $category = $transaction->categories->first();
/** @var null|Category $journalCategory */ /** @var null|Category $journalCategory */
$journalCategory = $journal->categories->first(); $journalCategory = $journal->categories->first();

View File

@ -39,9 +39,9 @@ class BudgetLimitCurrency extends Command
public const string CONFIG_NAME = '480_bl_currency'; public const string CONFIG_NAME = '480_bl_currency';
protected $description = 'Give budget limits a currency'; protected $description = 'Give budget limits a currency';
protected $signature = 'firefly-iii:bl-currency {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:bl-currency {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -38,8 +38,8 @@ class CCLiabilities extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_cc_liabilities'; public const string CONFIG_NAME = '480_cc_liabilities';
protected $description = 'Convert old credit card liabilities.'; protected $description = 'Convert old credit card liabilities.';
protected $signature = 'firefly-iii:cc-liabilities {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:cc-liabilities {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -119,8 +119,8 @@ class DecryptDatabase extends Command
if (null === $original) { if (null === $original) {
return; return;
} }
$id = (int)$row->id; $id = (int)$row->id;
$value = ''; $value = '';
try { try {
$value = $this->tryDecrypt($original); $value = $this->tryDecrypt($original);

View File

@ -36,7 +36,7 @@ class FixPostgresSequences extends Command
protected $description = 'Fixes issues with PostgreSQL sequences.'; protected $description = 'Fixes issues with PostgreSQL sequences.';
protected $signature = 'firefly-iii:fix-pgsql-sequences'; protected $signature = 'firefly-iii:fix-pgsql-sequences';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -38,9 +38,9 @@ class MigrateAttachments extends Command
public const string CONFIG_NAME = '480_migrate_attachments'; public const string CONFIG_NAME = '480_migrate_attachments';
protected $description = 'Migrates attachment meta-data.'; protected $description = 'Migrates attachment meta-data.';
protected $signature = 'firefly-iii:migrate-attachments {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:migrate-attachments {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -49,7 +49,7 @@ class MigrateAttachments extends Command
*/ */
public function handle(): int public function handle(): int
{ {
$start = microtime(true); $start = microtime(true);
if ($this->isExecuted() && true !== $this->option('force')) { if ($this->isExecuted() && true !== $this->option('force')) {
$this->friendlyInfo('This command has already been executed.'); $this->friendlyInfo('This command has already been executed.');
@ -65,12 +65,12 @@ class MigrateAttachments extends Command
$attDescription = (string)$att->description; $attDescription = (string)$att->description;
if ('' !== $attDescription) { if ('' !== $attDescription) {
// find or create note: // find or create note:
$note = $att->notes()->first(); $note = $att->notes()->first();
if (null === $note) { if (null === $note) {
$note = new Note(); $note = new Note();
$note->noteable()->associate($att); $note->noteable()->associate($att);
} }
$note->text = $attDescription; $note->text = $attDescription;
$note->save(); $note->save();
// clear description: // clear description:
@ -87,7 +87,7 @@ class MigrateAttachments extends Command
if (0 !== $count) { if (0 !== $count) {
$this->friendlyInfo(sprintf('Updated %d attachment(s).', $count)); $this->friendlyInfo(sprintf('Updated %d attachment(s).', $count));
} }
$end = round(microtime(true) - $start, 2); $end = round(microtime(true) - $start, 2);
$this->friendlyInfo(sprintf('Migrated attachment notes in %s seconds.', $end)); $this->friendlyInfo(sprintf('Migrated attachment notes in %s seconds.', $end));
$this->markAsExecuted(); $this->markAsExecuted();

View File

@ -37,9 +37,9 @@ class MigrateJournalNotes extends Command
public const string CONFIG_NAME = '480_migrate_notes'; public const string CONFIG_NAME = '480_migrate_notes';
protected $description = 'Migrate notes for transaction journals.'; protected $description = 'Migrate notes for transaction journals.';
protected $signature = 'firefly-iii:migrate-notes {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:migrate-notes {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -59,8 +59,8 @@ class MigrateJournalNotes extends Command
/** @var TransactionJournalMeta $meta */ /** @var TransactionJournalMeta $meta */
foreach ($set as $meta) { foreach ($set as $meta) {
$journal = $meta->transactionJournal; $journal = $meta->transactionJournal;
$note = $journal->notes()->first(); $note = $journal->notes()->first();
if (null === $note) { if (null === $note) {
$note = new Note(); $note = new Note();
$note->noteable()->associate($journal); $note->noteable()->associate($journal);
@ -81,7 +81,7 @@ class MigrateJournalNotes extends Command
$this->friendlyInfo(sprintf('Migrated %d note(s).', $count)); $this->friendlyInfo(sprintf('Migrated %d note(s).', $count));
} }
$end = round(microtime(true) - $start, 2); $end = round(microtime(true) - $start, 2);
$this->friendlyInfo(sprintf('Migrated notes in %s seconds.', $end)); $this->friendlyInfo(sprintf('Migrated notes in %s seconds.', $end));
$this->markAsExecuted(); $this->markAsExecuted();

View File

@ -39,9 +39,9 @@ class MigrateRecurrenceMeta extends Command
public const string CONFIG_NAME = '481_migrate_recurrence_meta'; public const string CONFIG_NAME = '481_migrate_recurrence_meta';
protected $description = 'Migrate recurrence meta data'; protected $description = 'Migrate recurrence meta data';
protected $signature = 'firefly-iii:migrate-recurrence-meta {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:migrate-recurrence-meta {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -79,7 +79,7 @@ class MigrateRecurrenceMeta extends Command
private function migrateMetaData(): int private function migrateMetaData(): int
{ {
$count = 0; $count = 0;
// get all recurrence meta data: // get all recurrence meta data:
$collection = RecurrenceMeta::with('recurrence')->get(); $collection = RecurrenceMeta::with('recurrence')->get();
@ -94,7 +94,7 @@ class MigrateRecurrenceMeta extends Command
private function migrateEntry(RecurrenceMeta $meta): int private function migrateEntry(RecurrenceMeta $meta): int
{ {
/** @var null|Recurrence $recurrence */ /** @var null|Recurrence $recurrence */
$recurrence = $meta->recurrence; $recurrence = $meta->recurrence;
if (null === $recurrence) { if (null === $recurrence) {
return 0; return 0;
} }
@ -102,7 +102,7 @@ class MigrateRecurrenceMeta extends Command
if (null === $firstTransaction) { if (null === $firstTransaction) {
return 0; return 0;
} }
$value = $meta->value; $value = $meta->value;
if ('tags' === $meta->name) { if ('tags' === $meta->name) {
$array = explode(',', $meta->value); $array = explode(',', $meta->value);

View File

@ -25,9 +25,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Upgrade; namespace FireflyIII\Console\Commands\Upgrade;
use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\Recurrence;
use FireflyIII\Models\RecurrenceTransaction;
use FireflyIII\Models\TransactionType;
use Illuminate\Console\Command; use Illuminate\Console\Command;
/** /**
@ -39,9 +36,9 @@ class MigrateRecurrenceType extends Command
public const string CONFIG_NAME = '550_migrate_recurrence_type'; public const string CONFIG_NAME = '550_migrate_recurrence_type';
protected $description = 'Migrate transaction type of recurring transaction.'; protected $description = 'Migrate transaction type of recurring transaction.';
protected $signature = 'firefly-iii:migrate-recurrence-type {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:migrate-recurrence-type {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -66,7 +63,6 @@ class MigrateRecurrenceType extends Command
return (bool)$configVar?->data; return (bool)$configVar?->data;
} }
private function markAsExecuted(): void private function markAsExecuted(): void
{ {
app('fireflyconfig')->set(self::CONFIG_NAME, true); app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@ -38,9 +38,9 @@ class MigrateTagLocations extends Command
public const string CONFIG_NAME = '500_migrate_tag_locations'; public const string CONFIG_NAME = '500_migrate_tag_locations';
protected $description = 'Migrate tag locations.'; protected $description = 'Migrate tag locations.';
protected $signature = 'firefly-iii:migrate-tag-locations {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:migrate-tag-locations {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -94,9 +94,9 @@ class MigrateTagLocations extends Command
$location->locatable()->associate($tag); $location->locatable()->associate($tag);
$location->save(); $location->save();
$tag->longitude = null; $tag->longitude = null;
$tag->latitude = null; $tag->latitude = null;
$tag->zoomLevel = null; $tag->zoomLevel = null;
$tag->save(); $tag->save();
} }

View File

@ -47,8 +47,8 @@ class MigrateToGroups extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_migrated_to_groups'; public const string CONFIG_NAME = '480_migrated_to_groups';
protected $description = 'Migrates a pre-4.7.8 transaction structure to the 4.7.8+ transaction structure.'; protected $description = 'Migrates a pre-4.7.8 transaction structure to the 4.7.8+ transaction structure.';
protected $signature = 'firefly-iii:migrate-to-groups {--F|force : Force the migration, even if it fired before.}'; protected $signature = 'firefly-iii:migrate-to-groups {--F|force : Force the migration, even if it fired before.}';
private JournalCLIRepositoryInterface $cliRepository; private JournalCLIRepositoryInterface $cliRepository;
private int $count; private int $count;
private TransactionGroupFactory $groupFactory; private TransactionGroupFactory $groupFactory;
@ -157,7 +157,7 @@ class MigrateToGroups extends Command
$data['transactions'][] = $this->generateTransaction($journal, $transaction); $data['transactions'][] = $this->generateTransaction($journal, $transaction);
} }
app('log')->debug(sprintf('Now calling transaction journal factory (%d transactions in array)', count($data['transactions']))); app('log')->debug(sprintf('Now calling transaction journal factory (%d transactions in array)', count($data['transactions'])));
$group = $this->groupFactory->create($data); $group = $this->groupFactory->create($data);
app('log')->debug('Done calling transaction journal factory'); app('log')->debug('Done calling transaction journal factory');
// delete the old transaction journal. // delete the old transaction journal.
@ -215,7 +215,7 @@ class MigrateToGroups extends Command
private function generateTransaction(TransactionJournal $journal, Transaction $transaction): array private function generateTransaction(TransactionJournal $journal, Transaction $transaction): array
{ {
app('log')->debug(sprintf('Now going to add transaction #%d to the array.', $transaction->id)); app('log')->debug(sprintf('Now going to add transaction #%d to the array.', $transaction->id));
$opposingTr = $this->findOpposingTransaction($journal, $transaction); $opposingTr = $this->findOpposingTransaction($journal, $transaction);
if (null === $opposingTr) { if (null === $opposingTr) {
$this->friendlyError( $this->friendlyError(
@ -256,8 +256,8 @@ class MigrateToGroups extends Command
$invoiceDate = $this->cliRepository->getMetaDate($journal, 'invoice_date'); $invoiceDate = $this->cliRepository->getMetaDate($journal, 'invoice_date');
// overrule journal category with transaction category. // overrule journal category with transaction category.
$budgetId = $this->getTransactionBudget($transaction, $opposingTr) ?? $budgetId; $budgetId = $this->getTransactionBudget($transaction, $opposingTr) ?? $budgetId;
$categoryId = $this->getTransactionCategory($transaction, $opposingTr) ?? $categoryId; $categoryId = $this->getTransactionCategory($transaction, $opposingTr) ?? $categoryId;
return [ return [
'type' => strtolower($journal->transactionType->type), 'type' => strtolower($journal->transactionType->type),

View File

@ -44,9 +44,9 @@ class MigrateToRules extends Command
public const string CONFIG_NAME = '480_bills_to_rules'; public const string CONFIG_NAME = '480_bills_to_rules';
protected $description = 'Migrate bills to rules.'; protected $description = 'Migrate bills to rules.';
protected $signature = 'firefly-iii:bills-to-rules {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:bills-to-rules {--F|force : Force the execution of this command.}';
private BillRepositoryInterface $billRepository; private BillRepositoryInterface $billRepository;
private int $count; private int $count;
private RuleGroupRepositoryInterface $ruleGroupRepository; private RuleGroupRepositoryInterface $ruleGroupRepository;
@ -137,7 +137,7 @@ class MigrateToRules extends Command
] ]
); );
} }
$bills = $this->billRepository->getBills(); $bills = $this->billRepository->getBills();
/** @var Bill $bill */ /** @var Bill $bill */
foreach ($bills as $bill) { foreach ($bills as $bill) {
@ -153,8 +153,8 @@ class MigrateToRules extends Command
$languageString = null !== $language->data && !is_array($language->data) ? (string)$language->data : 'en_US'; $languageString = null !== $language->data && !is_array($language->data) ? (string)$language->data : 'en_US';
// get match thing: // get match thing:
$match = implode(' ', explode(',', $bill->match)); $match = implode(' ', explode(',', $bill->match));
$newRule = [ $newRule = [
'rule_group_id' => $ruleGroup->id, 'rule_group_id' => $ruleGroup->id,
'active' => true, 'active' => true,
'strict' => false, 'strict' => false,
@ -197,7 +197,7 @@ class MigrateToRules extends Command
$this->ruleRepository->store($newRule); $this->ruleRepository->store($newRule);
// update bill: // update bill:
$newBillData = [ $newBillData = [
'currency_id' => $bill->transaction_currency_id, 'currency_id' => $bill->transaction_currency_id,
'name' => $bill->name, 'name' => $bill->name,
'match' => 'MIGRATED_TO_RULES', 'match' => 'MIGRATED_TO_RULES',

View File

@ -43,8 +43,8 @@ class OtherCurrenciesCorrections extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_other_currencies'; public const string CONFIG_NAME = '480_other_currencies';
protected $description = 'Update all journal currency information.'; protected $description = 'Update all journal currency information.';
protected $signature = 'firefly-iii:other-currencies {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:other-currencies {--F|force : Force the execution of this command.}';
private array $accountCurrencies; private array $accountCurrencies;
private AccountRepositoryInterface $accountRepos; private AccountRepositoryInterface $accountRepos;
private JournalCLIRepositoryInterface $cliRepos; private JournalCLIRepositoryInterface $cliRepos;
@ -120,7 +120,7 @@ class OtherCurrenciesCorrections extends Command
$this->journalRepos->setUser($journal->user); $this->journalRepos->setUser($journal->user);
$this->cliRepos->setUser($journal->user); $this->cliRepos->setUser($journal->user);
$leadTransaction = $this->getLeadTransaction($journal); $leadTransaction = $this->getLeadTransaction($journal);
if (null === $leadTransaction) { if (null === $leadTransaction) {
$this->friendlyError(sprintf('Could not reliably determine which transaction is in the lead for transaction journal #%d.', $journal->id)); $this->friendlyError(sprintf('Could not reliably determine which transaction is in the lead for transaction journal #%d.', $journal->id));
@ -128,8 +128,8 @@ class OtherCurrenciesCorrections extends Command
return; return;
} }
$account = $leadTransaction->account; $account = $leadTransaction->account;
$currency = $this->getCurrency($account); $currency = $this->getCurrency($account);
if (null === $currency) { if (null === $currency) {
$this->friendlyError( $this->friendlyError(
sprintf( sprintf(
@ -217,14 +217,14 @@ class OtherCurrenciesCorrections extends Command
private function getCurrency(Account $account): ?TransactionCurrency private function getCurrency(Account $account): ?TransactionCurrency
{ {
$accountId = $account->id; $accountId = $account->id;
if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) { if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) {
return null; return null;
} }
if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) { if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) {
return $this->accountCurrencies[$accountId]; return $this->accountCurrencies[$accountId];
} }
$currency = $this->accountRepos->getAccountCurrency($account); $currency = $this->accountRepos->getAccountCurrency($account);
if (null === $currency) { if (null === $currency) {
$this->accountCurrencies[$accountId] = 0; $this->accountCurrencies[$accountId] = 0;

View File

@ -37,9 +37,9 @@ class RenameAccountMeta extends Command
public const string CONFIG_NAME = '480_rename_account_meta'; public const string CONFIG_NAME = '480_rename_account_meta';
protected $description = 'Rename account meta-data to new format.'; protected $description = 'Rename account meta-data to new format.';
protected $signature = 'firefly-iii:rename-account-meta {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:rename-account-meta {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.

View File

@ -39,8 +39,8 @@ class TransactionIdentifier extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_transaction_identifier'; public const string CONFIG_NAME = '480_transaction_identifier';
protected $description = 'Fixes transaction identifiers.'; protected $description = 'Fixes transaction identifiers.';
protected $signature = 'firefly-iii:transaction-identifiers {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:transaction-identifiers {--F|force : Force the execution of this command.}';
private JournalCLIRepositoryInterface $cliRepository; private JournalCLIRepositoryInterface $cliRepository;
private int $count; private int $count;
@ -130,8 +130,8 @@ class TransactionIdentifier extends Command
$opposing->identifier = $identifier; $opposing->identifier = $identifier;
$transaction->save(); $transaction->save();
$opposing->save(); $opposing->save();
$exclude[] = $transaction->id; $exclude[] = $transaction->id;
$exclude[] = $opposing->id; $exclude[] = $opposing->id;
++$this->count; ++$this->count;
} }
++$identifier; ++$identifier;

View File

@ -41,8 +41,8 @@ class TransferCurrenciesCorrections extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_transfer_currencies'; public const string CONFIG_NAME = '480_transfer_currencies';
protected $description = 'Updates transfer currency information.'; protected $description = 'Updates transfer currency information.';
protected $signature = 'firefly-iii:transfer-currencies {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:transfer-currencies {--F|force : Force the execution of this command.}';
private array $accountCurrencies; private array $accountCurrencies;
private AccountRepositoryInterface $accountRepos; private AccountRepositoryInterface $accountRepos;
private JournalCLIRepositoryInterface $cliRepos; private JournalCLIRepositoryInterface $cliRepos;
@ -219,14 +219,14 @@ class TransferCurrenciesCorrections extends Command
private function getCurrency(Account $account): ?TransactionCurrency private function getCurrency(Account $account): ?TransactionCurrency
{ {
$accountId = $account->id; $accountId = $account->id;
if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) { if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) {
return null; return null;
} }
if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) { if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) {
return $this->accountCurrencies[$accountId]; return $this->accountCurrencies[$accountId];
} }
$currency = $this->accountRepos->getAccountCurrency($account); $currency = $this->accountRepos->getAccountCurrency($account);
if (null === $currency) { if (null === $currency) {
$this->accountCurrencies[$accountId] = 0; $this->accountCurrencies[$accountId] = 0;
@ -321,7 +321,7 @@ class TransferCurrenciesCorrections extends Command
&& null === $this->sourceTransaction->foreign_amount && null === $this->sourceTransaction->foreign_amount
&& (int)$this->sourceTransaction->transaction_currency_id !== $this->sourceCurrency->id && (int)$this->sourceTransaction->transaction_currency_id !== $this->sourceCurrency->id
) { ) {
$message = sprintf( $message = sprintf(
'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.', 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.',
$this->sourceTransaction->id, $this->sourceTransaction->id,
$this->sourceTransaction->transaction_currency_id, $this->sourceTransaction->transaction_currency_id,
@ -367,7 +367,7 @@ class TransferCurrenciesCorrections extends Command
&& null === $this->destinationTransaction->foreign_amount && null === $this->destinationTransaction->foreign_amount
&& (int)$this->destinationTransaction->transaction_currency_id !== $this->destinationCurrency->id && (int)$this->destinationTransaction->transaction_currency_id !== $this->destinationCurrency->id
) { ) {
$message = sprintf( $message = sprintf(
'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.', 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.',
$this->destinationTransaction->id, $this->destinationTransaction->id,
$this->destinationTransaction->transaction_currency_id, $this->destinationTransaction->transaction_currency_id,
@ -390,8 +390,8 @@ class TransferCurrenciesCorrections extends Command
{ {
if ($this->destinationCurrency->id === $this->sourceCurrency->id) { if ($this->destinationCurrency->id === $this->sourceCurrency->id) {
// update both transactions to match: // update both transactions to match:
$this->sourceTransaction->foreign_amount = null; $this->sourceTransaction->foreign_amount = null;
$this->sourceTransaction->foreign_currency_id = null; $this->sourceTransaction->foreign_currency_id = null;
$this->destinationTransaction->foreign_amount = null; $this->destinationTransaction->foreign_amount = null;
$this->destinationTransaction->foreign_currency_id = null; $this->destinationTransaction->foreign_currency_id = null;

View File

@ -41,9 +41,9 @@ class UpgradeCurrencyPreferences extends Command
public const string CONFIG_NAME = '610_upgrade_currency_prefs'; public const string CONFIG_NAME = '610_upgrade_currency_prefs';
protected $description = 'Upgrade user currency preferences'; protected $description = 'Upgrade user currency preferences';
protected $signature = 'firefly-iii:upgrade-currency-preferences {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:upgrade-currency-preferences {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -83,7 +83,7 @@ class UpgradeCurrencyPreferences extends Command
$this->upgradeGroupPreferences($group); $this->upgradeGroupPreferences($group);
} }
$users = User::get(); $users = User::get();
/** @var User $user */ /** @var User $user */
foreach ($users as $user) { foreach ($users as $user) {
@ -107,8 +107,8 @@ class UpgradeCurrencyPreferences extends Command
private function upgradeUserPreferences(User $user): void private function upgradeUserPreferences(User $user): void
{ {
$currencies = TransactionCurrency::get(); $currencies = TransactionCurrency::get();
$enabled = new Collection(); $enabled = new Collection();
/** @var TransactionCurrency $currency */ /** @var TransactionCurrency $currency */
foreach ($currencies as $currency) { foreach ($currencies as $currency) {

View File

@ -42,8 +42,8 @@ class UpgradeLiabilities extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '560_upgrade_liabilities'; public const string CONFIG_NAME = '560_upgrade_liabilities';
protected $description = 'Upgrade liabilities to new 5.6.0 structure.'; protected $description = 'Upgrade liabilities to new 5.6.0 structure.';
protected $signature = 'firefly-iii:upgrade-liabilities {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:upgrade-liabilities {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -102,7 +102,7 @@ class UpgradeLiabilities extends Command
private function upgradeLiability(Account $account): void private function upgradeLiability(Account $account): void
{ {
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$repository->setUser($account->user); $repository->setUser($account->user);
// get opening balance, and correct if necessary. // get opening balance, and correct if necessary.
@ -113,7 +113,7 @@ class UpgradeLiabilities extends Command
} }
// add liability direction property (if it does not yet exist!) // add liability direction property (if it does not yet exist!)
$value = $repository->getMetaValue($account, 'liability_direction'); $value = $repository->getMetaValue($account, 'liability_direction');
if (null === $value) { if (null === $value) {
/** @var AccountMetaFactory $factory */ /** @var AccountMetaFactory $factory */
$factory = app(AccountMetaFactory::class); $factory = app(AccountMetaFactory::class);

View File

@ -43,8 +43,8 @@ class UpgradeLiabilitiesEight extends Command
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '600_upgrade_liabilities'; public const string CONFIG_NAME = '600_upgrade_liabilities';
protected $description = 'Upgrade liabilities to new 6.0.0 structure.'; protected $description = 'Upgrade liabilities to new 6.0.0 structure.';
protected $signature = 'firefly-iii:liabilities-600 {--F|force : Force the execution of this command.}'; protected $signature = 'firefly-iii:liabilities-600 {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
@ -105,7 +105,7 @@ class UpgradeLiabilitiesEight extends Command
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$repository->setUser($account->user); $repository->setUser($account->user);
$direction = $repository->getMetaValue($account, 'liability_direction'); $direction = $repository->getMetaValue($account, 'liability_direction');
if ('credit' === $direction && $this->hasBadOpening($account)) { if ('credit' === $direction && $this->hasBadOpening($account)) {
$this->deleteCreditTransaction($account); $this->deleteCreditTransaction($account);
$this->reverseOpeningBalance($account); $this->reverseOpeningBalance($account);
@ -131,7 +131,7 @@ class UpgradeLiabilitiesEight extends Command
if (null === $openingJournal) { if (null === $openingJournal) {
return false; return false;
} }
$liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id) ->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $liabilityType->id) ->where('transaction_journals.transaction_type_id', $liabilityType->id)
->first(['transaction_journals.*']) ->first(['transaction_journals.*'])
@ -168,17 +168,17 @@ class UpgradeLiabilitiesEight extends Command
$openingBalanceType = TransactionType::whereType(TransactionType::OPENING_BALANCE)->first(); $openingBalanceType = TransactionType::whereType(TransactionType::OPENING_BALANCE)->first();
/** @var TransactionJournal $openingJournal */ /** @var TransactionJournal $openingJournal */
$openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') $openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id) ->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $openingBalanceType->id) ->where('transaction_journals.transaction_type_id', $openingBalanceType->id)
->first(['transaction_journals.*']) ->first(['transaction_journals.*'])
; ;
/** @var null|Transaction $source */ /** @var null|Transaction $source */
$source = $openingJournal->transactions()->where('amount', '<', 0)->first(); $source = $openingJournal->transactions()->where('amount', '<', 0)->first();
/** @var null|Transaction $dest */ /** @var null|Transaction $dest */
$dest = $openingJournal->transactions()->where('amount', '>', 0)->first(); $dest = $openingJournal->transactions()->where('amount', '>', 0)->first();
if (null !== $source && null !== $dest) { if (null !== $source && null !== $dest) {
$sourceId = $source->account_id; $sourceId = $source->account_id;
$destId = $dest->account_id; $destId = $dest->account_id;

View File

@ -39,7 +39,7 @@ trait VerifiesAccessToken
*/ */
public function getUser(): User public function getUser(): User
{ {
$userId = (int)$this->option('user'); $userId = (int)$this->option('user');
/** @var UserRepositoryInterface $repository */ /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
@ -67,12 +67,12 @@ trait VerifiesAccessToken
*/ */
protected function verifyAccessToken(): bool protected function verifyAccessToken(): bool
{ {
$userId = (int)$this->option('user'); $userId = (int)$this->option('user');
$token = (string)$this->option('token'); $token = (string)$this->option('token');
/** @var UserRepositoryInterface $repository */ /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
$user = $repository->find($userId); $user = $repository->find($userId);
if (null === $user) { if (null === $user) {
app('log')->error(sprintf('verifyAccessToken(): no such user for input "%d"', $userId)); app('log')->error(sprintf('verifyAccessToken(): no such user for input "%d"', $userId));

View File

@ -30,13 +30,13 @@ namespace FireflyIII\Enums;
enum UserRoleEnum: string enum UserRoleEnum: string
{ {
// most basic rights, cannot see other members, can see everything else. // most basic rights, cannot see other members, can see everything else.
case READ_ONLY = 'ro'; case READ_ONLY = 'ro';
// required to even USE the group properly (in this order) // required to even USE the group properly (in this order)
case MANAGE_TRANSACTIONS = 'mng_trx'; case MANAGE_TRANSACTIONS = 'mng_trx';
// required to edit, add or change categories/tags/object-groups // required to edit, add or change categories/tags/object-groups
case MANAGE_META = 'mng_meta'; case MANAGE_META = 'mng_meta';
// manage other financial objects: // manage other financial objects:
case MANAGE_BUDGETS = 'mng_budgets'; case MANAGE_BUDGETS = 'mng_budgets';
@ -49,14 +49,14 @@ enum UserRoleEnum: string
case MANAGE_CURRENCIES = 'mng_currencies'; case MANAGE_CURRENCIES = 'mng_currencies';
// view and generate reports // view and generate reports
case VIEW_REPORTS = 'view_reports'; case VIEW_REPORTS = 'view_reports';
// view memberships. needs FULL to manage them. // view memberships. needs FULL to manage them.
case VIEW_MEMBERSHIPS = 'view_memberships'; case VIEW_MEMBERSHIPS = 'view_memberships';
// everything the creator can, except remove/change original creator and delete group // everything the creator can, except remove/change original creator and delete group
case FULL = 'full'; case FULL = 'full';
// reserved for original creator // reserved for original creator
case OWNER = 'owner'; case OWNER = 'owner';
} }

View File

@ -29,9 +29,9 @@ namespace FireflyIII\Enums;
*/ */
enum WebhookTrigger: int enum WebhookTrigger: int
{ {
case STORE_TRANSACTION = 100; case STORE_TRANSACTION = 100;
// case BEFORE_STORE_TRANSACTION = 101; // case BEFORE_STORE_TRANSACTION = 101;
case UPDATE_TRANSACTION = 110; case UPDATE_TRANSACTION = 110;
// case BEFORE_UPDATE_TRANSACTION = 111; // case BEFORE_UPDATE_TRANSACTION = 111;
case DESTROY_TRANSACTION = 120; case DESTROY_TRANSACTION = 120;
// case BEFORE_DESTROY_TRANSACTION = 121; // case BEFORE_DESTROY_TRANSACTION = 121;

View File

@ -54,7 +54,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
if (null === $route) { if (null === $route) {
return parent::render($request, $e); return parent::render($request, $e);
} }
$name = $route->getName(); $name = $route->getName();
if (!auth()->check()) { if (!auth()->check()) {
return parent::render($request, $e); return parent::render($request, $e);
} }
@ -160,7 +160,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
} }
/** @var null|Account $account */ /** @var null|Account $account */
$account = $user->accounts()->with(['accountType'])->withTrashed()->find($accountId); $account = $user->accounts()->with(['accountType'])->withTrashed()->find($accountId);
if (null === $account) { if (null === $account) {
app('log')->error(sprintf('Could not find account %d, so give big fat error.', $accountId)); app('log')->error(sprintf('Could not find account %d, so give big fat error.', $accountId));
@ -189,7 +189,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
$groupId = !is_object($param) ? (int)$param : 0; $groupId = !is_object($param) ? (int)$param : 0;
/** @var null|TransactionGroup $group */ /** @var null|TransactionGroup $group */
$group = $user->transactionGroups()->withTrashed()->find($groupId); $group = $user->transactionGroups()->withTrashed()->find($groupId);
if (null === $group) { if (null === $group) {
app('log')->error(sprintf('Could not find group %d, so give big fat error.', $groupId)); app('log')->error(sprintf('Could not find group %d, so give big fat error.', $groupId));
@ -203,7 +203,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
return parent::render($request, $exception); return parent::render($request, $exception);
} }
$type = $journal->transactionType->type; $type = $journal->transactionType->type;
$request->session()->reflash(); $request->session()->reflash();
if (TransactionType::RECONCILIATION === $type) { if (TransactionType::RECONCILIATION === $type) {
@ -229,7 +229,7 @@ class GracefulNotFoundHandler extends ExceptionHandler
$attachmentId = is_object($param) ? 0 : (int)$param; $attachmentId = is_object($param) ? 0 : (int)$param;
/** @var null|Attachment $attachment */ /** @var null|Attachment $attachment */
$attachment = $user->attachments()->withTrashed()->find($attachmentId); $attachment = $user->attachments()->withTrashed()->find($attachmentId);
if (null === $attachment) { if (null === $attachment) {
app('log')->error(sprintf('Could not find attachment %d, so give big fat error.', $attachmentId)); app('log')->error(sprintf('Could not find attachment %d, so give big fat error.', $attachmentId));

View File

@ -128,7 +128,7 @@ class Handler extends ExceptionHandler
$errorCode = 500; $errorCode = 500;
$errorCode = $e instanceof MethodNotAllowedHttpException ? 405 : $errorCode; $errorCode = $e instanceof MethodNotAllowedHttpException ? 405 : $errorCode;
$isDebug = (bool) config('app.debug', false); $isDebug = (bool) config('app.debug', false);
if ($isDebug) { if ($isDebug) {
app('log')->debug(sprintf('Return JSON %s with debug.', get_class($e))); app('log')->debug(sprintf('Return JSON %s with debug.', get_class($e)));
@ -191,7 +191,7 @@ class Handler extends ExceptionHandler
return; return;
} }
$userData = [ $userData = [
'id' => 0, 'id' => 0,
'email' => 'unknown@example.com', 'email' => 'unknown@example.com',
]; ];
@ -200,9 +200,9 @@ class Handler extends ExceptionHandler
$userData['email'] = auth()->user()->email; $userData['email'] = auth()->user()->email;
} }
$headers = request()->headers->all(); $headers = request()->headers->all();
$data = [ $data = [
'class' => get_class($e), 'class' => get_class($e),
'errorMessage' => $e->getMessage(), 'errorMessage' => $e->getMessage(),
'time' => date('r'), 'time' => date('r'),
@ -219,8 +219,8 @@ class Handler extends ExceptionHandler
]; ];
// create job that will mail. // create job that will mail.
$ipAddress = request()->ip() ?? '0.0.0.0'; $ipAddress = request()->ip() ?? '0.0.0.0';
$job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data); $job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data);
dispatch($job); dispatch($job);
parent::report($e); parent::report($e);

View File

@ -50,7 +50,7 @@ final class IntervalException extends \Exception
int $code = 0, int $code = 0,
?\Throwable $previous = null ?\Throwable $previous = null
): self { ): self {
$message = sprintf( $message = sprintf(
'The periodicity %s is unknown. Choose one of available periodicity: %s', 'The periodicity %s is unknown. Choose one of available periodicity: %s',
$periodicity->name, $periodicity->name,
implode(', ', $intervals) implode(', ', $intervals)

View File

@ -73,7 +73,7 @@ class AccountFactory
{ {
app('log')->debug(sprintf('findOrCreate("%s", "%s")', $accountName, $accountType)); app('log')->debug(sprintf('findOrCreate("%s", "%s")', $accountName, $accountType));
$type = $this->accountRepository->getAccountTypeByType($accountType); $type = $this->accountRepository->getAccountTypeByType($accountType);
if (null === $type) { if (null === $type) {
throw new FireflyException(sprintf('Cannot find account type "%s"', $accountType)); throw new FireflyException(sprintf('Cannot find account type "%s"', $accountType));
} }
@ -108,13 +108,13 @@ class AccountFactory
$data['iban'] = $this->filterIban($data['iban'] ?? null); $data['iban'] = $this->filterIban($data['iban'] ?? null);
// account may exist already: // account may exist already:
$return = $this->find($data['name'], $type->type); $return = $this->find($data['name'], $type->type);
if (null !== $return) { if (null !== $return) {
return $return; return $return;
} }
$return = $this->createAccount($type, $data); $return = $this->createAccount($type, $data);
event(new StoredAccount($return)); event(new StoredAccount($return));
@ -198,11 +198,11 @@ class AccountFactory
$databaseData['virtual_balance'] = null; $databaseData['virtual_balance'] = null;
} }
// create account! // create account!
$account = Account::create($databaseData); $account = Account::create($databaseData);
Log::channel('audit')->info(sprintf('Account #%d ("%s") has been created.', $account->id, $account->name)); Log::channel('audit')->info(sprintf('Account #%d ("%s") has been created.', $account->id, $account->name));
// update meta data: // update meta data:
$data = $this->cleanMetaDataArray($account, $data); $data = $this->cleanMetaDataArray($account, $data);
$this->storeMetaData($account, $data); $this->storeMetaData($account, $data);
// create opening balance (only asset accounts) // create opening balance (only asset accounts)
@ -222,7 +222,7 @@ class AccountFactory
} }
// create notes // create notes
$notes = array_key_exists('notes', $data) ? $data['notes'] : ''; $notes = array_key_exists('notes', $data) ? $data['notes'] : '';
$this->updateNote($account, $notes); $this->updateNote($account, $notes);
// create location // create location
@ -242,10 +242,10 @@ class AccountFactory
*/ */
private function cleanMetaDataArray(Account $account, array $data): array private function cleanMetaDataArray(Account $account, array $data): array
{ {
$currencyId = array_key_exists('currency_id', $data) ? (int)$data['currency_id'] : 0; $currencyId = array_key_exists('currency_id', $data) ? (int)$data['currency_id'] : 0;
$currencyCode = array_key_exists('currency_code', $data) ? (string)$data['currency_code'] : ''; $currencyCode = array_key_exists('currency_code', $data) ? (string)$data['currency_code'] : '';
$accountRole = array_key_exists('account_role', $data) ? (string)$data['account_role'] : null; $accountRole = array_key_exists('account_role', $data) ? (string)$data['account_role'] : null;
$currency = $this->getCurrency($currencyId, $currencyCode); $currency = $this->getCurrency($currencyId, $currencyCode);
// only asset account may have a role: // only asset account may have a role:
if (AccountType::ASSET !== $account->accountType->type) { if (AccountType::ASSET !== $account->accountType->type) {
@ -263,7 +263,7 @@ class AccountFactory
private function storeMetaData(Account $account, array $data): void private function storeMetaData(Account $account, array $data): void
{ {
$fields = $this->validFields; $fields = $this->validFields;
if (AccountType::ASSET === $account->accountType->type) { if (AccountType::ASSET === $account->accountType->type) {
$fields = $this->validAssetFields; $fields = $this->validAssetFields;
} }
@ -272,8 +272,8 @@ class AccountFactory
} }
// remove currency_id if necessary. // remove currency_id if necessary.
$type = $account->accountType->type; $type = $account->accountType->type;
$list = config('firefly.valid_currency_account_types'); $list = config('firefly.valid_currency_account_types');
if (!in_array($type, $list, true)) { if (!in_array($type, $list, true)) {
$pos = array_search('currency_id', $fields, true); $pos = array_search('currency_id', $fields, true);
if (false !== $pos) { if (false !== $pos) {
@ -350,9 +350,9 @@ class AccountFactory
*/ */
private function storeOrder(Account $account, array $data): void private function storeOrder(Account $account, array $data): void
{ {
$accountType = $account->accountType->type; $accountType = $account->accountType->type;
$maxOrder = $this->accountRepository->maxOrder($accountType); $maxOrder = $this->accountRepository->maxOrder($accountType);
$order = null; $order = null;
if (!array_key_exists('order', $data)) { if (!array_key_exists('order', $data)) {
$order = $maxOrder + 1; $order = $maxOrder + 1;
} }

View File

@ -43,13 +43,13 @@ class AttachmentFactory
public function create(array $data): ?Attachment public function create(array $data): ?Attachment
{ {
// append if necessary. // append if necessary.
$model = !str_contains($data['attachable_type'], 'FireflyIII') ? sprintf('FireflyIII\\Models\\%s', $data['attachable_type']) $model = !str_contains($data['attachable_type'], 'FireflyIII') ? sprintf('FireflyIII\\Models\\%s', $data['attachable_type'])
: $data['attachable_type']; : $data['attachable_type'];
// get journal instead of transaction. // get journal instead of transaction.
if (Transaction::class === $model) { if (Transaction::class === $model) {
/** @var null|Transaction $transaction */ /** @var null|Transaction $transaction */
$transaction = $this->user->transactions()->find((int)$data['attachable_id']); $transaction = $this->user->transactions()->find((int)$data['attachable_id']);
if (null === $transaction) { if (null === $transaction) {
throw new FireflyException('Unexpectedly could not find transaction'); throw new FireflyException('Unexpectedly could not find transaction');
} }
@ -74,7 +74,7 @@ class AttachmentFactory
); );
$notes = (string)($data['notes'] ?? ''); $notes = (string)($data['notes'] ?? '');
if ('' !== $notes) { if ('' !== $notes) {
$note = new Note(); $note = new Note();
$note->noteable()->associate($attachment); $note->noteable()->associate($attachment);
$note->text = $notes; $note->text = $notes;
$note->save(); $note->save();

View File

@ -47,8 +47,8 @@ class BillFactory
public function create(array $data): ?Bill public function create(array $data): ?Bill
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__), $data); app('log')->debug(sprintf('Now in %s', __METHOD__), $data);
$factory = app(TransactionCurrencyFactory::class); $factory = app(TransactionCurrencyFactory::class);
$currency = $factory->find((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)) ?? $currency = $factory->find((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)) ??
app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup); app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
try { try {
@ -56,7 +56,7 @@ class BillFactory
$active = array_key_exists('active', $data) ? $data['active'] : 0; $active = array_key_exists('active', $data) ? $data['active'] : 0;
/** @var Bill $bill */ /** @var Bill $bill */
$bill = Bill::create( $bill = Bill::create(
[ [
'name' => $data['name'], 'name' => $data['name'],
'match' => 'MIGRATED_TO_RULES', 'match' => 'MIGRATED_TO_RULES',
@ -93,7 +93,7 @@ class BillFactory
} }
} }
// try also with ID: // try also with ID:
$objectGroupId = (int)($data['object_group_id'] ?? 0); $objectGroupId = (int)($data['object_group_id'] ?? 0);
if (0 !== $objectGroupId) { if (0 !== $objectGroupId) {
$objectGroup = $this->findObjectGroupById($objectGroupId); $objectGroup = $this->findObjectGroupById($objectGroupId);
if (null !== $objectGroup) { if (null !== $objectGroup) {

View File

@ -54,7 +54,7 @@ class PiggyBankEventFactory
return; return;
} }
app('log')->debug('Found repetition'); app('log')->debug('Found repetition');
$amount = $piggyRepos->getExactAmount($piggyBank, $repetition, $journal); $amount = $piggyRepos->getExactAmount($piggyBank, $repetition, $journal);
if (0 === bccomp($amount, '0')) { if (0 === bccomp($amount, '0')) {
app('log')->debug('Amount is zero, will not create event.'); app('log')->debug('Amount is zero, will not create event.');

View File

@ -98,7 +98,7 @@ class RecurrenceFactory
} }
$repeatUntilString = $repeatUntil?->format('Y-m-d'); $repeatUntilString = $repeatUntil?->format('Y-m-d');
$recurrence = new Recurrence( $recurrence = new Recurrence(
[ [
'user_id' => $this->user->id, 'user_id' => $this->user->id,
'user_group_id' => $this->user->user_group_id, 'user_group_id' => $this->user->user_group_id,

View File

@ -36,11 +36,11 @@ class TagFactory
public function findOrCreate(string $tag): ?Tag public function findOrCreate(string $tag): ?Tag
{ {
$tag = trim($tag); $tag = trim($tag);
app('log')->debug(sprintf('Now in TagFactory::findOrCreate("%s")', $tag)); app('log')->debug(sprintf('Now in TagFactory::findOrCreate("%s")', $tag));
/** @var null|Tag $dbTag */ /** @var null|Tag $dbTag */
$dbTag = $this->user->tags()->where('tag', $tag)->first(); $dbTag = $this->user->tags()->where('tag', $tag)->first();
if (null !== $dbTag) { if (null !== $dbTag) {
app('log')->debug(sprintf('Tag exists (#%d), return it.', $dbTag->id)); app('log')->debug(sprintf('Tag exists (#%d), return it.', $dbTag->id));
@ -84,7 +84,7 @@ class TagFactory
]; ];
/** @var null|Tag $tag */ /** @var null|Tag $tag */
$tag = Tag::create($array); $tag = Tag::create($array);
if (null !== $tag && null !== $latitude && null !== $longitude) { if (null !== $tag && null !== $latitude && null !== $longitude) {
// create location object. // create location object.
$location = new Location(); $location = new Location();

View File

@ -43,7 +43,7 @@ class TransactionCurrencyFactory
$data['decimal_places'] = (int)$data['decimal_places']; $data['decimal_places'] = (int)$data['decimal_places'];
// if the code already exists (deleted) // if the code already exists (deleted)
// force delete it and then create the transaction: // force delete it and then create the transaction:
$count = TransactionCurrency::withTrashed()->whereCode($data['code'])->count(); $count = TransactionCurrency::withTrashed()->whereCode($data['code'])->count();
if (1 === $count) { if (1 === $count) {
$old = TransactionCurrency::withTrashed()->whereCode($data['code'])->first(); $old = TransactionCurrency::withTrashed()->whereCode($data['code'])->first();
$old->forceDelete(); $old->forceDelete();

View File

@ -221,7 +221,7 @@ class TransactionFactory
} }
app('log')->debug('Will update account with IBAN information.'); app('log')->debug('Will update account with IBAN information.');
$service = app(AccountUpdateService::class); $service = app(AccountUpdateService::class);
$service->update($this->account, ['iban' => $this->accountInformation['iban']]); $service->update($this->account, ['iban' => $this->accountInformation['iban']]);
} }
} }

View File

@ -63,8 +63,8 @@ class TransactionGroupFactory
throw new DuplicateTransactionException($e->getMessage(), 0, $e); throw new DuplicateTransactionException($e->getMessage(), 0, $e);
} }
$title = $data['group_title'] ?? null; $title = $data['group_title'] ?? null;
$title = '' === $title ? null : $title; $title = '' === $title ? null : $title;
if (null !== $title) { if (null !== $title) {
$title = substr($title, 0, 1000); $title = substr($title, 0, 1000);
@ -73,7 +73,7 @@ class TransactionGroupFactory
throw new FireflyException('Created zero transaction journals.'); throw new FireflyException('Created zero transaction journals.');
} }
$group = new TransactionGroup(); $group = new TransactionGroup();
$group->user()->associate($this->user); $group->user()->associate($this->user);
$group->userGroup()->associate($data['user_group'] ?? $this->user->userGroup); $group->userGroup()->associate($data['user_group'] ?? $this->user->userGroup);
$group->title = $title; $group->title = $title;

View File

@ -96,7 +96,7 @@ class TransactionJournalFactory
{ {
app('log')->debug('Now in TransactionJournalFactory::create()'); app('log')->debug('Now in TransactionJournalFactory::create()');
// convert to special object. // convert to special object.
$dataObject = new NullArrayObject($data); $dataObject = new NullArrayObject($data);
app('log')->debug('Start of TransactionJournalFactory::create()'); app('log')->debug('Start of TransactionJournalFactory::create()');
$collection = new Collection(); $collection = new Collection();
@ -163,7 +163,7 @@ class TransactionJournalFactory
protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void
{ {
$set = [ $set = [
'journal' => $journal, 'journal' => $journal,
'name' => $field, 'name' => $field,
'data' => (string) ($data[$field] ?? ''), 'data' => (string) ($data[$field] ?? ''),
@ -197,14 +197,14 @@ class TransactionJournalFactory
$this->errorIfDuplicate($row['import_hash_v2']); $this->errorIfDuplicate($row['import_hash_v2']);
/** Some basic fields */ /** Some basic fields */
$type = $this->typeRepository->findTransactionType(null, $row['type']); $type = $this->typeRepository->findTransactionType(null, $row['type']);
$carbon = $row['date'] ?? today(config('app.timezone')); $carbon = $row['date'] ?? today(config('app.timezone'));
$order = $row['order'] ?? 0; $order = $row['order'] ?? 0;
$currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']); $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']);
$foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);
$bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']);
$billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null; $billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null;
$description = (string) $row['description']; $description = (string) $row['description'];
// Manipulate basic fields // Manipulate basic fields
$carbon->setTimezone(config('app.timezone')); $carbon->setTimezone(config('app.timezone'));
@ -220,7 +220,7 @@ class TransactionJournalFactory
} }
/** create or get source and destination accounts */ /** create or get source and destination accounts */
$sourceInfo = [ $sourceInfo = [
'id' => $row['source_id'], 'id' => $row['source_id'],
'name' => $row['source_name'], 'name' => $row['source_name'],
'iban' => $row['source_iban'], 'iban' => $row['source_iban'],
@ -229,7 +229,7 @@ class TransactionJournalFactory
'currency_id' => $currency->id, 'currency_id' => $currency->id,
]; ];
$destInfo = [ $destInfo = [
'id' => $row['destination_id'], 'id' => $row['destination_id'],
'name' => $row['destination_name'], 'name' => $row['destination_name'],
'iban' => $row['destination_iban'], 'iban' => $row['destination_iban'],
@ -239,8 +239,8 @@ class TransactionJournalFactory
]; ];
app('log')->debug('Source info:', $sourceInfo); app('log')->debug('Source info:', $sourceInfo);
app('log')->debug('Destination info:', $destInfo); app('log')->debug('Destination info:', $destInfo);
$sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo); $sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo);
$destinationAccount = $this->getAccount($type->type, 'destination', $destInfo); $destinationAccount = $this->getAccount($type->type, 'destination', $destInfo);
app('log')->debug('Done with getAccount(2x)'); app('log')->debug('Done with getAccount(2x)');
// this is the moment for a reconciliation sanity check (again). // this is the moment for a reconciliation sanity check (again).
@ -248,15 +248,15 @@ class TransactionJournalFactory
[$sourceAccount, $destinationAccount] = $this->reconciliationSanityCheck($sourceAccount, $destinationAccount); [$sourceAccount, $destinationAccount] = $this->reconciliationSanityCheck($sourceAccount, $destinationAccount);
} }
$currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount); $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount);
$foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency); $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency);
$foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount); $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount);
$description = $this->getDescription($description); $description = $this->getDescription($description);
app('log')->debug(sprintf('Date: %s (%s)', $carbon->toW3cString(), $carbon->getTimezone()->getName())); app('log')->debug(sprintf('Date: %s (%s)', $carbon->toW3cString(), $carbon->getTimezone()->getName()));
/** Create a basic journal. */ /** Create a basic journal. */
$journal = TransactionJournal::create( $journal = TransactionJournal::create(
[ [
'user_id' => $this->user->id, 'user_id' => $this->user->id,
'user_group_id' => $this->user->user_group_id, 'user_group_id' => $this->user->user_group_id,
@ -273,7 +273,7 @@ class TransactionJournalFactory
app('log')->debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description)); app('log')->debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description));
/** Create two transactions. */ /** Create two transactions. */
$transactionFactory = app(TransactionFactory::class); $transactionFactory = app(TransactionFactory::class);
$transactionFactory->setUser($this->user); $transactionFactory->setUser($this->user);
$transactionFactory->setJournal($journal); $transactionFactory->setJournal($journal);
$transactionFactory->setAccount($sourceAccount); $transactionFactory->setAccount($sourceAccount);
@ -292,7 +292,7 @@ class TransactionJournalFactory
} }
/** @var TransactionFactory $transactionFactory */ /** @var TransactionFactory $transactionFactory */
$transactionFactory = app(TransactionFactory::class); $transactionFactory = app(TransactionFactory::class);
$transactionFactory->setUser($this->user); $transactionFactory->setUser($this->user);
$transactionFactory->setJournal($journal); $transactionFactory->setJournal($journal);
$transactionFactory->setAccount($destinationAccount); $transactionFactory->setAccount($destinationAccount);
@ -310,7 +310,7 @@ class TransactionJournalFactory
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
} }
$journal->completed = true; $journal->completed = true;
$journal->save(); $journal->save();
$this->storeBudget($journal, $row); $this->storeBudget($journal, $row);
$this->storeCategory($journal, $row); $this->storeCategory($journal, $row);
@ -334,7 +334,7 @@ class TransactionJournalFactory
app('log')->error(sprintf('Could not encode dataRow: %s', $e->getMessage())); app('log')->error(sprintf('Could not encode dataRow: %s', $e->getMessage()));
$json = microtime(); $json = microtime();
} }
$hash = hash('sha256', $json); $hash = hash('sha256', $json);
app('log')->debug(sprintf('The hash is: %s', $hash), $dataRow); app('log')->debug(sprintf('The hash is: %s', $hash), $dataRow);
return $hash; return $hash;
@ -378,18 +378,18 @@ class TransactionJournalFactory
private function validateAccounts(NullArrayObject $data): void private function validateAccounts(NullArrayObject $data): void
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); app('log')->debug(sprintf('Now in %s', __METHOD__));
$transactionType = $data['type'] ?? 'invalid'; $transactionType = $data['type'] ?? 'invalid';
$this->accountValidator->setUser($this->user); $this->accountValidator->setUser($this->user);
$this->accountValidator->setTransactionType($transactionType); $this->accountValidator->setTransactionType($transactionType);
// validate source account. // validate source account.
$array = [ $array = [
'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null, 'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null,
'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null, 'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null,
'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null, 'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null,
'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null, 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null,
]; ];
$validSource = $this->accountValidator->validateSource($array); $validSource = $this->accountValidator->validateSource($array);
// do something with result: // do something with result:
if (false === $validSource) { if (false === $validSource) {
@ -398,7 +398,7 @@ class TransactionJournalFactory
app('log')->debug('Source seems valid.'); app('log')->debug('Source seems valid.');
// validate destination account // validate destination account
$array = [ $array = [
'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null, 'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null,
'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null, 'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null,
'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null, 'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null,
@ -466,7 +466,7 @@ class TransactionJournalFactory
// return user's default: // return user's default:
return app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup); return app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
} }
$result = $preference ?? $currency; $result = $preference ?? $currency;
app('log')->debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name)); app('log')->debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name));
return $result; return $result;

View File

@ -34,10 +34,10 @@ class TransactionJournalMetaFactory
public function updateOrCreate(array $data): ?TransactionJournalMeta public function updateOrCreate(array $data): ?TransactionJournalMeta
{ {
// app('log')->debug('In updateOrCreate()'); // app('log')->debug('In updateOrCreate()');
$value = $data['data']; $value = $data['data'];
/** @var null|TransactionJournalMeta $entry */ /** @var null|TransactionJournalMeta $entry */
$entry = $data['journal']->transactionJournalMeta()->where('name', $data['name'])->first(); $entry = $data['journal']->transactionJournalMeta()->where('name', $data['name'])->first();
if (null === $value && null !== $entry) { if (null === $value && null !== $entry) {
// app('log')->debug('Value is empty, delete meta value.'); // app('log')->debug('Value is empty, delete meta value.');
$entry->delete(); $entry->delete();
@ -63,7 +63,7 @@ class TransactionJournalMetaFactory
if (null === $entry) { if (null === $entry) {
// app('log')->debug('Will create new object.'); // app('log')->debug('Will create new object.');
app('log')->debug(sprintf('Going to create new meta-data entry to store "%s".', $data['name'])); app('log')->debug(sprintf('Going to create new meta-data entry to store "%s".', $data['name']));
$entry = new TransactionJournalMeta(); $entry = new TransactionJournalMeta();
$entry->transactionJournal()->associate($data['journal']); $entry->transactionJournal()->associate($data['journal']);
$entry->name = $data['name']; $entry->name = $data['name'];
} }

View File

@ -40,12 +40,12 @@ class UserGroupFactory
*/ */
public function create(array $data): UserGroup public function create(array $data): UserGroup
{ {
$userGroup = new UserGroup(); $userGroup = new UserGroup();
$userGroup->title = $data['title']; $userGroup->title = $data['title'];
$userGroup->save(); $userGroup->save();
// grab the OWNER role: // grab the OWNER role:
$role = UserRole::whereTitle(UserRoleEnum::OWNER->value)->first(); $role = UserRole::whereTitle(UserRoleEnum::OWNER->value)->first();
if (null === $role) { if (null === $role) {
throw new FireflyException('Role "owner" does not exist.'); throw new FireflyException('Role "owner" does not exist.');
} }

View File

@ -44,16 +44,16 @@ class ChartJsGenerator implements GeneratorInterface
'labels' => [], 'labels' => [],
]; ];
$amounts = array_column($data, 'amount'); $amounts = array_column($data, 'amount');
$next = next($amounts); $next = next($amounts);
$sortFlag = SORT_ASC; $sortFlag = SORT_ASC;
if (!is_bool($next) && 1 === bccomp((string)$next, '0')) { if (!is_bool($next) && 1 === bccomp((string)$next, '0')) {
$sortFlag = SORT_DESC; $sortFlag = SORT_DESC;
} }
array_multisort($amounts, $sortFlag, $data); array_multisort($amounts, $sortFlag, $data);
unset($next, $sortFlag, $amounts); unset($next, $sortFlag, $amounts);
$index = 0; $index = 0;
foreach ($data as $key => $valueArray) { foreach ($data as $key => $valueArray) {
// make larger than 0 // make larger than 0
$chartData['datasets'][0]['data'][] = app('steam')->positive((string)$valueArray['amount']); $chartData['datasets'][0]['data'][] = app('steam')->positive((string)$valueArray['amount']);
@ -99,11 +99,11 @@ class ChartJsGenerator implements GeneratorInterface
public function multiSet(array $data): array public function multiSet(array $data): array
{ {
reset($data); reset($data);
$first = current($data); $first = current($data);
if (!is_array($first)) { if (!is_array($first)) {
return []; return [];
} }
$labels = is_array($first['entries']) ? array_keys($first['entries']) : []; $labels = is_array($first['entries']) ? array_keys($first['entries']) : [];
$chartData = [ $chartData = [
'count' => count($data), 'count' => count($data),
@ -113,7 +113,7 @@ class ChartJsGenerator implements GeneratorInterface
unset($first, $labels); unset($first, $labels);
foreach ($data as $set) { foreach ($data as $set) {
$currentSet = [ $currentSet = [
'label' => $set['label'] ?? '(no label)', 'label' => $set['label'] ?? '(no label)',
'type' => $set['type'] ?? 'line', 'type' => $set['type'] ?? 'line',
'data' => array_values($set['entries']), 'data' => array_values($set['entries']),
@ -153,20 +153,20 @@ class ChartJsGenerator implements GeneratorInterface
// sort by value, keep keys. // sort by value, keep keys.
// different sort when values are positive and when they're negative. // different sort when values are positive and when they're negative.
asort($data); asort($data);
$next = next($data); $next = next($data);
if (!is_bool($next) && 1 === bccomp((string)$next, '0')) { if (!is_bool($next) && 1 === bccomp((string)$next, '0')) {
// next is positive, sort other way around. // next is positive, sort other way around.
arsort($data); arsort($data);
} }
unset($next); unset($next);
$index = 0; $index = 0;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
// make larger than 0 // make larger than 0
$chartData['datasets'][0]['data'][] = app('steam')->positive((string)$value); $chartData['datasets'][0]['data'][] = app('steam')->positive((string)$value);
$chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index);
$chartData['labels'][] = $key; $chartData['labels'][] = $key;
++$index; ++$index;
} }

View File

@ -48,8 +48,8 @@ class MonthReportGenerator implements ReportGeneratorInterface
*/ */
public function generate(): string public function generate(): string
{ {
$auditData = []; $auditData = [];
$dayBefore = clone $this->start; $dayBefore = clone $this->start;
$dayBefore->subDay(); $dayBefore->subDay();
/** @var Account $account */ /** @var Account $account */
@ -122,16 +122,16 @@ class MonthReportGenerator implements ReportGeneratorInterface
$journalRepository->setUser($account->user); $journalRepository->setUser($account->user);
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation() $collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation()
->withBudgetInformation()->withCategoryInformation()->withBillInformation() ->withBudgetInformation()->withCategoryInformation()->withBillInformation()
; ;
$journals = $collector->getExtractedJournals(); $journals = $collector->getExtractedJournals();
$journals = array_reverse($journals, true); $journals = array_reverse($journals, true);
$dayBeforeBalance = app('steam')->balance($account, $date); $dayBeforeBalance = app('steam')->balance($account, $date);
$startBalance = $dayBeforeBalance; $startBalance = $dayBeforeBalance;
$defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($account->user->userGroup); $defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($account->user->userGroup);
$currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency; $currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
foreach ($journals as $index => $journal) { foreach ($journals as $index => $journal) {
$journals[$index]['balance_before'] = $startBalance; $journals[$index]['balance_before'] = $startBalance;
@ -149,19 +149,19 @@ class MonthReportGenerator implements ReportGeneratorInterface
} }
} }
$newBalance = bcadd($startBalance, $transactionAmount); $newBalance = bcadd($startBalance, $transactionAmount);
$journals[$index]['balance_after'] = $newBalance; $journals[$index]['balance_after'] = $newBalance;
$startBalance = $newBalance; $startBalance = $newBalance;
// add meta dates for each journal. // add meta dates for each journal.
$journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date'); $journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date');
$journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date'); $journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date');
$journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date'); $journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date');
$journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date'); $journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date');
$journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date'); $journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date');
$journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date'); $journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date');
} }
$locale = app('steam')->getLocale(); $locale = app('steam')->getLocale();
return [ return [
'journals' => $journals, 'journals' => $journals,

View File

@ -157,7 +157,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
} }
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts($this->accounts)->setRange($this->start, $this->end) $collector->setAccounts($this->accounts)->setRange($this->start, $this->end)
->setTypes([TransactionType::WITHDRAWAL]) ->setTypes([TransactionType::WITHDRAWAL])
->withAccountInformation() ->withAccountInformation()

View File

@ -156,7 +156,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
} }
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts($this->accounts)->setRange($this->start, $this->end) $collector->setAccounts($this->accounts)->setRange($this->start, $this->end)
->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER]) ->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER])
->setCategories($this->categories)->withAccountInformation() ->setCategories($this->categories)->withAccountInformation()
@ -178,7 +178,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
} }
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts($this->accounts)->setRange($this->start, $this->end) $collector->setAccounts($this->accounts)->setRange($this->start, $this->end)
->setTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER]) ->setTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER])

View File

@ -49,7 +49,7 @@ class ReportGeneratorFactory
$period = 'MultiYear'; $period = 'MultiYear';
} }
$class = sprintf('FireflyIII\Generator\Report\%s\%sReportGenerator', $type, $period); $class = sprintf('FireflyIII\Generator\Report\%s\%sReportGenerator', $type, $period);
if (class_exists($class)) { if (class_exists($class)) {
/** @var ReportGeneratorInterface $obj */ /** @var ReportGeneratorInterface $obj */
$obj = app($class); $obj = app($class);

View File

@ -131,7 +131,7 @@ class StandardMessageGenerator implements MessageGeneratorInterface
*/ */
private function generateMessage(Webhook $webhook, Model $model): void private function generateMessage(Webhook $webhook, Model $model): void
{ {
$class = get_class($model); $class = get_class($model);
// Line is ignored because all of Firefly III's Models have an id property. // Line is ignored because all of Firefly III's Models have an id property.
app('log')->debug(sprintf('Now in generateMessage(#%d, %s#%d)', $webhook->id, $class, $model->id)); app('log')->debug(sprintf('Now in generateMessage(#%d, %s#%d)', $webhook->id, $class, $model->id));
@ -179,7 +179,7 @@ class StandardMessageGenerator implements MessageGeneratorInterface
case WebhookResponse::TRANSACTIONS->value: case WebhookResponse::TRANSACTIONS->value:
/** @var TransactionGroup $model */ /** @var TransactionGroup $model */
$transformer = new TransactionGroupTransformer(); $transformer = new TransactionGroupTransformer();
try { try {
$basicMessage['content'] = $transformer->transformObject($model); $basicMessage['content'] = $transformer->transformObject($model);
@ -196,9 +196,9 @@ class StandardMessageGenerator implements MessageGeneratorInterface
case WebhookResponse::ACCOUNTS->value: case WebhookResponse::ACCOUNTS->value:
/** @var TransactionGroup $model */ /** @var TransactionGroup $model */
$accounts = $this->collectAccounts($model); $accounts = $this->collectAccounts($model);
foreach ($accounts as $account) { foreach ($accounts as $account) {
$transformer = new AccountTransformer(); $transformer = new AccountTransformer();
$transformer->setParameters(new ParameterBag()); $transformer->setParameters(new ParameterBag());
$basicMessage['content'][] = $transformer->transform($account); $basicMessage['content'][] = $transformer->transform($account);
} }
@ -223,7 +223,7 @@ class StandardMessageGenerator implements MessageGeneratorInterface
private function storeMessage(Webhook $webhook, array $message): void private function storeMessage(Webhook $webhook, array $message): void
{ {
$webhookMessage = new WebhookMessage(); $webhookMessage = new WebhookMessage();
$webhookMessage->webhook()->associate($webhook); $webhookMessage->webhook()->associate($webhook);
$webhookMessage->sent = false; $webhookMessage->sent = false;
$webhookMessage->errored = false; $webhookMessage->errored = false;

View File

@ -39,7 +39,7 @@ class AdminEventHandler
{ {
public function sendInvitationNotification(InvitationCreated $event): void public function sendInvitationNotification(InvitationCreated $event): void
{ {
$sendMail = app('fireflyconfig')->get('notification_invite_created', true)->data; $sendMail = app('fireflyconfig')->get('notification_invite_created', true)->data;
if (false === $sendMail) { if (false === $sendMail) {
return; return;
} }
@ -75,7 +75,7 @@ class AdminEventHandler
*/ */
public function sendNewVersion(NewVersionAvailable $event): void public function sendNewVersion(NewVersionAvailable $event): void
{ {
$sendMail = app('fireflyconfig')->get('notification_new_version', true)->data; $sendMail = app('fireflyconfig')->get('notification_new_version', true)->data;
if (false === $sendMail) { if (false === $sendMail) {
return; return;
} }

View File

@ -35,7 +35,7 @@ class AuditEventHandler
{ {
public function storeAuditEvent(TriggeredAuditLog $event): void public function storeAuditEvent(TriggeredAuditLog $event): void
{ {
$array = [ $array = [
'auditable' => $event->auditable, 'auditable' => $event->auditable,
'changer' => $event->changer, 'changer' => $event->changer,
'action' => $event->field, 'action' => $event->field,

View File

@ -46,11 +46,11 @@ class AutomationHandler
app('log')->debug('In reportJournals.'); app('log')->debug('In reportJournals.');
/** @var UserRepositoryInterface $repository */ /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
$user = $repository->find($event->userId); $user = $repository->find($event->userId);
/** @var bool $sendReport */ /** @var bool $sendReport */
$sendReport = app('preferences')->getForUser($user, 'notification_transaction_creation', false)->data; $sendReport = app('preferences')->getForUser($user, 'notification_transaction_creation', false)->data;
if (false === $sendReport) { if (false === $sendReport) {
app('log')->debug('Not sending report, because config says so.'); app('log')->debug('Not sending report, because config says so.');

View File

@ -37,7 +37,7 @@ class BillEventHandler
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); app('log')->debug(sprintf('Now in %s', __METHOD__));
$bill = $event->bill; $bill = $event->bill;
/** @var bool $preference */ /** @var bool $preference */
$preference = app('preferences')->getForUser($bill->user, 'notification_bill_reminder', true)->data; $preference = app('preferences')->getForUser($bill->user, 'notification_bill_reminder', true)->data;

View File

@ -37,8 +37,8 @@ class DestroyedGroupEventHandler
public function triggerWebhooks(DestroyedTransactionGroup $destroyedGroupEvent): void public function triggerWebhooks(DestroyedTransactionGroup $destroyedGroupEvent): void
{ {
app('log')->debug('DestroyedTransactionGroup:triggerWebhooks'); app('log')->debug('DestroyedTransactionGroup:triggerWebhooks');
$group = $destroyedGroupEvent->transactionGroup; $group = $destroyedGroupEvent->transactionGroup;
$user = $group->user; $user = $group->user;
/** @var MessageGeneratorInterface $engine */ /** @var MessageGeneratorInterface $engine */
$engine = app(MessageGeneratorInterface::class); $engine = app(MessageGeneratorInterface::class);

View File

@ -66,7 +66,7 @@ class BudgetLimitHandler
private function updateAvailableBudget(BudgetLimit $budgetLimit): void private function updateAvailableBudget(BudgetLimit $budgetLimit): void
{ {
app('log')->debug(sprintf('Now in updateAvailableBudget(#%d)', $budgetLimit->id)); app('log')->debug(sprintf('Now in updateAvailableBudget(#%d)', $budgetLimit->id));
$budget = Budget::find($budgetLimit->budget_id); $budget = Budget::find($budgetLimit->budget_id);
if (null === $budget) { if (null === $budget) {
app('log')->warning('Budget is null, probably deleted, find deleted version.'); app('log')->warning('Budget is null, probably deleted, find deleted version.');
$budget = Budget::withTrashed()->find($budgetLimit->budget_id); $budget = Budget::withTrashed()->find($budgetLimit->budget_id);
@ -79,7 +79,7 @@ class BudgetLimitHandler
} }
/** @var null|User $user */ /** @var null|User $user */
$user = $budget->user; $user = $budget->user;
// sanity check. It happens when the budget has been deleted so the original user is unknown. // sanity check. It happens when the budget has been deleted so the original user is unknown.
if (null === $user) { if (null === $user) {
@ -102,20 +102,20 @@ class BudgetLimitHandler
if (null === $viewRange || is_array($viewRange)) { if (null === $viewRange || is_array($viewRange)) {
$viewRange = '1M'; $viewRange = '1M';
} }
$viewRange = (string)$viewRange; $viewRange = (string)$viewRange;
$start = app('navigation')->startOfPeriod($budgetLimit->start_date, $viewRange); $start = app('navigation')->startOfPeriod($budgetLimit->start_date, $viewRange);
$end = app('navigation')->startOfPeriod($budgetLimit->end_date, $viewRange); $end = app('navigation')->startOfPeriod($budgetLimit->end_date, $viewRange);
$end = app('navigation')->endOfPeriod($end, $viewRange); $end = app('navigation')->endOfPeriod($end, $viewRange);
// limit period in total is: // limit period in total is:
$limitPeriod = Period::make($start, $end, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE()); $limitPeriod = Period::make($start, $end, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());
app('log')->debug(sprintf('Limit period is from %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d'))); app('log')->debug(sprintf('Limit period is from %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d')));
// from the start until the end of the budget limit, need to loop! // from the start until the end of the budget limit, need to loop!
$current = clone $start; $current = clone $start;
while ($current <= $end) { while ($current <= $end) {
$currentEnd = app('navigation')->endOfPeriod($current, $viewRange); $currentEnd = app('navigation')->endOfPeriod($current, $viewRange);
// create or find AB for this particular period, and set the amount accordingly. // create or find AB for this particular period, and set the amount accordingly.
/** @var null|AvailableBudget $availableBudget */ /** @var null|AvailableBudget $availableBudget */
@ -158,16 +158,16 @@ class BudgetLimitHandler
} }
// prep for next loop // prep for next loop
$current = app('navigation')->addPeriod($current, $viewRange, 0); $current = app('navigation')->addPeriod($current, $viewRange, 0);
} }
} }
private function calculateAmount(AvailableBudget $availableBudget): void private function calculateAmount(AvailableBudget $availableBudget): void
{ {
$repository = app(BudgetLimitRepositoryInterface::class); $repository = app(BudgetLimitRepositoryInterface::class);
$repository->setUser($availableBudget->user); $repository->setUser($availableBudget->user);
$newAmount = '0'; $newAmount = '0';
$abPeriod = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY()); $abPeriod = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY());
app('log')->debug( app('log')->debug(
sprintf( sprintf(
'Now at AB #%d, ("%s" to "%s")', 'Now at AB #%d, ("%s" to "%s")',
@ -177,7 +177,7 @@ class BudgetLimitHandler
) )
); );
// have to recalculate everything just in case. // have to recalculate everything just in case.
$set = $repository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date); $set = $repository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date);
app('log')->debug(sprintf('Found %d interesting budget limit(s).', $set->count())); app('log')->debug(sprintf('Found %d interesting budget limit(s).', $set->count()));
/** @var BudgetLimit $budgetLimit */ /** @var BudgetLimit $budgetLimit */

View File

@ -39,7 +39,7 @@ class PiggyBankEventHandler
if (null !== $event->transactionGroup) { if (null !== $event->transactionGroup) {
$journal = $event->transactionGroup->transactionJournals()->first(); $journal = $event->transactionGroup->transactionJournals()->first();
} }
$date = $journal?->date ?? today(config('app.timezone')); $date = $journal?->date ?? today(config('app.timezone'));
// sanity check: event must not already exist for this journal and piggy bank. // sanity check: event must not already exist for this journal and piggy bank.
if (null !== $journal) { if (null !== $journal) {
$exists = PiggyBankEvent::where('piggy_bank_id', $event->piggyBank->id) $exists = PiggyBankEvent::where('piggy_bank_id', $event->piggyBank->id)

View File

@ -36,18 +36,18 @@ class RuleHandler
{ {
public function ruleActionFailedOnArray(RuleActionFailedOnArray $event): void public function ruleActionFailedOnArray(RuleActionFailedOnArray $event): void
{ {
$ruleAction = $event->ruleAction; $ruleAction = $event->ruleAction;
$rule = $ruleAction->rule; $rule = $ruleAction->rule;
/** @var bool $preference */ /** @var bool $preference */
$preference = app('preferences')->getForUser($rule->user, 'notification_rule_action_failures', true)->data; $preference = app('preferences')->getForUser($rule->user, 'notification_rule_action_failures', true)->data;
if (false === $preference) { if (false === $preference) {
return; return;
} }
app('log')->debug('Now in ruleActionFailedOnArray'); app('log')->debug('Now in ruleActionFailedOnArray');
$journal = $event->journal; $journal = $event->journal;
$error = $event->error; $error = $event->error;
$user = $ruleAction->rule->user; $user = $ruleAction->rule->user;
$mainMessage = trans('rules.main_message', ['rule' => $rule->title, 'action' => $ruleAction->action_type, 'group' => $journal['transaction_group_id'], 'error' => $error]); $mainMessage = trans('rules.main_message', ['rule' => $rule->title, 'action' => $ruleAction->action_type, 'group' => $journal['transaction_group_id'], 'error' => $error]);
$groupTitle = $journal['description'] ?? ''; $groupTitle = $journal['description'] ?? '';
@ -61,18 +61,18 @@ class RuleHandler
public function ruleActionFailedOnObject(RuleActionFailedOnObject $event): void public function ruleActionFailedOnObject(RuleActionFailedOnObject $event): void
{ {
$ruleAction = $event->ruleAction; $ruleAction = $event->ruleAction;
$rule = $ruleAction->rule; $rule = $ruleAction->rule;
/** @var bool $preference */ /** @var bool $preference */
$preference = app('preferences')->getForUser($rule->user, 'notification_rule_action_failures', true)->data; $preference = app('preferences')->getForUser($rule->user, 'notification_rule_action_failures', true)->data;
if (false === $preference) { if (false === $preference) {
return; return;
} }
app('log')->debug('Now in ruleActionFailedOnObject'); app('log')->debug('Now in ruleActionFailedOnObject');
$journal = $event->journal; $journal = $event->journal;
$error = $event->error; $error = $event->error;
$user = $ruleAction->rule->user; $user = $ruleAction->rule->user;
$mainMessage = trans('rules.main_message', ['rule' => $rule->title, 'action' => $ruleAction->action_type, 'group' => $journal->transaction_group_id, 'error' => $error]); $mainMessage = trans('rules.main_message', ['rule' => $rule->title, 'action' => $ruleAction->action_type, 'group' => $journal->transaction_group_id, 'error' => $error]);
$groupTitle = $journal->description ?? ''; $groupTitle = $journal->description ?? '';

View File

@ -37,7 +37,7 @@ class StoredAccountEventHandler
$account = $event->account; $account = $event->account;
/** @var CreditRecalculateService $object */ /** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class); $object = app(CreditRecalculateService::class);
$object->setAccount($account); $object->setAccount($account);
$object->recalculate(); $object->recalculate();
} }

View File

@ -50,14 +50,14 @@ class StoredGroupEventHandler
} }
app('log')->debug('Now in StoredGroupEventHandler::processRules()'); app('log')->debug('Now in StoredGroupEventHandler::processRules()');
$journals = $storedGroupEvent->transactionGroup->transactionJournals; $journals = $storedGroupEvent->transactionGroup->transactionJournals;
$array = []; $array = [];
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
$array[] = $journal->id; $array[] = $journal->id;
} }
$journalIds = implode(',', $array); $journalIds = implode(',', $array);
app('log')->debug(sprintf('Add local operator for journal(s): %s', $journalIds)); app('log')->debug(sprintf('Add local operator for journal(s): %s', $journalIds));
// collect rules: // collect rules:
@ -66,10 +66,10 @@ class StoredGroupEventHandler
// add the groups to the rule engine. // add the groups to the rule engine.
// it should run the rules in the group and cancel the group if necessary. // it should run the rules in the group and cancel the group if necessary.
$groups = $ruleGroupRepository->getRuleGroupsWithRules('store-journal'); $groups = $ruleGroupRepository->getRuleGroupsWithRules('store-journal');
// create and fire rule engine. // create and fire rule engine.
$newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine = app(RuleEngineInterface::class);
$newRuleEngine->setUser($storedGroupEvent->transactionGroup->user); $newRuleEngine->setUser($storedGroupEvent->transactionGroup->user);
$newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]);
$newRuleEngine->setRuleGroups($groups); $newRuleEngine->setRuleGroups($groups);
@ -78,7 +78,7 @@ class StoredGroupEventHandler
public function recalculateCredit(StoredTransactionGroup $event): void public function recalculateCredit(StoredTransactionGroup $event): void
{ {
$group = $event->transactionGroup; $group = $event->transactionGroup;
/** @var CreditRecalculateService $object */ /** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class); $object = app(CreditRecalculateService::class);
@ -92,14 +92,14 @@ class StoredGroupEventHandler
public function triggerWebhooks(StoredTransactionGroup $storedGroupEvent): void public function triggerWebhooks(StoredTransactionGroup $storedGroupEvent): void
{ {
app('log')->debug(__METHOD__); app('log')->debug(__METHOD__);
$group = $storedGroupEvent->transactionGroup; $group = $storedGroupEvent->transactionGroup;
if (false === $storedGroupEvent->fireWebhooks) { if (false === $storedGroupEvent->fireWebhooks) {
app('log')->info(sprintf('Will not fire webhooks for transaction group #%d', $group->id)); app('log')->info(sprintf('Will not fire webhooks for transaction group #%d', $group->id));
return; return;
} }
$user = $group->user; $user = $group->user;
/** @var MessageGeneratorInterface $engine */ /** @var MessageGeneratorInterface $engine */
$engine = app(MessageGeneratorInterface::class); $engine = app(MessageGeneratorInterface::class);

View File

@ -37,7 +37,7 @@ class UpdatedAccountEventHandler
$account = $event->account; $account = $event->account;
/** @var CreditRecalculateService $object */ /** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class); $object = app(CreditRecalculateService::class);
$object->setAccount($account); $object->setAccount($account);
$object->recalculate(); $object->recalculate();
} }

View File

@ -52,24 +52,24 @@ class UpdatedGroupEventHandler
return; return;
} }
$journals = $updatedGroupEvent->transactionGroup->transactionJournals; $journals = $updatedGroupEvent->transactionGroup->transactionJournals;
$array = []; $array = [];
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
$array[] = $journal->id; $array[] = $journal->id;
} }
$journalIds = implode(',', $array); $journalIds = implode(',', $array);
app('log')->debug(sprintf('Add local operator for journal(s): %s', $journalIds)); app('log')->debug(sprintf('Add local operator for journal(s): %s', $journalIds));
// collect rules: // collect rules:
$ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
$ruleGroupRepository->setUser($updatedGroupEvent->transactionGroup->user); $ruleGroupRepository->setUser($updatedGroupEvent->transactionGroup->user);
$groups = $ruleGroupRepository->getRuleGroupsWithRules('update-journal'); $groups = $ruleGroupRepository->getRuleGroupsWithRules('update-journal');
// file rule engine. // file rule engine.
$newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine = app(RuleEngineInterface::class);
$newRuleEngine->setUser($updatedGroupEvent->transactionGroup->user); $newRuleEngine->setUser($updatedGroupEvent->transactionGroup->user);
$newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]);
$newRuleEngine->setRuleGroups($groups); $newRuleEngine->setRuleGroups($groups);
@ -78,7 +78,7 @@ class UpdatedGroupEventHandler
public function recalculateCredit(UpdatedTransactionGroup $event): void public function recalculateCredit(UpdatedTransactionGroup $event): void
{ {
$group = $event->transactionGroup; $group = $event->transactionGroup;
/** @var CreditRecalculateService $object */ /** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class); $object = app(CreditRecalculateService::class);
@ -89,13 +89,13 @@ class UpdatedGroupEventHandler
public function triggerWebhooks(UpdatedTransactionGroup $updatedGroupEvent): void public function triggerWebhooks(UpdatedTransactionGroup $updatedGroupEvent): void
{ {
app('log')->debug(__METHOD__); app('log')->debug(__METHOD__);
$group = $updatedGroupEvent->transactionGroup; $group = $updatedGroupEvent->transactionGroup;
if (false === $updatedGroupEvent->fireWebhooks) { if (false === $updatedGroupEvent->fireWebhooks) {
app('log')->info(sprintf('Will not fire webhooks for transaction group #%d', $group->id)); app('log')->info(sprintf('Will not fire webhooks for transaction group #%d', $group->id));
return; return;
} }
$user = $group->user; $user = $group->user;
/** @var MessageGeneratorInterface $engine */ /** @var MessageGeneratorInterface $engine */
$engine = app(MessageGeneratorInterface::class); $engine = app(MessageGeneratorInterface::class);
@ -112,14 +112,14 @@ class UpdatedGroupEventHandler
*/ */
public function unifyAccounts(UpdatedTransactionGroup $updatedGroupEvent): void public function unifyAccounts(UpdatedTransactionGroup $updatedGroupEvent): void
{ {
$group = $updatedGroupEvent->transactionGroup; $group = $updatedGroupEvent->transactionGroup;
if (1 === $group->transactionJournals->count()) { if (1 === $group->transactionJournals->count()) {
return; return;
} }
// first journal: // first journal:
/** @var null|TransactionJournal $first */ /** @var null|TransactionJournal $first */
$first = $group->transactionJournals() $first = $group->transactionJournals()
->orderBy('transaction_journals.date', 'DESC') ->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.id', 'DESC')
@ -133,15 +133,15 @@ class UpdatedGroupEventHandler
return; return;
} }
$all = $group->transactionJournals()->get()->pluck('id')->toArray(); $all = $group->transactionJournals()->get()->pluck('id')->toArray();
/** @var Account $sourceAccount */ /** @var Account $sourceAccount */
$sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account; $sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account;
/** @var Account $destAccount */ /** @var Account $destAccount */
$destAccount = $first->transactions()->where('amount', '>', '0')->first()->account; $destAccount = $first->transactions()->where('amount', '>', '0')->first()->account;
$type = $first->transactionType->type; $type = $first->transactionType->type;
if (TransactionType::TRANSFER === $type || TransactionType::WITHDRAWAL === $type) { if (TransactionType::TRANSFER === $type || TransactionType::WITHDRAWAL === $type) {
// set all source transactions to source account: // set all source transactions to source account:
Transaction::whereIn('transaction_journal_id', $all) Transaction::whereIn('transaction_journal_id', $all)

View File

@ -82,8 +82,8 @@ class UserEventHandler
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
/** @var User $user */ /** @var User $user */
$user = $event->user; $user = $event->user;
$count = $repository->count(); $count = $repository->count();
// only act when there is 1 user in the system and he has no admin rights. // only act when there is 1 user in the system and he has no admin rights.
if (1 === $count && !$repository->hasRole($user, 'owner')) { if (1 === $count && !$repository->hasRole($user, 'owner')) {
@ -115,13 +115,13 @@ class UserEventHandler
*/ */
public function createGroupMembership(RegisteredUser $event): void public function createGroupMembership(RegisteredUser $event): void
{ {
$user = $event->user; $user = $event->user;
$groupExists = true; $groupExists = true;
$groupTitle = $user->email; $groupTitle = $user->email;
$index = 1; $index = 1;
/** @var UserGroup $group */ /** @var UserGroup $group */
$group = null; $group = null;
// create a new group. // create a new group.
while (true === $groupExists) { // @phpstan-ignore-line while (true === $groupExists) { // @phpstan-ignore-line
@ -131,7 +131,7 @@ class UserEventHandler
break; break;
} }
$groupTitle = sprintf('%s-%d', $user->email, $index); $groupTitle = sprintf('%s-%d', $user->email, $index);
++$index; ++$index;
if ($index > 99) { if ($index > 99) {
throw new FireflyException('Email address can no longer be used for registrations.'); throw new FireflyException('Email address can no longer be used for registrations.');
@ -139,7 +139,7 @@ class UserEventHandler
} }
/** @var null|UserRole $role */ /** @var null|UserRole $role */
$role = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); $role = UserRole::where('title', UserRoleEnum::OWNER->value)->first();
if (null === $role) { if (null === $role) {
throw new FireflyException('The user role is unexpectedly empty. Did you run all migrations?'); throw new FireflyException('The user role is unexpectedly empty. Did you run all migrations?');
} }
@ -165,7 +165,7 @@ class UserEventHandler
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
/** @var User $user */ /** @var User $user */
$user = $event->user; $user = $event->user;
if ($repository->hasRole($user, 'demo')) { if ($repository->hasRole($user, 'demo')) {
// set user back to English. // set user back to English.
app('preferences')->setForUser($user, 'language', 'en_US'); app('preferences')->setForUser($user, 'language', 'en_US');
@ -186,7 +186,7 @@ class UserEventHandler
return; // do not email demo user. return; // do not email demo user.
} }
$list = app('preferences')->getForUser($user, 'login_ip_history', [])->data; $list = app('preferences')->getForUser($user, 'login_ip_history', [])->data;
if (!is_array($list)) { if (!is_array($list)) {
$list = []; $list = [];
} }
@ -375,7 +375,7 @@ class UserEventHandler
public function storeUserIPAddress(ActuallyLoggedIn $event): void public function storeUserIPAddress(ActuallyLoggedIn $event): void
{ {
app('log')->debug('Now in storeUserIPAddress'); app('log')->debug('Now in storeUserIPAddress');
$user = $event->user; $user = $event->user;
if ($user->hasRole('demo')) { if ($user->hasRole('demo')) {
app('log')->debug('Do not log demo user logins'); app('log')->debug('Do not log demo user logins');
@ -392,8 +392,8 @@ class UserEventHandler
return; return;
} }
$inArray = false; $inArray = false;
$ip = request()->ip(); $ip = request()->ip();
app('log')->debug(sprintf('User logging in from IP address %s', $ip)); app('log')->debug(sprintf('User logging in from IP address %s', $ip));
// update array if in array // update array if in array
@ -421,7 +421,7 @@ class UserEventHandler
$preference = array_values($preference); $preference = array_values($preference);
/** @var bool $send */ /** @var bool $send */
$send = app('preferences')->getForUser($user, 'notification_user_login', true)->data; $send = app('preferences')->getForUser($user, 'notification_user_login', true)->data;
app('preferences')->setForUser($user, 'login_ip_history', $preference); app('preferences')->setForUser($user, 'login_ip_history', $preference);
if (false === $inArray && true === $send) { if (false === $inArray && true === $send) {

View File

@ -48,8 +48,8 @@ class VersionCheckEventHandler
app('log')->debug('Now in checkForUpdates()'); app('log')->debug('Now in checkForUpdates()');
// should not check for updates: // should not check for updates:
$permission = app('fireflyconfig')->get('permission_update_check', -1); $permission = app('fireflyconfig')->get('permission_update_check', -1);
$value = (int)$permission->data; $value = (int)$permission->data;
if (1 !== $value) { if (1 !== $value) {
app('log')->debug('Update check is not enabled.'); app('log')->debug('Update check is not enabled.');
$this->warnToCheckForUpdates($event); $this->warnToCheckForUpdates($event);
@ -58,8 +58,8 @@ class VersionCheckEventHandler
} }
/** @var UserRepositoryInterface $repository */ /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
$user = $event->user; $user = $event->user;
if (!$repository->hasRole($user, 'owner')) { if (!$repository->hasRole($user, 'owner')) {
app('log')->debug('User is not admin, done.'); app('log')->debug('User is not admin, done.');
@ -78,7 +78,7 @@ class VersionCheckEventHandler
} }
// last check time was more than a week ago. // last check time was more than a week ago.
app('log')->debug('Have not checked for a new version in a week!'); app('log')->debug('Have not checked for a new version in a week!');
$release = $this->getLatestRelease(); $release = $this->getLatestRelease();
session()->flash($release['level'], $release['message']); session()->flash($release['level'], $release['message']);
app('fireflyconfig')->set('last_update_check', time()); app('fireflyconfig')->set('last_update_check', time());
@ -90,8 +90,8 @@ class VersionCheckEventHandler
protected function warnToCheckForUpdates(RequestedVersionCheckStatus $event): void protected function warnToCheckForUpdates(RequestedVersionCheckStatus $event): void
{ {
/** @var UserRepositoryInterface $repository */ /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
$user = $event->user; $user = $event->user;
if (!$repository->hasRole($user, 'owner')) { if (!$repository->hasRole($user, 'owner')) {
app('log')->debug('User is not admin, done.'); app('log')->debug('User is not admin, done.');

View File

@ -34,7 +34,7 @@ class PiggyBankObserver
public function created(PiggyBank $piggyBank): void public function created(PiggyBank $piggyBank): void
{ {
app('log')->debug('Observe "created" of a piggy bank.'); app('log')->debug('Observe "created" of a piggy bank.');
$repetition = new PiggyBankRepetition(); $repetition = new PiggyBankRepetition();
$repetition->piggyBank()->associate($piggyBank); $repetition->piggyBank()->associate($piggyBank);
$repetition->startdate = $piggyBank->startdate; $repetition->startdate = $piggyBank->startdate;
$repetition->targetdate = $piggyBank->targetdate; $repetition->targetdate = $piggyBank->targetdate;

View File

@ -117,7 +117,7 @@ class AttachmentHelper implements AttachmentHelperInterface
public function saveAttachmentFromApi(Attachment $attachment, string $content): bool public function saveAttachmentFromApi(Attachment $attachment, string $content): bool
{ {
Log::debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
$resource = tmpfile(); $resource = tmpfile();
if (false === $resource) { if (false === $resource) {
Log::error('Cannot create temp-file for file upload.'); Log::error('Cannot create temp-file for file upload.');
@ -130,24 +130,24 @@ class AttachmentHelper implements AttachmentHelperInterface
return false; return false;
} }
$path = stream_get_meta_data($resource)['uri']; $path = stream_get_meta_data($resource)['uri'];
Log::debug(sprintf('Path is %s', $path)); Log::debug(sprintf('Path is %s', $path));
$result = fwrite($resource, $content); $result = fwrite($resource, $content);
if (false === $result) { if (false === $result) {
Log::error('Could not write temp file.'); Log::error('Could not write temp file.');
return false; return false;
} }
Log::debug(sprintf('Wrote %d bytes to temp file.', $result)); Log::debug(sprintf('Wrote %d bytes to temp file.', $result));
$finfo = finfo_open(FILEINFO_MIME_TYPE); $finfo = finfo_open(FILEINFO_MIME_TYPE);
if (false === $finfo) { if (false === $finfo) {
Log::error('Could not open finfo.'); Log::error('Could not open finfo.');
fclose($resource); fclose($resource);
return false; return false;
} }
$mime = (string)finfo_file($finfo, $path); $mime = (string)finfo_file($finfo, $path);
$allowedMime = config('firefly.allowedMimes'); $allowedMime = config('firefly.allowedMimes');
if (!in_array($mime, $allowedMime, true)) { if (!in_array($mime, $allowedMime, true)) {
Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime)); Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime));
fclose($resource); fclose($resource);
@ -156,8 +156,8 @@ class AttachmentHelper implements AttachmentHelperInterface
} }
Log::debug(sprintf('Found mime "%s" in file "%s"', $mime, $path)); Log::debug(sprintf('Found mime "%s" in file "%s"', $mime, $path));
// is allowed? Save the file, without encryption. // is allowed? Save the file, without encryption.
$parts = explode('/', $attachment->fileName()); $parts = explode('/', $attachment->fileName());
$file = $parts[count($parts) - 1]; $file = $parts[count($parts) - 1];
Log::debug(sprintf('Write file to disk in file named "%s"', $file)); Log::debug(sprintf('Write file to disk in file named "%s"', $file));
$this->uploadDisk->put($file, $content); $this->uploadDisk->put($file, $content);
@ -215,13 +215,13 @@ class AttachmentHelper implements AttachmentHelperInterface
$validation = $this->validateUpload($file, $model); $validation = $this->validateUpload($file, $model);
$attachment = null; $attachment = null;
if (false !== $validation) { if (false !== $validation) {
$user = $model->user; $user = $model->user;
// ignore lines about polymorphic calls. // ignore lines about polymorphic calls.
if ($model instanceof PiggyBank) { if ($model instanceof PiggyBank) {
$user = $model->account->user; $user = $model->account->user;
} }
$attachment = new Attachment(); // create Attachment object. $attachment = new Attachment(); // create Attachment object.
$attachment->user()->associate($user); $attachment->user()->associate($user);
$attachment->attachable()->associate($model); $attachment->attachable()->associate($model);
$attachment->md5 = (string)md5_file($file->getRealPath()); $attachment->md5 = (string)md5_file($file->getRealPath());
@ -232,14 +232,14 @@ class AttachmentHelper implements AttachmentHelperInterface
$attachment->save(); $attachment->save();
Log::debug('Created attachment:', $attachment->toArray()); Log::debug('Created attachment:', $attachment->toArray());
$fileObject = $file->openFile(); $fileObject = $file->openFile();
$fileObject->rewind(); $fileObject->rewind();
if (0 === $file->getSize()) { if (0 === $file->getSize()) {
throw new FireflyException('Cannot upload empty or non-existent file.'); throw new FireflyException('Cannot upload empty or non-existent file.');
} }
$content = (string)$fileObject->fread($file->getSize()); $content = (string)$fileObject->fread($file->getSize());
Log::debug(sprintf('Full file length is %d and upload size is %d.', strlen($content), $file->getSize())); Log::debug(sprintf('Full file length is %d and upload size is %d.', strlen($content), $file->getSize()));
// store it without encryption. // store it without encryption.
@ -248,8 +248,8 @@ class AttachmentHelper implements AttachmentHelperInterface
$attachment->save(); $attachment->save();
$this->attachments->push($attachment); $this->attachments->push($attachment);
$name = e($file->getClientOriginalName()); // add message: $name = e($file->getClientOriginalName()); // add message:
$msg = (string)trans('validation.file_attached', ['name' => $name]); $msg = (string)trans('validation.file_attached', ['name' => $name]);
$this->messages->add('attachments', $msg); $this->messages->add('attachments', $msg);
} }
@ -289,14 +289,14 @@ class AttachmentHelper implements AttachmentHelperInterface
protected function validMime(UploadedFile $file): bool protected function validMime(UploadedFile $file): bool
{ {
Log::debug('Now in validMime()'); Log::debug('Now in validMime()');
$mime = e($file->getMimeType()); $mime = e($file->getMimeType());
$name = e($file->getClientOriginalName()); $name = e($file->getClientOriginalName());
Log::debug(sprintf('Name is %s, and mime is %s', $name, $mime)); Log::debug(sprintf('Name is %s, and mime is %s', $name, $mime));
Log::debug('Valid mimes are', $this->allowedMimes); Log::debug('Valid mimes are', $this->allowedMimes);
$result = true; $result = true;
if (!in_array($mime, $this->allowedMimes, true)) { if (!in_array($mime, $this->allowedMimes, true)) {
$msg = (string)trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]); $msg = (string)trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]);
$this->errors->add('attachments', $msg); $this->errors->add('attachments', $msg);
Log::error($msg); Log::error($msg);
@ -315,7 +315,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$name = e($file->getClientOriginalName()); $name = e($file->getClientOriginalName());
$result = true; $result = true;
if ($size > $this->maxUploadSize) { if ($size > $this->maxUploadSize) {
$msg = (string)trans('validation.file_too_large', ['name' => $name]); $msg = (string)trans('validation.file_too_large', ['name' => $name]);
$this->errors->add('attachments', $msg); $this->errors->add('attachments', $msg);
Log::error($msg); Log::error($msg);
@ -330,10 +330,10 @@ class AttachmentHelper implements AttachmentHelperInterface
*/ */
protected function hasFile(UploadedFile $file, Model $model): bool protected function hasFile(UploadedFile $file, Model $model): bool
{ {
$md5 = md5_file($file->getRealPath()); $md5 = md5_file($file->getRealPath());
$name = $file->getClientOriginalName(); $name = $file->getClientOriginalName();
$class = get_class($model); $class = get_class($model);
$count = 0; $count = 0;
// ignore lines about polymorphic calls. // ignore lines about polymorphic calls.
if ($model instanceof PiggyBank) { if ($model instanceof PiggyBank) {
$count = $model->account->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count(); $count = $model->account->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
@ -343,7 +343,7 @@ class AttachmentHelper implements AttachmentHelperInterface
} }
$result = false; $result = false;
if ($count > 0) { if ($count > 0) {
$msg = (string)trans('validation.file_already_attached', ['name' => $name]); $msg = (string)trans('validation.file_already_attached', ['name' => $name]);
$this->errors->add('attachments', $msg); $this->errors->add('attachments', $msg);
Log::error($msg); Log::error($msg);
$result = true; $result = true;

View File

@ -211,9 +211,9 @@ trait AccountCollection
$this->query->leftJoin('account_types as source_account_type', 'source_account_type.id', '=', 'source_account.account_type_id'); $this->query->leftJoin('account_types as source_account_type', 'source_account_type.id', '=', 'source_account.account_type_id');
// add source account fields: // add source account fields:
$this->fields[] = 'source_account.name as source_account_name'; $this->fields[] = 'source_account.name as source_account_name';
$this->fields[] = 'source_account.iban as source_account_iban'; $this->fields[] = 'source_account.iban as source_account_iban';
$this->fields[] = 'source_account_type.type as source_account_type'; $this->fields[] = 'source_account_type.type as source_account_type';
// same for dest // same for dest
$this->query->leftJoin('accounts as dest_account', 'dest_account.id', '=', 'destination.account_id'); $this->query->leftJoin('accounts as dest_account', 'dest_account.id', '=', 'destination.account_id');

View File

@ -682,12 +682,12 @@ trait MetaCollection
$list = $tags->pluck('tag')->toArray(); $list = $tags->pluck('tag')->toArray();
$list = array_map('strtolower', $list); $list = array_map('strtolower', $list);
$filter = static function (array $object) use ($list): bool|array { $filter = static function (array $object) use ($list): bool|array {
$return = $object; $return = $object;
unset($return['transactions']); unset($return['transactions']);
$return['transactions'] = []; $return['transactions'] = [];
Log::debug(sprintf('Now in setAllTags(%s) filter', implode(', ', $list))); Log::debug(sprintf('Now in setAllTags(%s) filter', implode(', ', $list)));
$expectedTagCount = count($list); $expectedTagCount = count($list);
$foundTagCount = 0; $foundTagCount = 0;
foreach ($object['transactions'] as $transaction) { foreach ($object['transactions'] as $transaction) {
$transactionTagCount = count($transaction['tags']); $transactionTagCount = count($transaction['tags']);
app('log')->debug(sprintf('Transaction #%d has %d tag(s)', $transaction['transaction_journal_id'], $transactionTagCount)); app('log')->debug(sprintf('Transaction #%d has %d tag(s)', $transaction['transaction_journal_id'], $transactionTagCount));
@ -708,7 +708,7 @@ trait MetaCollection
Log::debug(sprintf('Found %d tags, need at least %d.', $foundTagCount, $expectedTagCount)); Log::debug(sprintf('Found %d tags, need at least %d.', $foundTagCount, $expectedTagCount));
// found at least the expected tags. // found at least the expected tags.
$result = $foundTagCount >= $expectedTagCount; $result = $foundTagCount >= $expectedTagCount;
if (true === $result) { if (true === $result) {
return $return; return $return;
} }
@ -941,8 +941,8 @@ trait MetaCollection
if (false === $this->hasJoinedMetaTables) { if (false === $this->hasJoinedMetaTables) {
$this->hasJoinedMetaTables = true; $this->hasJoinedMetaTables = true;
$this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id'); $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
$this->fields[] = 'journal_meta.name as meta_name'; $this->fields[] = 'journal_meta.name as meta_name';
$this->fields[] = 'journal_meta.data as meta_data'; $this->fields[] = 'journal_meta.data as meta_data';
} }
} }

View File

@ -65,7 +65,7 @@ trait TimeCollection
if ($end < $start) { if ($end < $start) {
[$start, $end] = [$end, $start]; [$start, $end] = [$end, $start];
} }
$end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object.
$end->endOfDay(); $end->endOfDay();
$start->startOfDay(); $start->startOfDay();
$this->withMetaDate($field); $this->withMetaDate($field);
@ -536,7 +536,7 @@ trait TimeCollection
if ($end < $start) { if ($end < $start) {
[$start, $end] = [$end, $start]; [$start, $end] = [$end, $start];
} }
$end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object.
$end->endOfDay(); $end->endOfDay();
$start->startOfDay(); $start->startOfDay();
$this->withMetaDate($field); $this->withMetaDate($field);

View File

@ -62,12 +62,12 @@ class GroupCollector implements GroupCollectorInterface
*/ */
public function __construct() public function __construct()
{ {
$this->postFilters = []; $this->postFilters = [];
$this->tags = []; $this->tags = [];
$this->user = null; $this->user = null;
$this->userGroup = null; $this->userGroup = null;
$this->limit = null; $this->limit = null;
$this->page = null; $this->page = null;
$this->hasAccountInfo = false; $this->hasAccountInfo = false;
$this->hasCatInformation = false; $this->hasCatInformation = false;
@ -287,7 +287,7 @@ class GroupCollector implements GroupCollectorInterface
if (is_int($param)) { if (is_int($param)) {
$replace = (string)$param; $replace = (string)$param;
} }
$pos = strpos($query, '?'); $pos = strpos($query, '?');
if (false !== $pos) { if (false !== $pos) {
$query = substr_replace($query, $replace, $pos, 1); $query = substr_replace($query, $replace, $pos, 1);
} }
@ -455,13 +455,13 @@ class GroupCollector implements GroupCollectorInterface
// add to query: // add to query:
$this->query->orWhereIn('transaction_journals.transaction_group_id', $groupIds); $this->query->orWhereIn('transaction_journals.transaction_group_id', $groupIds);
} }
$result = $this->query->get($this->fields); $result = $this->query->get($this->fields);
// now to parse this into an array. // now to parse this into an array.
$collection = $this->parseArray($result); $collection = $this->parseArray($result);
// filter the array using all available post filters: // filter the array using all available post filters:
$collection = $this->postFilterCollection($collection); $collection = $this->postFilterCollection($collection);
// count it and continue: // count it and continue:
$this->total = $collection->count(); $this->total = $collection->count();
@ -691,12 +691,12 @@ class GroupCollector implements GroupCollectorInterface
/** @var TransactionJournal $augumentedJournal */ /** @var TransactionJournal $augumentedJournal */
foreach ($collection as $augumentedJournal) { foreach ($collection as $augumentedJournal) {
$groupId = (int)$augumentedJournal->transaction_group_id; $groupId = (int)$augumentedJournal->transaction_group_id;
if (!array_key_exists($groupId, $groups)) { if (!array_key_exists($groupId, $groups)) {
// make new array // make new array
$parsedGroup = $this->parseAugmentedJournal($augumentedJournal); $parsedGroup = $this->parseAugmentedJournal($augumentedJournal);
$groupArray = [ $groupArray = [
'id' => (int)$augumentedJournal->transaction_group_id, 'id' => (int)$augumentedJournal->transaction_group_id,
'user_id' => $augumentedJournal->user_id, 'user_id' => $augumentedJournal->user_id,
'user_group_id' => $augumentedJournal->user_group_id, 'user_group_id' => $augumentedJournal->user_group_id,
@ -766,7 +766,7 @@ class GroupCollector implements GroupCollectorInterface
} }
// try to process meta date value (if present) // try to process meta date value (if present)
$dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date']; $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date'];
if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) { if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) {
$name = $result['meta_name']; $name = $result['meta_name'];
if (array_key_exists('meta_data', $result) && '' !== (string)$result['meta_data']) { if (array_key_exists('meta_data', $result) && '' !== (string)$result['meta_data']) {
@ -775,15 +775,15 @@ class GroupCollector implements GroupCollectorInterface
} }
// convert values to integers: // convert values to integers:
$result = $this->convertToInteger($result); $result = $this->convertToInteger($result);
// convert back to strings because SQLite is dumb like that. // convert back to strings because SQLite is dumb like that.
$result = $this->convertToStrings($result); $result = $this->convertToStrings($result);
$result['reconciled'] = 1 === (int)$result['reconciled']; $result['reconciled'] = 1 === (int)$result['reconciled'];
if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well. if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well.
$tagId = (int)$augumentedJournal['tag_id']; $tagId = (int)$augumentedJournal['tag_id'];
$tagDate = null; $tagDate = null;
try { try {
$tagDate = Carbon::parse($augumentedJournal['tag_date']); $tagDate = Carbon::parse($augumentedJournal['tag_date']);
@ -847,9 +847,9 @@ class GroupCollector implements GroupCollectorInterface
{ {
$newArray = $newJournal->toArray(); $newArray = $newJournal->toArray();
if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well. if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well.
$tagId = (int)$newJournal['tag_id']; $tagId = (int)$newJournal['tag_id'];
$tagDate = null; $tagDate = null;
try { try {
$tagDate = Carbon::parse($newArray['tag_date']); $tagDate = Carbon::parse($newArray['tag_date']);
@ -872,7 +872,7 @@ class GroupCollector implements GroupCollectorInterface
{ {
$newArray = $newJournal->toArray(); $newArray = $newJournal->toArray();
if (array_key_exists('attachment_id', $newArray)) { if (array_key_exists('attachment_id', $newArray)) {
$attachmentId = (int)$newJournal['attachment_id']; $attachmentId = (int)$newJournal['attachment_id'];
$existingJournal['attachments'][$attachmentId] = [ $existingJournal['attachments'][$attachmentId] = [
'id' => $attachmentId, 'id' => $attachmentId,
@ -891,7 +891,7 @@ class GroupCollector implements GroupCollectorInterface
foreach ($groups as $groudId => $group) { foreach ($groups as $groudId => $group) {
/** @var array $transaction */ /** @var array $transaction */
foreach ($group['transactions'] as $transaction) { foreach ($group['transactions'] as $transaction) {
$currencyId = (int)$transaction['currency_id']; $currencyId = (int)$transaction['currency_id'];
if (null === $transaction['amount']) { if (null === $transaction['amount']) {
throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId)); throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId));
} }
@ -907,7 +907,7 @@ class GroupCollector implements GroupCollectorInterface
$groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']); $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']);
if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) { if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) {
$currencyId = (int)$transaction['foreign_currency_id']; $currencyId = (int)$transaction['foreign_currency_id'];
// set default: // set default:
if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
@ -936,7 +936,7 @@ class GroupCollector implements GroupCollectorInterface
*/ */
foreach ($this->postFilters as $function) { foreach ($this->postFilters as $function) {
app('log')->debug('Applying filter...'); app('log')->debug('Applying filter...');
$nextCollection = new Collection(); $nextCollection = new Collection();
// loop everything in the current collection // loop everything in the current collection
// and save it (or not) in the new collection. // and save it (or not) in the new collection.

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