Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Optimize currency search.
James Cole4835b0530470
diff --git a/.ci/phpstan.neon b/.ci/phpstan.neonindex 3da6d3fa52..1b8e889c72 100644--- a/.ci/phpstan.neon+++ b/.ci/phpstan.neon@@ -28,5 +28,5 @@ parameters:# The level 8 is the highest level. original was 5# 7 is more than enough, higher just leaves NULL things.- level: 8+ level: 7diff --git a/app/Api/V1/Controllers/Chart/BudgetController.php b/app/Api/V1/Controllers/Chart/BudgetController.phpindex 4bebbce464..0ad9ffaaca 100644--- a/app/Api/V1/Controllers/Chart/BudgetController.php+++ b/app/Api/V1/Controllers/Chart/BudgetController.php@@ -35,6 +35,7 @@ use FireflyIII\Models\TransactionCurrency;use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Http\Api\CleansChartData;use FireflyIII\Support\Http\Api\ExchangeRateConverter;use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait;@@ -143,7 +144,7 @@ class BudgetController extends Controller// convert data if necessary.if (true === $this->convertToPrimary && $currencyId !== $this->primaryCurrency->id) {- $currencies[$currencyId] ??= TransactionCurrency::find($currencyId);+ $currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId);$row['pc_budgeted'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['budgeted']);$row['pc_spent'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['spent']);$row['pc_left'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['left']);@@ -231,7 +232,7 @@ class BudgetController extends Controller* @var array $block*/foreach ($spent as $currencyId => $block) {- $this->currencies[$currencyId] ??= TransactionCurrency::find($currencyId);+ $this->currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId);$return[$currencyId] ??= ['currency_id' => (string)$currencyId,'currency_code' => $block['currency_code'],diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.phpindex 0e0f0fa8a1..c52ffd1b9d 100644--- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php+++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php@@ -33,6 +33,7 @@ use FireflyIII\Enums\UserRoleEnum;use FireflyIII\Models\CurrencyExchangeRate;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepositoryInterface;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait;use FireflyIII\Transformers\ExchangeRateTransformer;use Illuminate\Http\JsonResponse;@@ -98,7 +99,7 @@ class StoreController extends Controller$from = $request->getFromCurrency();$collection = new Collection();foreach ($data['rates'] as $key => $rate) {- $to = TransactionCurrency::where('code', $key)->first();+ $to = Amount::getTransactionCurrencyByCode($key);if (null === $to) {continue; // should not happen.}diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByDateRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByDateRequest.phpindex 4afb664063..25dc0f14a2 100644--- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByDateRequest.php+++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByDateRequest.php@@ -25,6 +25,7 @@ declare(strict_types=1);namespace FireflyIII\Api\V1\Requests\Models\CurrencyExchangeRate;use FireflyIII\Models\TransactionCurrency;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Request\ChecksLogin;use FireflyIII\Support\Request\ConvertsDataTypes;use Illuminate\Validation\Validator;@@ -48,7 +49,7 @@ class StoreByDateRequest extends FormRequestpublic function getFromCurrency(): TransactionCurrency{- return TransactionCurrency::where('code', $this->get('from'))->first();+ return Amount::getTransactionCurrencyByCode((string) $this->get('from'));}/**@@ -83,7 +84,7 @@ class StoreByDateRequest extends FormRequestcontinue;}- $to = TransactionCurrency::where('code', $key)->first();+ $to = Amount::getTransactionCurrencyByCode((string) $key);if (null === $to) {$validator->errors()->add(sprintf('rates.%s', $key), trans('validation.invalid_currency_code', ['code' => $key]));}diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.phpindex b4ef5d13b8..6038a65f02 100644--- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php+++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php@@ -26,6 +26,7 @@ namespace FireflyIII\Api\V1\Requests\Models\CurrencyExchangeRate;use Carbon\Carbon;use FireflyIII\Models\TransactionCurrency;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Request\ChecksLogin;use FireflyIII\Support\Request\ConvertsDataTypes;use Illuminate\Foundation\Http\FormRequest;@@ -42,7 +43,7 @@ class StoreRequest extends FormRequestpublic function getFromCurrency(): TransactionCurrency{- return TransactionCurrency::where('code', $this->get('from'))->first();+ return Amount::getTransactionCurrencyByCode((string) $this->get('from'));}public function getRate(): string@@ -52,7 +53,7 @@ class StoreRequest extends FormRequestpublic function getToCurrency(): TransactionCurrency{- return TransactionCurrency::where('code', $this->get('to'))->first();+ return Amount::getTransactionCurrencyByCode((string) $this->get('to'));}/**diff --git a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.phpindex d12108d549..dc86d72e68 100644--- a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php+++ b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php@@ -24,6 +24,7 @@ declare(strict_types=1);namespace FireflyIII\Api\V1\Requests\Models\PiggyBank;+use FireflyIII\Support\Facades\Amount;use Illuminate\Validation\Validator;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Repositories\Account\AccountRepositoryInterface;@@ -135,13 +136,13 @@ class StoreRequest extends FormRequestprivate function getCurrencyFromData(Validator $validator, array $data): ?TransactionCurrency{if (array_key_exists('transaction_currency_code', $data) && '' !== (string) $data['transaction_currency_code']) {- $currency = TransactionCurrency::whereCode($data['transaction_currency_code'])->first();+ $currency = Amount::getTransactionCurrencyByCode((string) $data['transaction_currency_code']);if (null !== $currency) {return $currency;}}if (array_key_exists('transaction_currency_id', $data) && '' !== (string) $data['transaction_currency_id']) {- $currency = TransactionCurrency::find((int) $data['transaction_currency_id']);+ $currency = Amount::getTransactionCurrencyById((int) $data['transaction_currency_id']);if (null !== $currency) {return $currency;}diff --git a/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.phpindex 56b1a5ee0c..6bb28af607 100644--- a/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php+++ b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php@@ -25,9 +25,11 @@ declare(strict_types=1);namespace FireflyIII\Console\Commands\Upgrade;use FireflyIII\Console\Commands\ShowsFriendlyMessages;+use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\Preference;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Models\UserGroup;+use FireflyIII\Support\Facades\Amount;use FireflyIII\User;use Illuminate\Console\Command;use Illuminate\Support\Collection;@@ -38,9 +40,9 @@ class UpgradesCurrencyPreferences extends Commandpublic const string CONFIG_NAME = '610_upgrade_currency_prefs';- protected $description = 'Upgrade user currency preferences';+ protected $description = 'Upgrade user currency preferences';- protected $signature = 'upgrade:610-currency-preferences {--F|force : Force the execution of this command.}';+ protected $signature = 'upgrade:610-currency-preferences {--F|force : Force the execution of this command.}';/*** Execute the console command.@@ -65,7 +67,7 @@ class UpgradesCurrencyPreferences extends Command{$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);if (null !== $configVar) {- return (bool) $configVar->data;+ return (bool)$configVar->data;}return false;@@ -80,7 +82,7 @@ class UpgradesCurrencyPreferences extends Command$this->upgradeGroupPreferences($group);}- $users = User::get();+ $users = User::get();/** @var User $user */foreach ($users as $user) {@@ -104,8 +106,8 @@ class UpgradesCurrencyPreferences extends Commandprivate function upgradeUserPreferences(User $user): void{- $currencies = TransactionCurrency::get();- $enabled = new Collection();+ $currencies = TransactionCurrency::get();+ $enabled = new Collection();/** @var TransactionCurrency $currency */foreach ($currencies as $currency) {@@ -116,10 +118,10 @@ class UpgradesCurrencyPreferences extends Command$user->currencies()->sync($enabled->pluck('id')->toArray());// set the default currency for the user and for the group:- $preference = $this->getPreference($user);- $primaryCurrency = TransactionCurrency::where('code', $preference)->first();- if (null === $primaryCurrency) {- // get EUR+ $preference = $this->getPreference($user);+ try {+ $primaryCurrency = Amount::getTransactionCurrencyByCode($preference);+ } catch (FireflyException) {$primaryCurrency = TransactionCurrency::where('code', 'EUR')->first();}$user->currencies()->updateExistingPivot($primaryCurrency->id, ['user_default' => true]);@@ -135,7 +137,7 @@ class UpgradesCurrencyPreferences extends Command}if (null !== $preference->data && !is_array($preference->data)) {- return (string) $preference->data;+ return (string)$preference->data;}return 'EUR';diff --git a/app/Factory/TransactionCurrencyFactory.php b/app/Factory/TransactionCurrencyFactory.phpindex b4088e200d..9dadc71fc1 100644--- a/app/Factory/TransactionCurrencyFactory.php+++ b/app/Factory/TransactionCurrencyFactory.php@@ -27,6 +27,7 @@ namespace FireflyIII\Factory;use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\TransactionCurrency;use Illuminate\Database\QueryException;+use Illuminate\Support\Facades\Log;/*** Class TransactionCurrencyFactory@@ -48,7 +49,7 @@ class TransactionCurrencyFactoryif (1 === $count) {$old = TransactionCurrency::withTrashed()->whereCode($data['code'])->first();$old->forceDelete();- app('log')->warning(sprintf('Force deleted old currency with ID #%d and code "%s".', $old->id, $data['code']));+ Log::warning(sprintf('Force deleted old currency with ID #%d and code "%s".', $old->id, $data['code']));}try {@@ -64,8 +65,8 @@ class TransactionCurrencyFactory);} catch (QueryException $e) {$result = null;- app('log')->error(sprintf('Could not create new currency: %s', $e->getMessage()));- app('log')->error($e->getTraceAsString());+ Log::error(sprintf('Could not create new currency: %s', $e->getMessage()));+ Log::error($e->getTraceAsString());throw new FireflyException('400004: Could not store new currency.', 0, $e);}@@ -79,7 +80,7 @@ class TransactionCurrencyFactory$currencyId = (int) $currencyId;if ('' === $currencyCode && 0 === $currencyId) {- app('log')->debug('Cannot find anything on empty currency code and empty currency ID!');+ Log::debug('Cannot find anything on empty currency code and empty currency ID!');return null;}@@ -90,7 +91,7 @@ class TransactionCurrencyFactoryif (null !== $currency) {return $currency;}- app('log')->warning(sprintf('Currency ID is %d but found nothing!', $currencyId));+ Log::warning(sprintf('Currency ID is %d but found nothing!', $currencyId));}// then by code:if ('' !== $currencyCode) {@@ -98,9 +99,9 @@ class TransactionCurrencyFactoryif (null !== $currency) {return $currency;}- app('log')->warning(sprintf('Currency code is %d but found nothing!', $currencyCode));+ Log::warning(sprintf('Currency code is %d but found nothing!', $currencyCode));}- app('log')->warning('Found nothing for currency.');+ Log::warning('Found nothing for currency.');return null;}diff --git a/app/Http/Middleware/InterestingMessage.php b/app/Http/Middleware/InterestingMessage.phpindex 30c9b65e68..d516459560 100644--- a/app/Http/Middleware/InterestingMessage.php+++ b/app/Http/Middleware/InterestingMessage.php@@ -25,14 +25,15 @@ declare(strict_types=1);namespace FireflyIII\Http\Middleware;use Closure;+use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\Account;use FireflyIII\Models\Bill;use FireflyIII\Models\GroupMembership;-use FireflyIII\Models\TransactionCurrency;use FireflyIII\Models\TransactionGroup;use FireflyIII\Models\TransactionJournal;use FireflyIII\Models\UserGroup;use FireflyIII\Models\Webhook;+use FireflyIII\Support\Facades\Amount;use FireflyIII\User;use Illuminate\Http\Request;@@ -103,33 +104,33 @@ class InterestingMessage// send message about newly created transaction group./** @var null|TransactionGroup $group */- $group = auth()->user()->transactionGroups()->with(['transactionJournals', 'transactionJournals.transactionType'])->find((int) $transactionGroupId);+ $group = auth()->user()->transactionGroups()->with(['transactionJournals', 'transactionJournals.transactionType'])->find((int)$transactionGroupId);if (null === $group) {return;}- $count = $group->transactionJournals->count();+ $count = $group->transactionJournals->count();/** @var null|TransactionJournal $journal */- $journal = $group->transactionJournals->first();+ $journal = $group->transactionJournals->first();if (null === $journal) {return;}- $title = $count > 1 ? $group->title : $journal->description;+ $title = $count > 1 ? $group->title : $journal->description;if ('created' === $message) {session()->flash('success_url', route('transactions.show', [$transactionGroupId]));- session()->flash('success', (string) trans('firefly.stored_journal', ['description' => $title]));+ session()->flash('success', (string)trans('firefly.stored_journal', ['description' => $title]));}if ('updated' === $message) {- $type = strtolower((string) $journal->transactionType->type);+ $type = strtolower((string)$journal->transactionType->type);session()->flash('success_url', route('transactions.show', [$transactionGroupId]));- session()->flash('success', (string) trans(sprintf('firefly.updated_%s', $type), ['description' => $title]));+ session()->flash('success', (string)trans(sprintf('firefly.updated_%s', $type), ['description' => $title]));}if ('no_change' === $message) {- $type = strtolower((string) $journal->transactionType->type);+ $type = strtolower((string)$journal->transactionType->type);session()->flash('warning_url', route('transactions.show', [$transactionGroupId]));- session()->flash('warning', (string) trans(sprintf('firefly.no_changes_%s', $type), ['description' => $title]));+ session()->flash('warning', (string)trans(sprintf('firefly.no_changes_%s', $type), ['description' => $title]));}}@@ -149,7 +150,7 @@ class InterestingMessage$message = $request->get('message');/** @var User $user */- $user = auth()->user();+ $user = auth()->user();/** @var null|UserGroup $userGroup */$userGroup = UserGroup::find($userGroupId);@@ -170,13 +171,13 @@ class InterestingMessageif ('deleted' === $message) {- session()->flash('success', (string) trans('firefly.flash_administration_deleted', ['title' => $userGroup->title]));+ session()->flash('success', (string)trans('firefly.flash_administration_deleted', ['title' => $userGroup->title]));}if ('created' === $message) {- session()->flash('success', (string) trans('firefly.flash_administration_created', ['title' => $userGroup->title]));+ session()->flash('success', (string)trans('firefly.flash_administration_created', ['title' => $userGroup->title]));}if ('updated' === $message) {- session()->flash('success', (string) trans('firefly.flash_administration_updated', ['title' => $userGroup->title]));+ session()->flash('success', (string)trans('firefly.flash_administration_updated', ['title' => $userGroup->title]));}}@@ -196,22 +197,22 @@ class InterestingMessage$message = $request->get('message');/** @var User $user */- $user = auth()->user();+ $user = auth()->user();/** @var null|Account $account */- $account = $user->accounts()->withTrashed()->find($accountId);+ $account = $user->accounts()->withTrashed()->find($accountId);if (null === $account) {return;}if ('deleted' === $message) {- session()->flash('success', (string) trans('firefly.account_deleted', ['name' => $account->name]));+ session()->flash('success', (string)trans('firefly.account_deleted', ['name' => $account->name]));}if ('created' === $message) {- session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name]));+ session()->flash('success', (string)trans('firefly.stored_new_account', ['name' => $account->name]));}if ('updated' === $message) {- session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name]));+ session()->flash('success', (string)trans('firefly.updated_account', ['name' => $account->name]));}}@@ -231,16 +232,16 @@ class InterestingMessage$message = $request->get('message');/** @var null|Bill $bill */- $bill = auth()->user()->bills()->withTrashed()->find($billId);+ $bill = auth()->user()->bills()->withTrashed()->find($billId);if (null === $bill) {return;}if ('deleted' === $message) {- session()->flash('success', (string) trans('firefly.deleted_bill', ['name' => $bill->name]));+ session()->flash('success', (string)trans('firefly.deleted_bill', ['name' => $bill->name]));}if ('created' === $message) {- session()->flash('success', (string) trans('firefly.stored_new_bill', ['name' => $bill->name]));+ session()->flash('success', (string)trans('firefly.stored_new_bill', ['name' => $bill->name]));}}@@ -260,19 +261,19 @@ class InterestingMessage$message = $request->get('message');/** @var null|Webhook $webhook */- $webhook = auth()->user()->webhooks()->withTrashed()->find($webhookId);+ $webhook = auth()->user()->webhooks()->withTrashed()->find($webhookId);if (null === $webhook) {return;}if ('deleted' === $message) {- session()->flash('success', (string) trans('firefly.deleted_webhook', ['title' => $webhook->title]));+ session()->flash('success', (string)trans('firefly.deleted_webhook', ['title' => $webhook->title]));}if ('updated' === $message) {- session()->flash('success', (string) trans('firefly.updated_webhook', ['title' => $webhook->title]));+ session()->flash('success', (string)trans('firefly.updated_webhook', ['title' => $webhook->title]));}if ('created' === $message) {- session()->flash('success', (string) trans('firefly.stored_new_webhook', ['title' => $webhook->title]));+ session()->flash('success', (string)trans('firefly.stored_new_webhook', ['title' => $webhook->title]));}}@@ -289,32 +290,31 @@ class InterestingMessage{// params:// get parameters from request.- $code = $request->get('code');- $message = $request->get('message');-- /** @var null|TransactionCurrency $currency */- $currency = TransactionCurrency::whereCode($code)->first();-- if (null === $currency) {+ $code = (string) $request->get('code');+ $message = (string) $request->get('message');+ try {+ $currency = Amount::getTransactionCurrencyByCode($code);+ } catch (FireflyException) {return;}+if ('enabled' === $message) {- session()->flash('success', (string) trans('firefly.currency_is_now_enabled', ['name' => $currency->name]));+ session()->flash('success', (string)trans('firefly.currency_is_now_enabled', ['name' => $currency->name]));}if ('enable_failed' === $message) {- session()->flash('error', (string) trans('firefly.could_not_enable_currency', ['name' => $currency->name]));+ session()->flash('error', (string)trans('firefly.could_not_enable_currency', ['name' => $currency->name]));}if ('disabled' === $message) {- session()->flash('success', (string) trans('firefly.currency_is_now_disabled', ['name' => $currency->name]));+ session()->flash('success', (string)trans('firefly.currency_is_now_disabled', ['name' => $currency->name]));}if ('disable_failed' === $message) {- session()->flash('error', (string) trans('firefly.could_not_disable_currency', ['name' => $currency->name]));+ session()->flash('error', (string)trans('firefly.could_not_disable_currency', ['name' => $currency->name]));}if ('default' === $message) {- session()->flash('success', (string) trans('firefly.new_default_currency', ['name' => $currency->name]));+ session()->flash('success', (string)trans('firefly.new_default_currency', ['name' => $currency->name]));}if ('default_failed' === $message) {- session()->flash('error', (string) trans('firefly.default_currency_failed', ['name' => $currency->name]));+ session()->flash('error', (string)trans('firefly.default_currency_failed', ['name' => $currency->name]));}}}diff --git a/app/Http/Requests/PiggyBankStoreRequest.php b/app/Http/Requests/PiggyBankStoreRequest.phpindex bf4da65cad..3aab00827e 100644--- a/app/Http/Requests/PiggyBankStoreRequest.php+++ b/app/Http/Requests/PiggyBankStoreRequest.php@@ -23,6 +23,7 @@ declare(strict_types=1);namespace FireflyIII\Http\Requests;+use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Repositories\Account\AccountRepositoryInterface;use FireflyIII\Rules\IsValidPositiveAmount;@@ -60,7 +61,7 @@ class PiggyBankStoreRequest extends FormRequest$accounts = [];}foreach ($accounts as $item) {- $data['accounts'][] = ['account_id' => (int) $item];+ $data['accounts'][] = ['account_id' => (int)$item];}return $data;@@ -97,7 +98,7 @@ class PiggyBankStoreRequest extends FormRequest$repository = app(AccountRepositoryInterface::class);$types = config('firefly.piggy_bank_account_types');foreach ($data['accounts'] as $value) {- $accountId = (int) $value;+ $accountId = (int)$value;$account = $repository->find($accountId);if (null !== $account) {// check currency here.@@ -106,7 +107,7 @@ class PiggyBankStoreRequest extends FormRequestif ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) {$validator->errors()->add('accounts', trans('validation.invalid_account_currency'));}- $type = $account->accountType->type;+ $type = $account->accountType->type;if (!in_array($type, $types, true)) {$validator->errors()->add('accounts', trans('validation.invalid_account_type'));}@@ -123,9 +124,10 @@ class PiggyBankStoreRequest extends FormRequestprivate function getCurrencyFromData(array $data): TransactionCurrency{- $currencyId = (int) ($data['transaction_currency_id'] ?? 0);- $currency = TransactionCurrency::find($currencyId);- if (null === $currency) {+ $currencyId = (int)($data['transaction_currency_id'] ?? 0);+ try {+ $currency = Amount::getTransactionCurrencyById($currencyId);+ } catch (FireflyException) {return Amount::getPrimaryCurrency();}diff --git a/app/Http/Requests/PiggyBankUpdateRequest.php b/app/Http/Requests/PiggyBankUpdateRequest.phpindex c7e1da285a..f23adf55a1 100644--- a/app/Http/Requests/PiggyBankUpdateRequest.php+++ b/app/Http/Requests/PiggyBankUpdateRequest.php@@ -23,6 +23,7 @@ declare(strict_types=1);namespace FireflyIII\Http\Requests;+use FireflyIII\Exceptions\FireflyException;use Illuminate\Validation\Validator;use FireflyIII\Models\PiggyBank;use FireflyIII\Models\TransactionCurrency;@@ -129,8 +130,9 @@ class PiggyBankUpdateRequest extends FormRequestprivate function getCurrencyFromData(array $data): TransactionCurrency{$currencyId = (int) ($data['transaction_currency_id'] ?? 0);- $currency = TransactionCurrency::find($currencyId);- if (null === $currency) {+ try {+ $currency = Amount::getTransactionCurrencyById($currencyId);+ } catch (FireflyException) {return Amount::getPrimaryCurrency();}diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.phpindex 408954e44e..c9039b7c0f 100644--- a/app/Repositories/Account/AccountRepository.php+++ b/app/Repositories/Account/AccountRepository.php@@ -38,6 +38,7 @@ use FireflyIII\Models\TransactionGroup;use FireflyIII\Models\TransactionJournal;use FireflyIII\Services\Internal\Destroy\AccountDestroyService;use FireflyIII\Services\Internal\Update\AccountUpdateService;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Facades\Steam;use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface;use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait;@@ -400,7 +401,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac}$currencyId = (int) $this->getMetaValue($account, 'currency_id');if ($currencyId > 0) {- return TransactionCurrency::find($currencyId);+ return Amount::getTransactionCurrencyById($currencyId);}return null;diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.phpindex 052a6622b8..33a2afc27a 100644--- a/app/Repositories/Budget/OperationsRepository.php+++ b/app/Repositories/Budget/OperationsRepository.php@@ -166,7 +166,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn$currencyDecimalPlaces = $journal['currency_decimal_places'];}if (true === $convertToPrimary && $journalCurrencyId !== $currencyId) {- $currencies[$journalCurrencyId] ??= TransactionCurrency::find($journalCurrencyId);+ $currencies[$journalCurrencyId] ??= Amount::getTransactionCurrencyById($journalCurrencyId);$amount = $converter->convert($currencies[$journalCurrencyId], $primaryCurrency, $journal['date'], $amount);}diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.phpindex 3d623f760a..34304e39db 100644--- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php+++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php@@ -24,6 +24,7 @@ declare(strict_types=1);namespace FireflyIII\Repositories\PiggyBank;+use Exception;use FireflyIII\Events\Model\PiggyBank\ChangedAmount;use FireflyIII\Events\Model\PiggyBank\ChangedName;use FireflyIII\Exceptions\FireflyException;@@ -32,12 +33,11 @@ use FireflyIII\Models\Account;use FireflyIII\Models\Note;use FireflyIII\Models\PiggyBank;use FireflyIII\Models\Transaction;-use FireflyIII\Models\TransactionCurrency;use FireflyIII\Models\TransactionJournal;use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Http\Api\ExchangeRateConverter;use Illuminate\Support\Facades\Log;-use Exception;/*** Trait ModifiesPiggyBanks@@ -71,9 +71,9 @@ trait ModifiesPiggyBanks$pivot->native_current_amount = null;// also update native_current_amount.- $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup);+ $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup);if ($userCurrency->id !== $piggyBank->transaction_currency_id) {- $converter = new ExchangeRateConverter();+ $converter = new ExchangeRateConverter();$converter->setIgnoreSettings(true);$pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount);}@@ -94,9 +94,9 @@ trait ModifiesPiggyBanks$pivot->native_current_amount = null;// also update native_current_amount.- $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup);+ $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup);if ($userCurrency->id !== $piggyBank->transaction_currency_id) {- $converter = new ExchangeRateConverter();+ $converter = new ExchangeRateConverter();$converter->setIgnoreSettings(true);$pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount);}@@ -128,8 +128,8 @@ trait ModifiesPiggyBanksLog::debug(sprintf('Maximum amount: %s', $maxAmount));}- $compare = bccomp($amount, $maxAmount);- $result = $compare <= 0;+ $compare = bccomp($amount, $maxAmount);+ $result = $compare <= 0;Log::debug(sprintf('Compare <= 0? %d, so canAddAmount is %s', $compare, var_export($result, true)));@@ -163,11 +163,11 @@ trait ModifiesPiggyBankspublic function setCurrentAmount(PiggyBank $piggyBank, string $amount): PiggyBank{- $repetition = $this->getRepetition($piggyBank);+ $repetition = $this->getRepetition($piggyBank);if (null === $repetition) {return $piggyBank;}- $max = $piggyBank->target_amount;+ $max = $piggyBank->target_amount;if (1 === bccomp($amount, $max) && 0 !== bccomp($piggyBank->target_amount, '0')) {$amount = $max;}@@ -210,14 +210,14 @@ trait ModifiesPiggyBankspublic function update(PiggyBank $piggyBank, array $data): PiggyBank{- $piggyBank = $this->updateProperties($piggyBank, $data);+ $piggyBank = $this->updateProperties($piggyBank, $data);if (array_key_exists('notes', $data)) {$this->updateNote($piggyBank, (string)$data['notes']);}// update the order of the piggy bank:- $oldOrder = $piggyBank->order;- $newOrder = (int)($data['order'] ?? $oldOrder);+ $oldOrder = $piggyBank->order;+ $newOrder = (int)($data['order'] ?? $oldOrder);if ($oldOrder !== $newOrder) {$this->setOrder($piggyBank, $newOrder);}@@ -287,7 +287,7 @@ trait ModifiesPiggyBanks$piggyBank->name = $data['name'];}if (array_key_exists('transaction_currency_id', $data) && is_int($data['transaction_currency_id'])) {- $currency = TransactionCurrency::find($data['transaction_currency_id']);+ $currency = Amount::getTransactionCurrencyById($data['transaction_currency_id']);if (null !== $currency) {$piggyBank->transaction_currency_id = $currency->id;}@@ -320,7 +320,7 @@ trait ModifiesPiggyBanksreturn;}- $dbNote = $piggyBank->notes()->first();+ $dbNote = $piggyBank->notes()->first();if (null === $dbNote) {$dbNote = new Note();$dbNote->noteable()->associate($piggyBank);@@ -331,16 +331,15 @@ trait ModifiesPiggyBankspublic function setOrder(PiggyBank $piggyBank, int $newOrder): bool{- $oldOrder = $piggyBank->order;+ $oldOrder = $piggyBank->order;// Log::debug(sprintf('Will move piggy bank #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));if ($newOrder > $oldOrder) {PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')- ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')- ->where('accounts.user_id', $this->user->id)- ->where('piggy_banks.order', '<=', $newOrder)->where('piggy_banks.order', '>', $oldOrder)- ->where('piggy_banks.id', '!=', $piggyBank->id)- ->distinct()->decrement('piggy_banks.order')- ;+ ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')+ ->where('accounts.user_id', $this->user->id)+ ->where('piggy_banks.order', '<=', $newOrder)->where('piggy_banks.order', '>', $oldOrder)+ ->where('piggy_banks.id', '!=', $piggyBank->id)+ ->distinct()->decrement('piggy_banks.order');$piggyBank->order = $newOrder;Log::debug(sprintf('[1] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));@@ -349,12 +348,11 @@ trait ModifiesPiggyBanksreturn true;}PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')- ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')- ->where('accounts.user_id', $this->user->id)- ->where('piggy_banks.order', '>=', $newOrder)->where('piggy_banks.order', '<', $oldOrder)- ->where('piggy_banks.id', '!=', $piggyBank->id)- ->distinct()->increment('piggy_banks.order')- ;+ ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')+ ->where('accounts.user_id', $this->user->id)+ ->where('piggy_banks.order', '>=', $newOrder)->where('piggy_banks.order', '<', $oldOrder)+ ->where('piggy_banks.id', '!=', $piggyBank->id)+ ->distinct()->increment('piggy_banks.order');$piggyBank->order = $newOrder;Log::debug(sprintf('[2] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));@@ -375,7 +373,7 @@ trait ModifiesPiggyBanks}// if this account contains less than the amount, remove the current amount, update the amount and continue.$this->removeAmount($piggyBank, $account, $current);- $amount = bcsub($amount, (string)$current);+ $amount = bcsub($amount, (string)$current);}}}diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.phpindex e0eb3fe31f..3d0d7a6989 100644--- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php+++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php@@ -354,7 +354,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,->first();if (null !== $currencyPreference) {- $currency = TransactionCurrency::where('id', $currencyPreference->data)->first();+ $currency = Amount::getTransactionCurrencyById((int) $currencyPreference->data);}$journalId = $row->transaction_journal_id;$return[$journalId] ??= [];diff --git a/app/Repositories/UserGroups/Account/AccountRepository.php b/app/Repositories/UserGroups/Account/AccountRepository.phpindex 28b38e4c02..23cae6e820 100644--- a/app/Repositories/UserGroups/Account/AccountRepository.php+++ b/app/Repositories/UserGroups/Account/AccountRepository.php@@ -32,6 +32,7 @@ use FireflyIII\Models\ObjectGroup;use FireflyIII\Models\Transaction;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Services\Internal\Update\AccountUpdateService;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Facades\Steam;use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait;use Illuminate\Database\Eloquent\Builder as EloquentBuilder;@@ -141,7 +142,7 @@ class AccountRepository implements AccountRepositoryInterface}$currencyId = (int) $this->getMetaValue($account, 'currency_id');if ($currencyId > 0) {- return TransactionCurrency::find($currencyId);+ return Amount::getTransactionCurrencyById($currencyId);}return null;diff --git a/app/Support/Amount.php b/app/Support/Amount.phpindex e4edc5c4fb..a9b81392e1 100644--- a/app/Support/Amount.php+++ b/app/Support/Amount.php@@ -29,11 +29,11 @@ use FireflyIII\Models\TransactionCurrency;use FireflyIII\Models\TransactionJournal;use FireflyIII\Models\UserGroup;use FireflyIII\Support\Facades\Preferences;+use FireflyIII\Support\Facades\Steam;use FireflyIII\Support\Singleton\PreferencesSingleton;use FireflyIII\User;use Illuminate\Support\Collection;use NumberFormatter;-use FireflyIII\Support\Facades\Steam;/*** Class Amount.@@ -59,15 +59,15 @@ class Amount*/public function formatFlat(string $symbol, int $decimalPlaces, string $amount, ?bool $coloured = null): string{- $locale = Steam::getLocale();- $rounded = Steam::bcround($amount, $decimalPlaces);+ $locale = Steam::getLocale();+ $rounded = Steam::bcround($amount, $decimalPlaces);$coloured ??= true;- $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY);+ $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY);$fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, $symbol);$fmt->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimalPlaces);$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces);- $result = (string)$fmt->format((float)$rounded); // intentional float+ $result = (string)$fmt->format((float)$rounded); // intentional floatif (true === $coloured) {if (1 === bccomp($rounded, '0')) {@@ -85,7 +85,7 @@ class Amountpublic function formatByCurrencyId(int $currencyId, string $amount, ?bool $coloured = null): string{- $format = TransactionCurrency::find($currencyId);+ $format = $this->getTransactionCurrencyById($currencyId);return $this->formatFlat($format->symbol, $format->decimal_places, $amount, $coloured);}@@ -115,6 +115,40 @@ class Amountreturn (string)$amount;}+ public function getTransactionCurrencyById(int $currencyId): TransactionCurrency+ {+ $instance = PreferencesSingleton::getInstance();+ $key = sprintf('transaction_currency_%d', $currencyId);+ /** @var TransactionCurrency|null $pref */+ $pref = $instance->getPreference($key);+ if (null !== $pref) {+ return $pref;+ }+ $currency = TransactionCurrency::find($currencyId);+ if (null === $currency) {+ throw new FireflyException(sprintf('Could not find a transaction currency with ID #%d', $currencyId));+ }+ $instance->setPreference($key, $currency);+ return $currency;+ }++ public function getTransactionCurrencyByCode(string $code): TransactionCurrency+ {+ $instance = PreferencesSingleton::getInstance();+ $key = sprintf('transaction_currency_%s', $code);+ /** @var TransactionCurrency|null $pref */+ $pref = $instance->getPreference($key);+ if (null !== $pref) {+ return $pref;+ }+ $currency = TransactionCurrency::whereCode($code)->first();+ if (null === $currency) {+ throw new FireflyException(sprintf('Could not find a transaction currency with code "%s"', $code));+ }+ $instance->setPreference($key, $currency);+ return $currency;+ }+public function convertToPrimary(?User $user = null): bool{$instance = PreferencesSingleton::getInstance();@@ -129,8 +163,8 @@ class Amountreturn $pref;}- $key = sprintf('convert_to_primary_%d', $user->id);- $pref = $instance->getPreference($key);+ $key = sprintf('convert_to_primary_%d', $user->id);+ $pref = $instance->getPreference($key);if (null === $pref) {$res = true === Preferences::getForUser($user, 'convert_to_primary', false)->data && true === config('cer.enabled');$instance->setPreference($key, $res);@@ -156,7 +190,7 @@ class Amountpublic function getPrimaryCurrencyByUserGroup(UserGroup $userGroup): TransactionCurrency{- $cache = new CacheProperties();+ $cache = new CacheProperties();$cache->addProperty('getPrimaryCurrencyByGroup');$cache->addProperty($userGroup->id);if ($cache->has()) {@@ -186,16 +220,16 @@ class Amount*/public function getAmountFromJournalObject(TransactionJournal $journal): string{- $convertToPrimary = $this->convertToPrimary();- $currency = $this->getPrimaryCurrency();- $field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'pc_amount' : 'amount';+ $convertToPrimary = $this->convertToPrimary();+ $currency = $this->getPrimaryCurrency();+ $field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'pc_amount' : 'amount';/** @var null|Transaction $sourceTransaction */$sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();if (null === $sourceTransaction) {return '0';}- $amount = $sourceTransaction->{$field} ?? '0';+ $amount = $sourceTransaction->{$field} ?? '0';if ((int)$sourceTransaction->foreign_currency_id === $currency->id) {// use foreign amount instead!$amount = (string)$sourceTransaction->foreign_amount; // hard coded to be foreign amount.@@ -243,20 +277,20 @@ class Amountprivate function getLocaleInfo(): array{// get config from preference, not from translation:- $locale = Steam::getLocale();- $array = Steam::getLocaleArray($locale);+ $locale = Steam::getLocale();+ $array = Steam::getLocaleArray($locale);setlocale(LC_MONETARY, $array);- $info = localeconv();+ $info = localeconv();// correct variables- $info['n_cs_precedes'] = $this->getLocaleField($info, 'n_cs_precedes');- $info['p_cs_precedes'] = $this->getLocaleField($info, 'p_cs_precedes');+ $info['n_cs_precedes'] = $this->getLocaleField($info, 'n_cs_precedes');+ $info['p_cs_precedes'] = $this->getLocaleField($info, 'p_cs_precedes');- $info['n_sep_by_space'] = $this->getLocaleField($info, 'n_sep_by_space');- $info['p_sep_by_space'] = $this->getLocaleField($info, 'p_sep_by_space');+ $info['n_sep_by_space'] = $this->getLocaleField($info, 'n_sep_by_space');+ $info['p_sep_by_space'] = $this->getLocaleField($info, 'p_sep_by_space');- $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY);+ $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY);$info['mon_decimal_point'] = $fmt->getSymbol(NumberFormatter::MONETARY_SEPARATOR_SYMBOL);$info['mon_thousands_sep'] = $fmt->getSymbol(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL);@@ -288,11 +322,11 @@ class Amount// there are five possible positions for the "+" or "-" sign (if it is even used)// pos_a and pos_e could be the ( and ) symbol.- $posA = ''; // before everything- $posB = ''; // before currency symbol- $posC = ''; // after currency symbol- $posD = ''; // before amount- $posE = ''; // after everything+ $posA = ''; // before everything+ $posB = ''; // before currency symbol+ $posC = ''; // after currency symbol+ $posD = ''; // before amount+ $posE = ''; // after everything// format would be (currency before amount)// AB%sC_D%vE@@ -334,9 +368,9 @@ class Amount}if ($csPrecedes) {- return $posA.$posB.'%s'.$posC.$space.$posD.'%v'.$posE;+ return $posA . $posB . '%s' . $posC . $space . $posD . '%v' . $posE;}- return $posA.$posD.'%v'.$space.$posB.'%s'.$posC.$posE;+ return $posA . $posD . '%v' . $space . $posB . '%s' . $posC . $posE;}}diff --git a/app/Support/Balance.php b/app/Support/Balance.phpindex 188a967ba6..6b97a04628 100644--- a/app/Support/Balance.php+++ b/app/Support/Balance.php@@ -26,7 +26,7 @@ namespace FireflyIII\Support;use Carbon\Carbon;use FireflyIII\Models\Transaction;-use FireflyIII\Models\TransactionCurrency;+use FireflyIII\Support\Facades\Amount;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Log;@@ -61,7 +61,7 @@ class Balanceforeach ($result as $entry) {$accountId = (int) $entry->account_id;$currencyId = (int) $entry->transaction_currency_id;- $currencies[$currencyId] ??= TransactionCurrency::find($currencyId);+ $currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId);$return[$accountId] ??= [];if (array_key_exists($currencyId, $return[$accountId])) {continue;diff --git a/app/Support/Binder/CurrencyCode.php b/app/Support/Binder/CurrencyCode.phpindex cc5000ede6..61fcb79528 100644--- a/app/Support/Binder/CurrencyCode.php+++ b/app/Support/Binder/CurrencyCode.php@@ -23,7 +23,9 @@ declare(strict_types=1);namespace FireflyIII\Support\Binder;+use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\TransactionCurrency;+use FireflyIII\Support\Facades\Amount;use Illuminate\Routing\Route;use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;@@ -38,10 +40,12 @@ class CurrencyCode implements BinderInterfacepublic static function routeBinder(string $value, Route $route): TransactionCurrency{if (auth()->check()) {- $currency = TransactionCurrency::where('code', trim($value))->first();- if (null !== $currency) {- return $currency;+ try {+ $currency = Amount::getTransactionCurrencyByCode(trim($value));+ } catch(FireflyException) {+ throw new NotFoundHttpException();}+ return $currency;}throw new NotFoundHttpException();diff --git a/app/Support/Http/Api/AccountBalanceGrouped.php b/app/Support/Http/Api/AccountBalanceGrouped.phpindex 4ef803e957..839c87bfb0 100644--- a/app/Support/Http/Api/AccountBalanceGrouped.php+++ b/app/Support/Http/Api/AccountBalanceGrouped.php@@ -28,6 +28,7 @@ use Carbon\Carbon;use FireflyIII\Enums\TransactionTypeEnum;use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\TransactionCurrency;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Facades\Navigation;use FireflyIII\Support\Facades\Steam;use Illuminate\Support\Collection;@@ -184,7 +185,7 @@ class AccountBalanceGroupedif (array_key_exists($currencyId, $this->currencies)) {return $this->currencies[$currencyId];}- $this->currencies[$currencyId] = TransactionCurrency::find($currencyId);+ $this->currencies[$currencyId] = Amount::getTransactionCurrencyById($currencyId);return $this->currencies[$currencyId];}diff --git a/app/Support/Http/Api/ExchangeRateConverter.php b/app/Support/Http/Api/ExchangeRateConverter.phpindex c783f36dbe..d992be48de 100644--- a/app/Support/Http/Api/ExchangeRateConverter.php+++ b/app/Support/Http/Api/ExchangeRateConverter.php@@ -30,6 +30,7 @@ use FireflyIII\Models\CurrencyExchangeRate;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Models\UserGroup;use FireflyIII\Support\CacheProperties;+use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Facades\Steam;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Log;@@ -264,7 +265,7 @@ class ExchangeRateConverterif ($cache->has()) {return (int) $cache->get();}- $euro = TransactionCurrency::whereCode('EUR')->first();+ $euro = Amount::getTransactionCurrencyByCode('EUR');++$this->queryCount;if (null === $euro) {throw new FireflyException('Cannot find EUR in system, cannot do currency conversion.');diff --git a/app/Support/Http/Api/SummaryBalanceGrouped.php b/app/Support/Http/Api/SummaryBalanceGrouped.phpindex 6fc534b59a..b50ab2160e 100644--- a/app/Support/Http/Api/SummaryBalanceGrouped.php+++ b/app/Support/Http/Api/SummaryBalanceGrouped.php@@ -26,6 +26,7 @@ namespace FireflyIII\Support\Http\Api;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;+use FireflyIII\Support\Facades\Amount;use Illuminate\Support\Facades\Log;class SummaryBalanceGrouped@@ -110,7 +111,7 @@ class SummaryBalanceGrouped// transaction info:$currencyId = (int) $journal['currency_id'];$amount = bcmul((string) $journal['amount'], $multiplier);- $currency = $this->currencies[$currencyId] ?? TransactionCurrency::find($currencyId);+ $currency = $this->currencies[$currencyId] ?? Amount::getTransactionCurrencyById($currencyId);$this->currencies[$currencyId] = $currency;$pcAmount = $converter->convert($currency, $this->default, $journal['date'], $amount);if ((int) $journal['foreign_currency_id'] === $this->default->id) {diff --git a/app/Support/Http/Api/ValidatesUserGroupTrait.php b/app/Support/Http/Api/ValidatesUserGroupTrait.phpindex c33be45a1e..6ce611396d 100644--- a/app/Support/Http/Api/ValidatesUserGroupTrait.php+++ b/app/Support/Http/Api/ValidatesUserGroupTrait.php@@ -38,8 +38,8 @@ use Illuminate\Support\Facades\Log;*/trait ValidatesUserGroupTrait{- protected ?UserGroup $userGroup = null;- protected ?User $user = null;+ protected UserGroup $userGroup;+ protected User $user;/*** An "undocumented" filterdiff --git a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.phpindex 8e904717b0..e4e01b214c 100644--- a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php+++ b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php@@ -142,7 +142,7 @@ class PiggyBankEnrichment implements EnrichmentInterface$accountId = (int)$item->account_id;$currencyId = (int)$item->data;if (!array_key_exists($currencyId, $this->currencies)) {- $this->currencies[$currencyId] = TransactionCurrency::find($currencyId);+ $this->currencies[$currencyId] = Amount::getTransactionCurrencyById($currencyId);}// $this->accountCurrencies[$accountId] = $this->currencies[$currencyId];}diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.phpindex 196bed56d0..8aff973ccf 100644--- a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php+++ b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php@@ -121,7 +121,7 @@ class PiggyBankEventEnrichment implements EnrichmentInterface$accountId = (int)$item->account_id;$currencyId = (int)$item->data;if (!array_key_exists($currencyId, $this->currencies)) {- $this->currencies[$currencyId] = TransactionCurrency::find($currencyId);+ $this->currencies[$currencyId] = Amount::getTransactionCurrencyById($currencyId);}$this->accountCurrencies[$accountId] = $this->currencies[$currencyId];}diff --git a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.phpindex 03003429bb..727f51bced 100644--- a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php+++ b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php@@ -321,7 +321,7 @@ class SubscriptionEnrichment implements EnrichmentInterfaceif ($this->convertToPrimary && null !== $entry->foreign_currency_id && (int)$entry->foreign_currency_id !== $this->primaryCurrency->id) {// TODO this is very database intensive./** @var TransactionCurrency $foreignCurrency */- $foreignCurrency = TransactionCurrency::find($entry->foreign_currency_id);+ $foreignCurrency = Amount::getTransactionCurrencyById($entry->foreign_currency_id);$array['pc_foreign_amount'] = $converter->convert($foreignCurrency, $this->primaryCurrency, $entry->date, $entry->amount);}$result[] = $array;diff --git a/app/Support/Models/AccountBalanceCalculator.php b/app/Support/Models/AccountBalanceCalculator.phpindex f4ae008911..0fc8abd843 100644--- a/app/Support/Models/AccountBalanceCalculator.php+++ b/app/Support/Models/AccountBalanceCalculator.php@@ -30,6 +30,7 @@ use FireflyIII\Models\AccountBalance;use FireflyIII\Models\Transaction;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Models\TransactionJournal;+use FireflyIII\Support\Facades\Amount;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Log;@@ -171,7 +172,7 @@ class AccountBalanceCalculator*/foreach ($currencies as $currencyId => $balance) {/** @var null|TransactionCurrency $currency */- $currency = TransactionCurrency::find($currencyId);+ $currency = Amount::getTransactionCurrencyById($currencyId);if (null === $currency) {Log::error(sprintf('Could not find currency #%d, will not save account balance.', $currencyId));diff --git a/app/Support/Steam.php b/app/Support/Steam.phpindex 039e16c0be..ac09212308 100644--- a/app/Support/Steam.php+++ b/app/Support/Steam.php@@ -285,7 +285,7 @@ class Steam$sumOfDay = $this->floatalize($sumOfDay);// find currency of this entry, does not have to exist.- $currencies[$entry->transaction_currency_id] ??= TransactionCurrency::find($entry->transaction_currency_id);+ $currencies[$entry->transaction_currency_id] ??= Amount::getTransactionCurrencyById($entry->transaction_currency_id);// make sure this $entry has its own $entryCurrency/** @var TransactionCurrency $entryCurrency */@@ -502,7 +502,7 @@ class Steamreturn null;}- return TransactionCurrency::find((int)$result->data);+ return Amount::getTransactionCurrencyById((int)$result->data);}private function groupAndSumTransactions(array $array, string $group, string $field): array@@ -524,7 +524,7 @@ class Steam$singleton = PreferencesSingleton::getInstance();foreach ($others as $key => $amount) {$preference = $singleton->getPreference($key);- $currency = $preference ?? TransactionCurrency::where('code', $key)->first();+ $currency = $preference ?? Amount::getTransactionCurrencyByCode($key);if (null === $currency) {continue;}diff --git a/app/Support/Twig/AmountFormat.php b/app/Support/Twig/AmountFormat.phpindex 3f7b9b8acf..6e1219c79c 100644--- a/app/Support/Twig/AmountFormat.php+++ b/app/Support/Twig/AmountFormat.php@@ -162,9 +162,9 @@ class AmountFormat extends AbstractExtensionstatic function (string $amount, string $code, ?bool $coloured = null): string {$coloured ??= true;- /** @var null|TransactionCurrency $currency */- $currency = TransactionCurrency::whereCode($code)->first();- if (null === $currency) {+ try {+ $currency = Amount::getTransactionCurrencyByCode($code);+ } catch(FireflyException) {Log::error(sprintf('Could not find currency with code "%s". Fallback to primary currency.', $code));$currency = Amount::getPrimaryCurrency();Log::error(sprintf('Fallback currency is "%s".', $currency->code));diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.phpindex 86d33e8c83..56eb27dab9 100644--- a/app/Support/Twig/General.php+++ b/app/Support/Twig/General.php@@ -99,7 +99,7 @@ class General extends AbstractExtension}// for multi currency accounts.if ($usePrimary && $key !== $primary->code) {- $strings[] = app('amount')->formatAnything(TransactionCurrency::where('code', $key)->first(), $balance, false);+ $strings[] = app('amount')->formatAnything(Amount::getTransactionCurrencyByCode($key), $balance, false);}}