Better fit for run recalculations.

This commit is contained in:
James Cole
2025-06-01 14:00:35 +02:00
parent 5bd87036b0
commit a9cd8b6512
12 changed files with 106 additions and 100 deletions

View File

@@ -74,18 +74,16 @@ class UpdateController extends Controller
{ {
app('log')->debug('Now in update routine for transaction group'); app('log')->debug('Now in update routine for transaction group');
$data = $request->getAll(); $data = $request->getAll();
$oldAmount = $this->groupRepository->getTotalAmount($transactionGroup); $oldHash = $this->groupRepository->getCompareHash($transactionGroup);
$transactionGroup = $this->groupRepository->update($transactionGroup, $data); $transactionGroup = $this->groupRepository->update($transactionGroup, $data);
$newAmount = $this->groupRepository->getTotalAmount($transactionGroup); $newHash = $this->groupRepository->getCompareHash($transactionGroup);
$manager = $this->getManager(); $manager = $this->getManager();
Log::debug(sprintf('Old amount: %s, new amount: %s', $oldAmount, $newAmount));
app('preferences')->mark(); app('preferences')->mark();
$applyRules = $data['apply_rules'] ?? true; $applyRules = $data['apply_rules'] ?? true;
$fireWebhooks = $data['fire_webhooks'] ?? true; $fireWebhooks = $data['fire_webhooks'] ?? true;
$amountChanged = 0 !== bccomp($oldAmount, $newAmount); $runRecalculations = $oldHash !== $newHash;
event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $amountChanged)); event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $runRecalculations));
/** @var User $admin */ /** @var User $admin */
$admin = auth()->user(); $admin = auth()->user();

View File

@@ -69,9 +69,9 @@ class UpdateController extends Controller
$transactionGroup = $this->groupRepository->update($transactionGroup, $data); $transactionGroup = $this->groupRepository->update($transactionGroup, $data);
$applyRules = $data['apply_rules'] ?? true; $applyRules = $data['apply_rules'] ?? true;
$fireWebhooks = $data['fire_webhooks'] ?? true; $fireWebhooks = $data['fire_webhooks'] ?? true;
$amountChanged = true; $runRecalculations = true;
event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $amountChanged)); event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $runRecalculations));
app('preferences')->mark(); app('preferences')->mark();
/** @var User $admin */ /** @var User $admin */

View File

@@ -58,6 +58,7 @@ class CorrectsGroupAccounts extends Command
$handler = new UpdatedGroupEventHandler(); $handler = new UpdatedGroupEventHandler();
foreach ($groups as $groupId) { foreach ($groups as $groupId) {
$group = TransactionGroup::find($groupId); $group = TransactionGroup::find($groupId);
// TODO in theory the "unifyAccounts" method could lead to the need for run recalculations.
$event = new UpdatedTransactionGroup($group, true, true, false); $event = new UpdatedTransactionGroup($group, true, true, false);
$handler->unifyAccounts($event); $handler->unifyAccounts($event);
} }

View File

@@ -37,5 +37,5 @@ class UpdatedTransactionGroup extends Event
/** /**
* Create a new event instance. * Create a new event instance.
*/ */
public function __construct(public TransactionGroup $transactionGroup, public bool $applyRules, public bool $fireWebhooks, public bool $amountChanged) {} public function __construct(public TransactionGroup $transactionGroup, public bool $applyRules, public bool $fireWebhooks, public bool $runRecalculations) {}
} }

View File

@@ -292,7 +292,7 @@ class ConvertController extends Controller
$group->refresh(); $group->refresh();
session()->flash('success', (string) trans('firefly.converted_to_'.$destinationType->type)); session()->flash('success', (string) trans('firefly.converted_to_'.$destinationType->type));
event(new UpdatedTransactionGroup($group, true, true, false)); event(new UpdatedTransactionGroup($group, true, true, true));
return redirect(route('transactions.show', [$group->id])); return redirect(route('transactions.show', [$group->id]));
} }

View File

@@ -217,8 +217,8 @@ class MassController extends Controller
$service->setData($data); $service->setData($data);
$service->update(); $service->update();
// trigger rules // trigger rules
$amountChanged = $service->isAmountChanged(); $runRecalculations = $service->isCompareHashChanged();
event(new UpdatedTransactionGroup($journal->transactionGroup, true, true, $amountChanged)); event(new UpdatedTransactionGroup($journal->transactionGroup, true, true, $runRecalculations));
} }
private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon

View File

@@ -147,8 +147,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
$set = Attachment::whereIn('attachable_id', $journals) $set = Attachment::whereIn('attachable_id', $journals)
->where('attachable_type', TransactionJournal::class) ->where('attachable_type', TransactionJournal::class)
->where('uploaded', true) ->where('uploaded', true)
->whereNull('deleted_at')->get() ->whereNull('deleted_at')->get();
;
$result = []; $result = [];
@@ -175,8 +174,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
/** @var null|Note $note */ /** @var null|Note $note */
$note = Note::where('noteable_id', $journalId) $note = Note::where('noteable_id', $journalId)
->where('noteable_type', TransactionJournal::class) ->where('noteable_type', TransactionJournal::class)
->first() ->first();
;
if (null === $note) { if (null === $note) {
return null; return null;
} }
@@ -199,8 +197,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
) )
->with(['source', 'destination', 'source.transactions']) ->with(['source', 'destination', 'source.transactions'])
->leftJoin('link_types', 'link_types.id', '=', 'journal_links.link_type_id') ->leftJoin('link_types', 'link_types.id', '=', 'journal_links.link_type_id')
->get(['journal_links.*', 'link_types.inward', 'link_types.outward', 'link_types.editable']) ->get(['journal_links.*', 'link_types.inward', 'link_types.outward', 'link_types.editable']);
;
/** @var TransactionJournalLink $entry */ /** @var TransactionJournalLink $entry */
foreach ($set as $entry) { foreach ($set as $entry) {
@@ -300,8 +297,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
->where('transaction_journal_id', $journalId) ->where('transaction_journal_id', $journalId)
->whereIn('name', $fields) ->whereIn('name', $fields)
->whereNull('deleted_at') ->whereNull('deleted_at')
->get(['name', 'data']) ->get(['name', 'data']);
;
$return = []; $return = [];
foreach ($query as $row) { foreach ($query as $row) {
@@ -320,8 +316,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
->where('transaction_journal_id', $journalId) ->where('transaction_journal_id', $journalId)
->whereIn('name', $fields) ->whereIn('name', $fields)
->whereNull('deleted_at') ->whereNull('deleted_at')
->get(['name', 'data']) ->get(['name', 'data']);
;
$return = []; $return = [];
foreach ($query as $row) { foreach ($query as $row) {
@@ -343,8 +338,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
$currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); $currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup);
$data = PiggyBankEvent::whereIn('transaction_journal_id', $journals) $data = PiggyBankEvent::whereIn('transaction_journal_id', $journals)
->with('piggyBank', 'piggyBank.account') ->with('piggyBank', 'piggyBank.account')
->get(['piggy_bank_events.*']) ->get(['piggy_bank_events.*']);
;
/** @var PiggyBankEvent $row */ /** @var PiggyBankEvent $row */
foreach ($data as $row) { foreach ($data as $row) {
@@ -354,8 +348,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
// get currency preference. // get currency preference.
$currencyPreference = AccountMeta::where('account_id', $row->piggyBank->account_id) $currencyPreference = AccountMeta::where('account_id', $row->piggyBank->account_id)
->where('name', 'currency_id') ->where('name', 'currency_id')
->first() ->first();
;
if (null !== $currencyPreference) { if (null !== $currencyPreference) {
$currency = TransactionCurrency::where('id', $currencyPreference->data)->first(); $currency = TransactionCurrency::where('id', $currencyPreference->data)->first();
} }
@@ -389,8 +382,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id') ->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id')
->where('tag_transaction_journal.transaction_journal_id', $journalId) ->where('tag_transaction_journal.transaction_journal_id', $journalId)
->orderBy('tags.tag', 'ASC') ->orderBy('tags.tag', 'ASC')
->get(['tags.tag']) ->get(['tags.tag']);
;
return $result->pluck('tag')->toArray(); return $result->pluck('tag')->toArray();
} }
@@ -433,9 +425,10 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
return $service->update($transactionGroup, $data); return $service->update($transactionGroup, $data);
} }
public function getTotalAmount(TransactionGroup $group): string public function getCompareHash(TransactionGroup $group): string
{ {
$sum = '0'; $sum = '0';
$names = '';
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($group->transactionJournals as $journal) { foreach ($group->transactionJournals as $journal) {
@@ -443,10 +436,11 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
foreach ($journal->transactions as $transaction) { foreach ($journal->transactions as $transaction) {
if (-1 === bccomp('0', (string)$transaction->amount)) { if (-1 === bccomp('0', (string)$transaction->amount)) {
$sum = bcadd($sum, $transaction->amount); $sum = bcadd($sum, $transaction->amount);
$names = sprintf('%s%s', $names, $transaction->account->name);
} }
} }
} }
return $sum; return hash('sha256', sprintf('%s-%s', $names, $sum));
} }
} }

View File

@@ -49,7 +49,13 @@ interface TransactionGroupRepositoryInterface
{ {
public function countAttachments(int $journalId): int; public function countAttachments(int $journalId): int;
public function getTotalAmount(TransactionGroup $group): string; /**
* Small method that returns a hash that can be used to compare two transaction groups.
*
* @param TransactionGroup $group
* @return string
*/
public function getCompareHash(TransactionGroup $group): string;
public function destroy(TransactionGroup $group): void; public function destroy(TransactionGroup $group): void;

View File

@@ -43,6 +43,7 @@ use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface;
use FireflyIII\Services\Internal\Support\JournalServiceTrait; use FireflyIII\Services\Internal\Support\JournalServiceTrait;
use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\FireflyConfig;
use FireflyIII\Support\NullArrayObject; use FireflyIII\Support\NullArrayObject;
@@ -60,6 +61,7 @@ class JournalUpdateService
private BillRepositoryInterface $billRepository; private BillRepositoryInterface $billRepository;
private CurrencyRepositoryInterface $currencyRepository; private CurrencyRepositoryInterface $currencyRepository;
private TransactionGroupRepositoryInterface $transactionGroupRepository;
private array $data; private array $data;
private ?Account $destinationAccount; private ?Account $destinationAccount;
private ?Transaction $destinationTransaction; private ?Transaction $destinationTransaction;
@@ -69,7 +71,7 @@ class JournalUpdateService
private ?Transaction $sourceTransaction; private ?Transaction $sourceTransaction;
private ?TransactionGroup $transactionGroup; private ?TransactionGroup $transactionGroup;
private ?TransactionJournal $transactionJournal; private ?TransactionJournal $transactionJournal;
private bool $amountChanged = false; private string $startCompareHash = '';
/** /**
* JournalUpdateService constructor. * JournalUpdateService constructor.
@@ -88,6 +90,7 @@ class JournalUpdateService
$this->tagFactory = app(TagFactory::class); $this->tagFactory = app(TagFactory::class);
$this->accountRepository = app(AccountRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class);
$this->currencyRepository = app(CurrencyRepositoryInterface::class); $this->currencyRepository = app(CurrencyRepositoryInterface::class);
$this->transactionGroupRepository = app(TransactionGroupRepositoryInterface::class);
$this->metaString = [ $this->metaString = [
'sepa_cc', 'sepa_cc',
'sepa_ct_op', 'sepa_ct_op',
@@ -120,10 +123,12 @@ class JournalUpdateService
$this->budgetRepository->setUser($transactionGroup->user); $this->budgetRepository->setUser($transactionGroup->user);
$this->tagFactory->setUser($transactionGroup->user); $this->tagFactory->setUser($transactionGroup->user);
$this->accountRepository->setUser($transactionGroup->user); $this->accountRepository->setUser($transactionGroup->user);
$this->transactionGroupRepository->setUser($transactionGroup->user);
$this->destinationAccount = null; $this->destinationAccount = null;
$this->destinationTransaction = null; $this->destinationTransaction = null;
$this->sourceAccount = null; $this->sourceAccount = null;
$this->sourceTransaction = null; $this->sourceTransaction = null;
$this->startCompareHash = $this->transactionGroupRepository->getCompareHash($transactionGroup);
} }
public function setTransactionJournal(TransactionJournal $transactionJournal): void public function setTransactionJournal(TransactionJournal $transactionJournal): void
@@ -675,7 +680,6 @@ class JournalUpdateService
return; return;
} }
$origSourceTransaction = $this->getSourceTransaction(); $origSourceTransaction = $this->getSourceTransaction();
$this->amountChanged = 0 !== bccomp($origSourceTransaction->amount, app('steam')->negative($amount));
$origSourceTransaction->amount = app('steam')->negative($amount); $origSourceTransaction->amount = app('steam')->negative($amount);
$origSourceTransaction->balance_dirty = true; $origSourceTransaction->balance_dirty = true;
$origSourceTransaction->save(); $origSourceTransaction->save();
@@ -818,8 +822,12 @@ class JournalUpdateService
return false; return false;
} }
public function isAmountChanged(): bool public function isCompareHashChanged(): bool {
{ Log::debug(sprintf('Now in %s', __METHOD__));
return $this->amountChanged; $compareHash = $this->transactionGroupRepository->getCompareHash($this->transactionGroup);
Log::debug(sprintf('Compare hash is "%s".', $compareHash));
Log::debug(sprintf('Start compare hash is "%s".', $this->startCompareHash));
return $compareHash !== $this->startCompareHash;
} }
} }

View File

@@ -490,7 +490,6 @@ let transactions = function () {
// addedSplit, is called from the HTML // addedSplit, is called from the HTML
// for source account // for source account
const renderAccount = function (item, b, c) { const renderAccount = function (item, b, c) {
console.log('render account');
return item.name_with_balance + '<br><small class="text-muted">' + i18next.t('firefly.account_type_' + item.type) + '</small>'; return item.name_with_balance + '<br><small class="text-muted">' + i18next.t('firefly.account_type_' + item.type) + '</small>';
}; };
console.log('here we are in'); console.log('here we are in');
@@ -499,7 +498,7 @@ let transactions = function () {
serverUrl: urls.account, serverUrl: urls.account,
onRenderItem: renderAccount, onRenderItem: renderAccount,
valueField: 'id', valueField: 'id',
labelField: 'title', labelField: 'name_with_balance',
onChange: changeSourceAccount, onChange: changeSourceAccount,
onSelectItem: selectSourceAccount, onSelectItem: selectSourceAccount,
hiddenValue: this.entries[count].source_account.alpine_name hiddenValue: this.entries[count].source_account.alpine_name
@@ -509,7 +508,7 @@ let transactions = function () {
serverUrl: urls.account, serverUrl: urls.account,
account_types: this.filters.destination, account_types: this.filters.destination,
valueField: 'id', valueField: 'id',
labelField: 'title', labelField: 'name_with_balance',
onRenderItem: renderAccount, onRenderItem: renderAccount,
onChange: changeDestinationAccount, onChange: changeDestinationAccount,
onSelectItem: selectDestinationAccount onSelectItem: selectDestinationAccount

View File

@@ -45,7 +45,7 @@ export function addAutocomplete(options) {
liveServer: true, liveServer: true,
}; };
if (typeof options.account_types !== 'undefined' && options.account_types.length > 0) { if (typeof options.account_types !== 'undefined' && options.account_types.length > 0) {
params.serverParams['filter[account_types]'] = options.account_types; params.serverParams['types'] = options.account_types;
} }
if (typeof options.onRenderItem !== 'undefined' && null !== options.onRenderItem) { if (typeof options.onRenderItem !== 'undefined' && null !== options.onRenderItem) {
console.log('overrule onRenderItem.'); console.log('overrule onRenderItem.');

View File

@@ -55,7 +55,7 @@ export function changeDestinationAccount(item, ac) {
export function selectDestinationAccount(item, ac) { export function selectDestinationAccount(item, ac) {
const index = parseInt(ac._searchInput.attributes['data-index'].value); const index = parseInt(ac._searchInput.attributes['data-index'].value);
document.querySelector('#form')._x_dataStack[0].$data.entries[index].destination_account = { document.querySelector('#form')._x_dataStack[0].$data.entries[index].destination_account = {
id: item.id, name: item.title, alpine_name: item.title, type: item.meta.type, currency_code: item.meta.currency_code, id: item.id, name: item.name, alpine_name: item.name, type: item.type, currency_code: item.currency_code,
}; };
document.querySelector('#form')._x_dataStack[0].changedDestinationAccount(); document.querySelector('#form')._x_dataStack[0].changedDestinationAccount();
} }
@@ -78,7 +78,7 @@ export function changeSourceAccount(item, ac) {
export function selectSourceAccount(item, ac) { export function selectSourceAccount(item, ac) {
const index = parseInt(ac._searchInput.attributes['data-index'].value); const index = parseInt(ac._searchInput.attributes['data-index'].value);
document.querySelector('#form')._x_dataStack[0].$data.entries[index].source_account = { document.querySelector('#form')._x_dataStack[0].$data.entries[index].source_account = {
id: item.id, name: item.title, alpine_name: item.title, type: item.meta.type, currency_code: item.meta.currency_code, id: item.id, name: item.name, alpine_name: item.name, type: item.type, currency_code: item.currency_code,
}; };
document.querySelector('#form')._x_dataStack[0].changedSourceAccount(); document.querySelector('#form')._x_dataStack[0].changedSourceAccount();
} }