Skip to content

Firefly III: a personal finances manager

Refactor recalculation service.

James Cole0b33e1ff093b
diff --git a/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php b/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php
index 47c2ae8968..28f7a700c0 100644
--- a/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php
+++ b/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php
@@ -39,6 +39,7 @@ use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\UserGroup;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface;
+use FireflyIII\Services\Internal\Recalculate\PrimaryAmountRecalculationService;
use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Facades\FireflyConfig;
use FireflyIII\Support\Facades\Preferences;
@@ -70,186 +71,13 @@ class CorrectsPrimaryCurrencyAmounts extends Command
Log::debug('Will update all primary currency amounts. This may take some time.');
$this->friendlyWarning('Recalculating primary currency amounts for all objects. This may take some time!');
- /** @var UserGroupRepositoryInterface $repository */
- $repository = app(UserGroupRepositoryInterface::class);
+ $calculator = new PrimaryAmountRecalculationService();
+ $calculator->recalculate();
- Preferences::mark();
-
- /** @var UserGroup $userGroup */
- foreach ($repository->getAll() as $userGroup) {
- $this->recalculateForGroup($userGroup);
- }
$this->friendlyInfo('Recalculated all primary currency amounts.');
return 0;
}
- private function recalculateForGroup(UserGroup $userGroup): void
- {
- Log::debug(sprintf('Now recalculating for user group #%d', $userGroup->id));
- $this->recalculateAccounts($userGroup);
-
- // do a check with the group's currency so we can skip some stuff.
- $currency = Amount::getPrimaryCurrencyByUserGroup($userGroup);
-
- $this->recalculatePiggyBanks($userGroup, $currency);
- $this->recalculateBudgets($userGroup, $currency);
- $this->recalculateAvailableBudgets($userGroup, $currency);
- $this->recalculateBills($userGroup, $currency);
- $this->calculateTransactions($userGroup, $currency);
- }
-
- private function recalculateAccounts(UserGroup $userGroup): void
- {
- $set = $userGroup
- ->accounts()
- ->where(static function (EloquentBuilder $q): void {
- $q->whereNotNull('virtual_balance');
-
- // this needs a different piece of code for postgres.
- if ('pgsql' === config('database.default')) {
- $q->orWhere(DB::raw('CAST(virtual_balance AS TEXT)'), '!=', '');
- }
- if ('pgsql' !== config('database.default')) {
- $q->orWhere('virtual_balance', '!=', '');
- }
- })
- ->get()
- ;
-
- /** @var Account $account */
- foreach ($set as $account) {
- $account->touch();
- }
- Log::debug(sprintf('Recalculated %d accounts for user group #%d.', $set->count(), $userGroup->id));
- }
-
- private function recalculatePiggyBanks(UserGroup $userGroup, TransactionCurrency $currency): void
- {
- $converter = new ExchangeRateConverter();
- $converter->setUserGroup($userGroup);
- $converter->setIgnoreSettings(true);
- $repository = app(PiggyBankRepositoryInterface::class);
- $repository->setUserGroup($userGroup);
- $set = $repository->getPiggyBanks();
- $set = $set->filter(static fn (PiggyBank $piggyBank): bool => $currency->id !== $piggyBank->transaction_currency_id);
- foreach ($set as $piggyBank) {
- $piggyBank->encrypted = false;
- $piggyBank->save();
-
- foreach ($piggyBank->accounts as $account) {
- $account->pivot->native_current_amount = null;
- if (0 !== bccomp((string) $account->pivot->current_amount, '0')) {
- $account->pivot->native_current_amount = $converter->convert(
- $piggyBank->transactionCurrency,
- $currency,
- today(),
- (string) $account->pivot->current_amount
- );
- }
- $account->pivot->save();
- }
- $this->recalculatePiggyBankEvents($piggyBank);
- }
- Log::debug(sprintf('Recalculated %d piggy banks for user group #%d.', $set->count(), $userGroup->id));
- }
-
- private function recalculatePiggyBankEvents(PiggyBank $piggyBank): void
- {
- $set = $piggyBank->piggyBankEvents()->get();
- $set->each(static function (PiggyBankEvent $event): void { // @phpstan-ignore-line
- $event->touch();
- });
- Log::debug(sprintf('Recalculated %d piggy bank events.', $set->count()));
- }
-
- private function recalculateBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
- {
- $set = $userGroup->budgets()->get();
-
- /** @var Budget $budget */
- foreach ($set as $budget) {
- $this->recalculateBudgetLimits($budget, $currency);
- $this->recalculateAutoBudgets($budget, $currency);
- }
- Log::debug(sprintf('Recalculated %d budgets.', $set->count()));
- }
-
- private function recalculateBudgetLimits(Budget $budget, TransactionCurrency $currency): void
- {
- $set = $budget->budgetlimits()->where('transaction_currency_id', '!=', $currency->id)->get();
-
- /** @var BudgetLimit $limit */
- foreach ($set as $limit) {
- Log::debug(sprintf('Will now touch BL #%d', $limit->id));
- $limit->touch();
- Log::debug(sprintf('Done with touch BL #%d', $limit->id));
- }
- Log::debug(sprintf('Recalculated %d budget limits for budget #%d.', $set->count(), $budget->id));
- }
-
- private function recalculateAutoBudgets(Budget $budget, TransactionCurrency $currency): void
- {
- $set = $budget->autoBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
-
- /** @var AutoBudget $autoBudget */
- foreach ($set as $autoBudget) {
- $autoBudget->touch();
- }
- Log::debug(sprintf('Recalculated %d auto budgets for budget #%d.', $set->count(), $budget->id));
- }
-
- private function recalculateAvailableBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
- {
- Log::debug('Start with available budgets.');
- $set = $userGroup->availableBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
-
- /** @var AvailableBudget $budget */
- foreach ($set as $budget) {
- $budget->touch();
- }
- Log::debug(sprintf('Recalculated %d available budgets.', $set->count()));
- }
-
- private function recalculateBills(UserGroup $userGroup, TransactionCurrency $currency): void
- {
- $set = $userGroup->bills()->where('transaction_currency_id', '!=', $currency->id)->get();
- /** @var Bill $bill */
- foreach ($set as $bill) {
- $bill->touch();
- }
- Log::debug(sprintf('Recalculated %d bills.', $set->count()));
- }
-
- private function calculateTransactions(UserGroup $userGroup, TransactionCurrency $currency): void
- {
- // custom query because of the potential size of this update.
- $set = DB::table('transactions')
- ->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
- ->where('transaction_journals.user_group_id', $userGroup->id)
- ->where(static function (DatabaseBuilder $q1) use ($currency): void {
- $q1->where(static function (DatabaseBuilder $q2) use ($currency): void {
- $q2->whereNot('transactions.transaction_currency_id', $currency->id)->whereNull('transactions.foreign_currency_id');
- })->orWhere(static function (DatabaseBuilder $q3) use ($currency): void {
- $q3->whereNot('transactions.transaction_currency_id', $currency->id)->whereNot('transactions.foreign_currency_id', $currency->id);
- });
- })
- // ->where(static function (DatabaseBuilder $q) use ($currency): void {
- // $q->whereNot('transactions.transaction_currency_id', $currency->id)
- // ->whereNot('transactions.foreign_currency_id', $currency->id)
- // ;
- // })
- ->get(['transactions.id'])
- ;
- TransactionObserver::$recalculate = false;
- foreach ($set as $item) {
- // here we are.
- /** @var null|Transaction $transaction */
- $transaction = Transaction::find($item->id);
- $transaction?->touch();
- }
- TransactionObserver::$recalculate = true;
- Log::debug(sprintf('Recalculated %d transactions.', $set->count()));
- }
}
diff --git a/app/Handlers/Events/PreferencesEventHandler.php b/app/Handlers/Events/PreferencesEventHandler.php
index 47ab58adcd..136f484fca 100644
--- a/app/Handlers/Events/PreferencesEventHandler.php
+++ b/app/Handlers/Events/PreferencesEventHandler.php
@@ -38,106 +38,9 @@ use Illuminate\Support\Facades\Log;
class PreferencesEventHandler
{
- public function resetPrimaryCurrencyAmounts(UserGroupChangedPrimaryCurrency $event): void
- {
- // Reset the primary currency amounts for all objects that have it.
- Log::debug('Resetting primary currency amounts for all objects.');
- $tables = [
- // !!! this array is also in the migration
- 'accounts' => ['native_virtual_balance'],
- 'available_budgets' => ['native_amount'],
- 'bills' => ['native_amount_min', 'native_amount_max'],
- ];
- foreach ($tables as $table => $columns) {
- foreach ($columns as $column) {
- Log::debug(sprintf('Resetting column %s in table %s.', $column, $table));
- DB::table($table)->where('user_group_id', $event->userGroup->id)->update([$column => null]);
- }
- }
- $this->resetPiggyBanks($event->userGroup);
- $this->resetBudgets($event->userGroup);
- $this->resetTransactions($event->userGroup);
- // fire laravel command to recalculate them all.
- if (Amount::convertToPrimary()) {
- Log::debug('Will now convert to primary currency.');
- Artisan::call('correction:recalculate-pc-amounts');
- return;
- }
- Log::debug('Will NOT convert to primary currency.');
- }
- private function resetPiggyBanks(UserGroup $userGroup): void
- {
- $repository = app(PiggyBankRepositoryInterface::class);
- $repository->setUserGroup($userGroup);
- $piggyBanks = $repository->getPiggyBanks();
- Log::debug(sprintf('Resetting %d piggy bank(s).', $piggyBanks->count()));
- /** @var PiggyBank $piggyBank */
- foreach ($piggyBanks as $piggyBank) {
- if (null !== $piggyBank->native_target_amount) {
- Log::debug(sprintf('Resetting native_target_amount for piggy bank #%d.', $piggyBank->id));
- $piggyBank->native_target_amount = null;
- $piggyBank->saveQuietly();
- }
- foreach ($piggyBank->accounts as $account) {
- if (null !== $account->pivot->native_current_amount) {
- Log::debug(sprintf('Resetting native_current_amount for piggy bank #%d and account #%d.', $piggyBank->id, $account->id));
- $account->pivot->native_current_amount = null;
- $account->pivot->save();
- }
- }
- foreach ($piggyBank->piggyBankEvents as $event) {
- if (null !== $event->native_amount) {
- Log::debug(sprintf('Resetting native_amount for piggy bank #%d and event #%d.', $piggyBank->id, $event->id));
- $event->native_amount = null;
- $event->saveQuietly();
- }
- }
- }
- }
- private function resetBudgets(UserGroup $userGroup): void
- {
- $repository = app(BudgetRepositoryInterface::class);
- $repository->setUserGroup($userGroup);
- $set = $repository->getBudgets();
-
- Log::debug(sprintf('Resetting %d budget(s).', $set->count()));
-
- /** @var Budget $budget */
- foreach ($set as $budget) {
- foreach ($budget->autoBudgets as $autoBudget) {
- if (null === $autoBudget->native_amount) {
- continue;
- }
- Log::debug(sprintf('Resetting native_amount for budget #%d and auto budget #%d.', $budget->id, $autoBudget->id));
- $autoBudget->native_amount = null;
- $autoBudget->saveQuietly();
- }
- foreach ($budget->budgetlimits as $limit) {
- if (null !== $limit->native_amount) {
- Log::debug(sprintf('Resetting native_amount for budget #%d and budget limit #%d.', $budget->id, $limit->id));
- $limit->native_amount = null;
- $limit->saveQuietly();
- }
- }
- }
- }
-
- private function resetTransactions(UserGroup $userGroup): void
- {
- // custom query because of the potential size of this update.
- $success = DB::table('transactions')
- ->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
- ->where('transaction_journals.user_group_id', $userGroup->id)
- ->where(static function (Builder $q): void {
- $q->whereNotNull('native_amount')->orWhereNotNull('native_foreign_amount');
- })
- ->update(['native_amount' => null, 'native_foreign_amount' => null])
- ;
- Log::debug(sprintf('Reset %d transactions.', $success));
- }
}
diff --git a/app/Handlers/Events/StoredGroupEventHandler.php b/app/Handlers/Events/StoredGroupEventHandler.php
deleted file mode 100644
index 776d92d8f8..0000000000
--- a/app/Handlers/Events/StoredGroupEventHandler.php
+++ /dev/null
@@ -1,187 +0,0 @@
-<?php
-
-/**
- * StoredGroupEventHandler.php
- * Copyright (c) 2019 [email protected]
- *
- * This file is part of Firefly III (https://github.com/firefly-iii).
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
-declare(strict_types=1);
-
-namespace FireflyIII\Handlers\Events;
-
-use FireflyIII\Enums\WebhookTrigger;
-use FireflyIII\Events\Model\TransactionGroup\TriggeredStoredTransactionGroup;
-use FireflyIII\Events\Model\Webhook\WebhookMessagesRequestSending;
-use FireflyIII\Events\StoredTransactionGroup;
-use FireflyIII\Generator\Webhook\MessageGeneratorInterface;
-use FireflyIII\Models\RuleGroup;
-use FireflyIII\Models\Transaction;
-use FireflyIII\Models\TransactionJournal;
-use FireflyIII\Repositories\PeriodStatistic\PeriodStatisticRepositoryInterface;
-use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
-use FireflyIII\Services\Internal\Support\CreditRecalculateService;
-use FireflyIII\TransactionRules\Engine\RuleEngineInterface;
-use Illuminate\Support\Collection;
-use Illuminate\Support\Facades\Log;
-
-/**
- * Class StoredGroupEventHandler
- *
- * TODO migrate to observer?
- */
-class StoredGroupEventHandler
-{
- public function runAllHandlers(StoredTransactionGroup $event): void
- {
- // $this->processRules($event, null);
- // $this->recalculateCredit($event);
- // $this->triggerWebhooks($event);
- $this->removePeriodStatistics($event);
- }
-
- public function triggerRulesManually(TriggeredStoredTransactionGroup $event): void
- {
- // $newEvent = new StoredTransactionGroup($event->transactionGroup, true, false);
- // $this->processRules($newEvent, $event->ruleGroup);
- }
-
- /**
- * This method grabs all the users rules and processes them.
- */
- private function processRules(StoredTransactionGroup $storedGroupEvent, ?RuleGroup $ruleGroup): void
- {
- if (false === $storedGroupEvent->applyRules) {
- Log::info(sprintf('Will not run rules on group #%d', $storedGroupEvent->transactionGroup->id));
-
- return;
- }
- Log::debug('Now in StoredGroupEventHandler::processRules()');
-
- $journals = $storedGroupEvent->transactionGroup->transactionJournals;
- $array = [];
-
- /** @var TransactionJournal $journal */
- foreach ($journals as $journal) {
- $array[] = $journal->id;
- }
- $journalIds = implode(',', $array);
- Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds));
-
- // collect rules:
- $ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
- $ruleGroupRepository->setUser($storedGroupEvent->transactionGroup->user);
-
- // add the groups to the rule engine.
- // it should run the rules in the group and cancel the group if necessary.
- if (null === $ruleGroup) {
- Log::debug('Fire processRules with ALL store-journal rule groups.');
- $groups = $ruleGroupRepository->getRuleGroupsWithRules('store-journal');
- }
- if (null !== $ruleGroup) {
- Log::debug(sprintf('Fire processRules with rule group #%d.', $ruleGroup->id));
- $groups = new Collection([$ruleGroup]);
- }
-
- // create and fire rule engine.
- $newRuleEngine = app(RuleEngineInterface::class);
- $newRuleEngine->setUser($storedGroupEvent->transactionGroup->user);
- $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]);
- $newRuleEngine->setRuleGroups($groups);
- $newRuleEngine->fire();
- }
-
- private function recalculateCredit(StoredTransactionGroup $event): void
- {
- $group = $event->transactionGroup;
-
- /** @var CreditRecalculateService $object */
- $object = app(CreditRecalculateService::class);
- $object->setGroup($group);
- $object->recalculate();
- }
-
- private function removePeriodStatistics(StoredTransactionGroup $event): void
- {
- /** @var PeriodStatisticRepositoryInterface $repository */
- $repository = app(PeriodStatisticRepositoryInterface::class);
-
- /** @var TransactionJournal $journal */
- foreach ($event->transactionGroup->transactionJournals as $journal) {
- /** @var null|Transaction $source */
- $source = $journal->transactions()->where('amount', '<', '0')->first();
-
- /** @var null|Transaction $dest */
- $dest = $journal->transactions()->where('amount', '>', '0')->first();
-
- if (null !== $source) {
- $repository->deleteStatisticsForModel($source->account, $journal->date);
- }
- if (null !== $dest) {
- $repository->deleteStatisticsForModel($dest->account, $journal->date);
- }
- $categories = $journal->categories;
- $tags = $journal->tags;
- $budgets = $journal->budgets;
- foreach ($categories as $category) {
- $repository->deleteStatisticsForModel($category, $journal->date);
- }
- foreach ($tags as $tag) {
- $repository->deleteStatisticsForModel($tag, $journal->date);
- }
- foreach ($budgets as $budget) {
- $repository->deleteStatisticsForModel($budget, $journal->date);
- }
- if (0 === $categories->count()) {
- $repository->deleteStatisticsForPrefix($journal->userGroup, 'no_category', $journal->date);
- }
- if (0 === $budgets->count()) {
- $repository->deleteStatisticsForPrefix($journal->userGroup, 'no_budget', $journal->date);
- }
- }
- }
-
- /**
- * This method processes all webhooks that respond to the "stored transaction group" trigger (100)
- */
- private function triggerWebhooks(StoredTransactionGroup $storedGroupEvent): void
- {
- Log::debug(__METHOD__);
- $group = $storedGroupEvent->transactionGroup;
- if (false === $storedGroupEvent->fireWebhooks) {
- Log::info(sprintf('Will not fire webhooks for transaction group #%d', $group->id));
-
- return;
- }
-
- $user = $group->user;
-
- /** @var MessageGeneratorInterface $engine */
- $engine = app(MessageGeneratorInterface::class);
- $engine->setUser($user);
-
- // tell the generator which trigger it should look for
- $engine->setTrigger(WebhookTrigger::STORE_TRANSACTION);
- // tell the generator which objects to process
- $engine->setObjects(new Collection()->push($group));
- // tell the generator to generate the messages
- $engine->generateMessages();
-
- // trigger event to send them:
- Log::debug(sprintf('send event WebhookMessagesRequestSending from %s', __METHOD__));
- event(new WebhookMessagesRequestSending());
- }
-}
diff --git a/app/Handlers/Events/UpdatedAccountEventHandler.php b/app/Handlers/Events/UpdatedAccountEventHandler.php
deleted file mode 100644
index 59c137e817..0000000000
--- a/app/Handlers/Events/UpdatedAccountEventHandler.php
+++ /dev/null
@@ -1,44 +0,0 @@
-<?php
-
-/*
- * UpdatedAccountEventHandler.php
- * Copyright (c) 2021 [email protected]
- *
- * This file is part of Firefly III (https://github.com/firefly-iii).
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
-
-declare(strict_types=1);
-
-namespace FireflyIII\Handlers\Events;
-
-use FireflyIII\Events\UpdatedAccount;
-use FireflyIII\Services\Internal\Support\CreditRecalculateService;
-
-/**
- * Class UpdatedAccountEventHandler
- */
-class UpdatedAccountEventHandler
-{
- public function recalculateCredit(UpdatedAccount $event): void
- {
- $account = $event->account;
-
- /** @var CreditRecalculateService $object */
- $object = app(CreditRecalculateService::class);
- $object->setAccount($account);
- $object->recalculate();
- }
-}
diff --git a/app/Listeners/System/RecalculatesPrimaryCurrencyAmounts.php b/app/Listeners/System/RecalculatesPrimaryCurrencyAmounts.php
new file mode 100644
index 0000000000..6dfa1752af
--- /dev/null
+++ b/app/Listeners/System/RecalculatesPrimaryCurrencyAmounts.php
@@ -0,0 +1,157 @@
+<?php
+/*
+ * RecalculatesPrimaryCurrencyAmounts.php
+ * Copyright (c) 2026 [email protected]
+ *
+ * This file is part of Firefly III (https://github.com/firefly-iii).
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+namespace FireflyIII\Listeners\System;
+
+use FireflyIII\Events\Preferences\UserGroupChangedPrimaryCurrency;
+use FireflyIII\Models\Budget;
+use FireflyIII\Models\PiggyBank;
+use FireflyIII\Models\UserGroup;
+use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
+use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
+use FireflyIII\Services\Internal\Recalculate\PrimaryAmountRecalculationService;
+use FireflyIII\Support\Facades\Amount;
+use Illuminate\Database\Query\Builder;
+use Illuminate\Support\Facades\Artisan;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+
+class RecalculatesPrimaryCurrencyAmounts
+{
+ public function handle(UserGroupChangedPrimaryCurrency $event): void
+ {
+ // Reset the primary currency amounts for all objects that have it.
+ Log::debug('Resetting primary currency amounts for all objects.');
+
+ $tables = [
+ // !!! this array is also in the migration
+ 'accounts' => ['native_virtual_balance'],
+ 'available_budgets' => ['native_amount'],
+ 'bills' => ['native_amount_min', 'native_amount_max'],
+ ];
+ foreach ($tables as $table => $columns) {
+ Log::debug(sprintf('Now processing table "%s"', $table));
+ foreach ($columns as $column) {
+ Log::debug(sprintf('Resetting column "%s" in table "%s".', $column, $table));
+ DB::table($table)->where('user_group_id', $event->userGroup->id)->update([$column => null]);
+ }
+ }
+
+ $this->resetPiggyBanks($event->userGroup);
+ $this->resetBudgets($event->userGroup);
+ $this->resetTransactions($event->userGroup);
+ Log::debug('Have now reset all primary amounts to NULL.');
+ // fire laravel command to recalculate them all.
+ if (Amount::convertToPrimary()) {
+ Log::debug('Will now convert amounts to primary currency.');
+
+ $calculator = new PrimaryAmountRecalculationService();
+ $calculator->recalculate();
+
+ return;
+ }
+ Log::debug('Will NOT convert to primary currency.');
+ }
+
+ private function resetBudget(Budget $budget): void
+ {
+ foreach ($budget->autoBudgets as $autoBudget) {
+ if ('' === (string)$autoBudget->native_amount) {
+ continue;
+ }
+ Log::debug(sprintf('Resetting native_amount for budget #%d and auto budget #%d.', $budget->id, $autoBudget->id));
+ $autoBudget->native_amount = null;
+ $autoBudget->saveQuietly();
+ }
+ foreach ($budget->budgetlimits as $limit) {
+ if ('' !== (string)$limit->native_amount) {
+ Log::debug(sprintf('Resetting native_amount for budget #%d and budget limit #%d.', $budget->id, $limit->id));
+ $limit->native_amount = null;
+ $limit->saveQuietly();
+ }
+ }
+ }
+
+ private function resetPiggyBank(PiggyBank $piggyBank): void
+ {
+ if ('' !== (string)$piggyBank->native_target_amount) {
+ Log::debug(sprintf('Resetting native_target_amount for piggy bank #%d.', $piggyBank->id));
+ $piggyBank->native_target_amount = null;
+ $piggyBank->saveQuietly();
+ }
+ foreach ($piggyBank->accounts as $account) {
+ if ('' !== (string)$account->pivot->native_current_amount) {
+ Log::debug(sprintf('Resetting native_current_amount for piggy bank #%d and account #%d.', $piggyBank->id, $account->id));
+ $account->pivot->native_current_amount = null;
+ $account->pivot->save();
+ }
+ }
+ foreach ($piggyBank->piggyBankEvents as $event) {
+ if ('' !== (string)$event->native_amount) {
+ Log::debug(sprintf('Resetting native_amount for piggy bank #%d and event #%d.', $piggyBank->id, $event->id));
+ $event->native_amount = null;
+ $event->saveQuietly();
+ }
+ }
+ }
+
+ private function resetTransactions(UserGroup $userGroup): void
+ {
+ // custom query because of the potential size of this update.
+ $success = DB::table('transactions')->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->where('transaction_journals.user_group_id', $userGroup->id)
+ ->where(static function (Builder $q): void {
+ $q->whereNotNull('native_amount')
+ ->orWhereNotNull('native_foreign_amount')
+ ->orWhere('native_amount', '!=', '')
+ ->orWhere('native_foreign_amount', '!=', '');
+ })
+ ->update(['native_amount' => null, 'native_foreign_amount' => null]);
+ Log::debug(sprintf('Reset %d transactions.', $success));
+ }
+
+ private function resetPiggyBanks(UserGroup $userGroup): void
+ {
+ $repository = app(PiggyBankRepositoryInterface::class);
+ $repository->setUserGroup($userGroup);
+ $piggyBanks = $repository->getPiggyBanks();
+ Log::debug(sprintf('Reset primary currency of %d piggy bank(s).', $piggyBanks->count()));
+
+ /** @var PiggyBank $piggyBank */
+ foreach ($piggyBanks as $piggyBank) {
+ $this->resetPiggyBank($piggyBank);
+ }
+ }
+
+ private function resetBudgets(UserGroup $userGroup): void
+ {
+ $repository = app(BudgetRepositoryInterface::class);
+ $repository->setUserGroup($userGroup);
+ $set = $repository->getBudgets();
+
+ Log::debug(sprintf('Reset primary currency of %d budget(s).', $set->count()));
+
+ /** @var Budget $budget */
+ foreach ($set as $budget) {
+ $this->resetBudget($budget);
+ }
+ }
+
+}
diff --git a/app/Services/Internal/Recalculate/PrimaryAmountRecalculationService.php b/app/Services/Internal/Recalculate/PrimaryAmountRecalculationService.php
new file mode 100644
index 0000000000..7ae9249cbd
--- /dev/null
+++ b/app/Services/Internal/Recalculate/PrimaryAmountRecalculationService.php
@@ -0,0 +1,238 @@
+<?php
+/*
+ * RecalculatesPrimaryAmounts.php
+ * Copyright (c) 2026 [email protected]
+ *
+ * This file is part of Firefly III (https://github.com/firefly-iii).
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+namespace FireflyIII\Services\Internal\Recalculate;
+
+use FireflyIII\Handlers\Observer\TransactionObserver;
+use FireflyIII\Models\Account;
+use FireflyIII\Models\AutoBudget;
+use FireflyIII\Models\AvailableBudget;
+use FireflyIII\Models\Bill;
+use FireflyIII\Models\Budget;
+use FireflyIII\Models\BudgetLimit;
+use FireflyIII\Models\PiggyBank;
+use FireflyIII\Models\PiggyBankEvent;
+use FireflyIII\Models\Transaction;
+use FireflyIII\Models\TransactionCurrency;
+use FireflyIII\Models\UserGroup;
+use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
+use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface;
+use FireflyIII\Support\Facades\Amount;
+use FireflyIII\Support\Facades\FireflyConfig;
+use FireflyIII\Support\Facades\Preferences;
+use FireflyIII\Support\Http\Api\ExchangeRateConverter;
+use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
+use Illuminate\Database\Query\Builder as DatabaseBuilder;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+
+class PrimaryAmountRecalculationService
+{
+ public function recalculate(): void
+ {
+ if (false === FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data) {
+ return;
+ }
+
+ /** @var UserGroupRepositoryInterface $repository */
+ $repository = app(UserGroupRepositoryInterface::class);
+ Preferences::mark();
+
+ /** @var UserGroup $userGroup */
+ foreach ($repository->getAll() as $userGroup) {
+ $this->recalculateForGroup($userGroup);
+ }
+ }
+
+ private function recalculateForGroup(UserGroup $userGroup): void
+ {
+ Log::debug(sprintf('Now recalculating primary amounts for user group #%d', $userGroup->id));
+ $this->recalculateAccounts($userGroup);
+
+ // do a check with the group's currency so we can skip some stuff.
+ $currency = Amount::getPrimaryCurrencyByUserGroup($userGroup);
+
+ $this->recalculatePiggyBanks($userGroup, $currency);
+ $this->recalculateBudgets($userGroup, $currency);
+ $this->recalculateAvailableBudgets($userGroup, $currency);
+ $this->recalculateBills($userGroup, $currency);
+ $this->calculateTransactions($userGroup, $currency);
+ }
+
+
+ private function recalculateAccounts(UserGroup $userGroup): void
+ {
+ $set = $userGroup
+ ->accounts()
+ ->where(static function (EloquentBuilder $q): void {
+ $q->whereNotNull('virtual_balance');
+
+ // this needs a different piece of code for postgres.
+ if ('pgsql' === config('database.default')) {
+ $q->orWhere(DB::raw('CAST(virtual_balance AS TEXT)'), '!=', '');
+ }
+ if ('pgsql' !== config('database.default')) {
+ $q->orWhere('virtual_balance', '!=', '');
+ }
+ })
+ ->get();
+
+ /** @var Account $account */
+ foreach ($set as $account) {
+ $account->touch();
+ }
+ Log::debug(sprintf('Recalculated %d accounts for user group #%d.', $set->count(), $userGroup->id));
+ }
+
+
+ private function recalculatePiggyBanks(UserGroup $userGroup, TransactionCurrency $currency): void
+ {
+ $converter = new ExchangeRateConverter();
+ $converter->setUserGroup($userGroup);
+ $converter->setIgnoreSettings(true);
+ $repository = app(PiggyBankRepositoryInterface::class);
+ $repository->setUserGroup($userGroup);
+ $set = $repository->getPiggyBanks();
+ $set = $set->filter(static fn(PiggyBank $piggyBank): bool => $currency->id !== $piggyBank->transaction_currency_id);
+ foreach ($set as $piggyBank) {
+ $piggyBank->encrypted = false;
+ $piggyBank->save();
+
+ foreach ($piggyBank->accounts as $account) {
+ $account->pivot->native_current_amount = null;
+ if (0 !== bccomp((string)$account->pivot->current_amount, '0')) {
+ $account->pivot->native_current_amount = $converter->convert(
+ $piggyBank->transactionCurrency,
+ $currency,
+ today(),
+ (string)$account->pivot->current_amount
+ );
+ }
+ $account->pivot->save();
+ }
+ $this->recalculatePiggyBankEvents($piggyBank);
+ }
+ Log::debug(sprintf('Recalculated %d piggy banks for user group #%d.', $set->count(), $userGroup->id));
+ }
+
+
+ private function recalculatePiggyBankEvents(PiggyBank $piggyBank): void
+ {
+ $set = $piggyBank->piggyBankEvents()->get();
+ $set->each(static function (PiggyBankEvent $event): void { // @phpstan-ignore-line
+ $event->touch();
+ });
+ Log::debug(sprintf('Recalculated %d piggy bank events.', $set->count()));
+ }
+
+ private function recalculateBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
+ {
+ $set = $userGroup->budgets()->get();
+
+ /** @var Budget $budget */
+ foreach ($set as $budget) {
+ $this->recalculateBudgetLimits($budget, $currency);
+ $this->recalculateAutoBudgets($budget, $currency);
+ }
+ Log::debug(sprintf('Recalculated %d budgets.', $set->count()));
+ }
+
+
+ private function recalculateBudgetLimits(Budget $budget, TransactionCurrency $currency): void
+ {
+ $set = $budget->budgetlimits()->where('transaction_currency_id', '!=', $currency->id)->get();
+
+ /** @var BudgetLimit $limit */
+ foreach ($set as $limit) {
+ Log::debug(sprintf('Will now touch BL #%d', $limit->id));
+ $limit->touch();
+ Log::debug(sprintf('Done with touch BL #%d', $limit->id));
+ }
+ Log::debug(sprintf('Recalculated %d budget limits for budget #%d.', $set->count(), $budget->id));
+ }
+
+ private function recalculateAutoBudgets(Budget $budget, TransactionCurrency $currency): void
+ {
+ $set = $budget->autoBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
+
+ /** @var AutoBudget $autoBudget */
+ foreach ($set as $autoBudget) {
+ $autoBudget->touch();
+ }
+ Log::debug(sprintf('Recalculated %d auto budgets for budget #%d.', $set->count(), $budget->id));
+ }
+
+ private function recalculateAvailableBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
+ {
+ Log::debug('Start with available budgets.');
+ $set = $userGroup->availableBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
+
+ /** @var AvailableBudget $budget */
+ foreach ($set as $budget) {
+ $budget->touch();
+ }
+ Log::debug(sprintf('Recalculated %d available budgets.', $set->count()));
+ }
+
+
+ private function recalculateBills(UserGroup $userGroup, TransactionCurrency $currency): void
+ {
+ $set = $userGroup->bills()->where('transaction_currency_id', '!=', $currency->id)->get();
+
+ /** @var Bill $bill */
+ foreach ($set as $bill) {
+ $bill->touch();
+ }
+ Log::debug(sprintf('Recalculated %d bills.', $set->count()));
+ }
+
+ private function calculateTransactions(UserGroup $userGroup, TransactionCurrency $currency): void
+ {
+ // custom query because of the potential size of this update.
+ $set = DB::table('transactions')
+ ->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
+ ->where('transaction_journals.user_group_id', $userGroup->id)
+ ->where(static function (DatabaseBuilder $q1) use ($currency): void {
+ $q1->where(static function (DatabaseBuilder $q2) use ($currency): void {
+ $q2->whereNot('transactions.transaction_currency_id', $currency->id)->whereNull('transactions.foreign_currency_id');
+ })->orWhere(static function (DatabaseBuilder $q3) use ($currency): void {
+ $q3->whereNot('transactions.transaction_currency_id', $currency->id)->whereNot('transactions.foreign_currency_id', $currency->id);
+ });
+ })
+ // ->where(static function (DatabaseBuilder $q) use ($currency): void {
+ // $q->whereNot('transactions.transaction_currency_id', $currency->id)
+ // ->whereNot('transactions.foreign_currency_id', $currency->id)
+ // ;
+ // })
+ ->get(['transactions.id']);
+ TransactionObserver::$recalculate = false;
+ foreach ($set as $item) {
+ // here we are.
+ /** @var null|Transaction $transaction */
+ $transaction = Transaction::find($item->id);
+ $transaction?->touch();
+ }
+ TransactionObserver::$recalculate = true;
+ Log::debug(sprintf('Recalculated %d transactions.', $set->count()));
+ }
+
+
+}