Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Update event handlers
Sander Dorigo9c2b83a9716e
diff --git a/app/Events/Model/TransactionGroup/CreatedSingleTransactionGroup.php b/app/Events/Model/TransactionGroup/CreatedSingleTransactionGroup.phpindex d994bf3fe6..f668553243 100644--- a/app/Events/Model/TransactionGroup/CreatedSingleTransactionGroup.php+++ b/app/Events/Model/TransactionGroup/CreatedSingleTransactionGroup.php@@ -37,8 +37,8 @@ class CreatedSingleTransactionGroup extends Event* Create a new event instance.*/public function __construct(- public TransactionGroup $transactionGroup,- public TransactionGroupEventFlags $flags+ public TransactionGroupEventFlags $flags,+ public TransactionGroupEventObjects $objects) {Log::debug(__METHOD__);}diff --git a/app/Events/Model/TransactionGroup/TransactionGroupEventObjects.php b/app/Events/Model/TransactionGroup/TransactionGroupEventObjects.phpindex c00b011c36..bda0de7bff 100644--- a/app/Events/Model/TransactionGroup/TransactionGroupEventObjects.php+++ b/app/Events/Model/TransactionGroup/TransactionGroupEventObjects.php@@ -2,6 +2,10 @@namespace FireflyIII\Events\Model\TransactionGroup;+use FireflyIII\Models\Tag;+use FireflyIII\Models\Transaction;+use FireflyIII\Models\TransactionGroup;+use FireflyIII\Models\TransactionJournal;use Illuminate\Support\Collection;/**@@ -27,4 +31,22 @@ class TransactionGroupEventObjects$this->tags =new Collection();$this->transactionJournals = new Collection();}++ public static function collectFromTransactionGroup(TransactionGroup $transactionGroup): self+ {+ $object = new self;+ /** @var TransactionJournal $journal */+ foreach($transactionGroup->transactionJournals as $journal) {+ $object->transactionJournals->push($journal);+ $object->budgets = $object->tags->merge($journal->budgets);+ $object->categories = $object->tags->merge($journal->categories);+ $object->tags = $object->tags->merge($journal->tags);++ /** @var Transaction $transaction */+ foreach($journal->transactions as $transaction) {+ $object->accounts->push($transaction->account);+ }+ }+ return $object;+ }}diff --git a/app/Listeners/Model/TransactionGroup/ProcessesNewTransactionGroup.php b/app/Listeners/Model/TransactionGroup/ProcessesNewTransactionGroup.phpindex b663de8be3..ec696fd917 100644--- a/app/Listeners/Model/TransactionGroup/ProcessesNewTransactionGroup.php+++ b/app/Listeners/Model/TransactionGroup/ProcessesNewTransactionGroup.php@@ -27,6 +27,7 @@ namespace FireflyIII\Listeners\Model\TransactionGroup;use Carbon\Carbon;use FireflyIII\Enums\WebhookTrigger;use FireflyIII\Events\Model\TransactionGroup\CreatedSingleTransactionGroup;+use FireflyIII\Events\Model\TransactionGroup\TransactionGroupEventObjects;use FireflyIII\Events\Model\TransactionGroup\UserRequestedBatchProcessing;use FireflyIII\Events\Model\Webhook\WebhookMessagesRequestSending;use FireflyIII\Generator\Webhook\MessageGeneratorInterface;@@ -47,175 +48,43 @@ use Illuminate\Support\Facades\Log;class ProcessesNewTransactionGroup implements ShouldQueue{+ use SupportsGroupProcessingTrait;public function handle(CreatedSingleTransactionGroup|UserRequestedBatchProcessing $event): void{- $groupId = 0;- $collection = new Collection();- if ($event instanceof CreatedSingleTransactionGroup) {- Log::debug(sprintf('In ProcessesNewTransactionGroup::handle(#%d)', $event->transactionGroup->id));- $groupId = $event->transactionGroup->id;- $collection = $event->transactionGroup->transactionJournals;- }- if ($event instanceof UserRequestedBatchProcessing) {- Log::debug('User called UserRequestedBatchProcessing');- }+ Log::debug(sprintf('User called %s', get_class($event)));$setting = FireflyConfig::get('enable_batch_processing', false)->data;if (true === $event->flags->batchSubmission && true === $setting) {- Log::debug(sprintf('Will do nothing for group #%d because it is part of a batch.', $groupId));+ Log::debug('Will do nothing for event because it is part of a batch.');return;}- Log::debug(sprintf('Will (joined with group #%d) collect all open transaction groups and process them.', $groupId));+ Log::debug('Will also collect all open transaction groups and process them.');$repository = app(JournalRepositoryInterface::class);- $set = $collection->merge($repository->getAllUncompletedJournals());- if (0 === $set->count()) {- Log::debug('Set is empty, never mind.');+ $journals = $event->objects->transactionJournals->merge($repository->getAllUncompletedJournals());- return;- }- Log::debug(sprintf('Set count is %d', $set->count()));+ Log::debug(sprintf('Transaction journal count is %d', $journals->count()));if (!$event->flags->applyRules) {- Log::debug(sprintf('Will NOT process rules for %d journal(s)', $set->count()));+ Log::debug(sprintf('Will NOT process rules for %d journal(s)', $journals->count()));}if (!$event->flags->recalculateCredit) {- Log::debug(sprintf('Will NOT recalculate credit for %d journal(s)', $set->count()));+ Log::debug(sprintf('Will NOT recalculate credit for %d journal(s)', $journals->count()));}if (!$event->flags->fireWebhooks) {- Log::debug(sprintf('Will NOT fire webhooks for %d journal(s)', $set->count()));+ Log::debug(sprintf('Will NOT fire webhooks for %d journal(s)', $journals->count()));}+if ($event->flags->applyRules) {- $this->processRules($set);+ $this->processRules($journals,'store-journal');}if ($event->flags->recalculateCredit) {- $this->recalculateCredit($set);+ $this->recalculateCredit($event->objects->accounts);}if ($event->flags->fireWebhooks) {- $this->fireWebhooks($set);- }- // always remove old relevant statistics.- self::removePeriodStatistics($set);-- // recalculate running balance if necessary.- if (true === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data) {- $this->recalculateRunningBalance($set);- }-- $repository->markAsCompleted($set);- }-- private function getFromInternalDate(array $ids): Carbon- {- $entries = TransactionJournalMeta::whereIn('transaction_journal_id', $ids)->where('name', '_internal_previous_date')->get(['journal_meta.*']);- $array = $entries->toArray();- $return = today()->subDay();- if (count($array) > 0) {- usort($array, function (array $a, array $b) {- return Carbon::parse($a['data'])->gt(Carbon::parse($b['data']));- });-- $date = Carbon::parse($array[0]['data']);- $return = $date->lt($return) ? $date : $return;- }-- return $return;- }-- private function recalculateRunningBalance(Collection $set): void- {- Log::debug('Now in recalculateRunningBalance');- // find the earliest date in the set, based on date and _internal_previous_date- $earliest = $set->pluck('date')->sort()->first();- $fromInternalDate = $this->getFromInternalDate($set->pluck('id')->toArray());- $earliest = $fromInternalDate->lt($earliest) ? $fromInternalDate : $earliest;- Log::debug(sprintf('Found earliest date: %s', $earliest->toW3cString()));-- // get accounts- $accounts = Account::leftJoin('transactions', 'transactions.account_id', 'accounts.id')- ->leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id')- ->leftJoin('account_types', 'account_types.id', 'accounts.account_type_id')- ->whereIn('transaction_journals.id', $set->pluck('id')->toArray())- ->get(['accounts.*'])- ;-- Log::debug('Found accounts to process', $accounts->pluck('id')->toArray());-- AccountBalanceCalculator::optimizedCalculation($accounts, $earliest);- }-- public static function removePeriodStatistics(Collection $set): void- {- if (auth()->check()) {- Log::debug('Always remove period statistics');-- /** @var PeriodStatisticRepositoryInterface $repository */- $repository = app(PeriodStatisticRepositoryInterface::class);- $repository->deleteStatisticsForCollection($set);+ $this->fireWebhooks($journals, WebhookTrigger::STORE_TRANSACTION);}- }-- private function fireWebhooks(Collection $set): void- {- // collect transaction groups by set ids.- $groups = TransactionGroup::whereIn('id', array_unique($set->pluck('transaction_group_id')->toArray()))->get();-- Log::debug(__METHOD__);-- /** @var TransactionJournal $first */- $first = $set->first();- $user = $first->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($groups);- // 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());- }-- private function recalculateCredit(Collection $set): void- {- Log::debug(sprintf('Will now recalculateCredit for %d journal(s)', $set->count()));-- /** @var CreditRecalculateService $object */- $object = app(CreditRecalculateService::class);- $object->setJournals($set);- $object->recalculate();- }-- private function processRules(Collection $set): void- {- Log::debug(sprintf('Will now processRules for %d journal(s)', $set->count()));- $array = $set->pluck('id')->toArray();-- /** @var TransactionJournal $first */- $first = $set->first();- $journalIds = implode(',', $array);- $user = $first->user;- Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds));-- // collect rules:- $ruleGroupRepository = app(RuleGroupRepositoryInterface::class);- $ruleGroupRepository->setUser($user);-- // add the groups to the rule engine.- // it should run the rules in the group and cancel the group if necessary.- Log::debug('Fire processRules with ALL store-journal rule groups.');- $groups = $ruleGroupRepository->getRuleGroupsWithRules('store-journal');-- // create and fire rule engine.- $newRuleEngine = app(RuleEngineInterface::class);- $newRuleEngine->setUser($user);- $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]);- $newRuleEngine->setRuleGroups($groups);- $newRuleEngine->fire();+ $this->removePeriodStatistics($event->objects);+ $this->recalculateRunningBalance($event->objects);+ $repository->markAsCompleted($journals);}}diff --git a/app/Listeners/Model/TransactionGroup/SupportsGroupProcessingTrait.php b/app/Listeners/Model/TransactionGroup/SupportsGroupProcessingTrait.phpnew file mode 100644index 0000000000..7c85f6e708--- /dev/null+++ b/app/Listeners/Model/TransactionGroup/SupportsGroupProcessingTrait.php@@ -0,0 +1,135 @@+<?php++namespace FireflyIII\Listeners\Model\TransactionGroup;++use Carbon\Carbon;+use FireflyIII\Enums\WebhookTrigger;+use FireflyIII\Events\Model\TransactionGroup\TransactionGroupEventObjects;+use FireflyIII\Events\Model\Webhook\WebhookMessagesRequestSending;+use FireflyIII\Generator\Webhook\MessageGeneratorInterface;+use FireflyIII\Models\Account;+use FireflyIII\Models\RuleTrigger;+use FireflyIII\Models\TransactionGroup;+use FireflyIII\Models\TransactionJournal;+use FireflyIII\Models\TransactionJournalMeta;+use FireflyIII\Repositories\PeriodStatistic\PeriodStatisticRepositoryInterface;+use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;+use FireflyIII\Services\Internal\Support\CreditRecalculateService;+use FireflyIII\Support\Facades\FireflyConfig;+use FireflyIII\Support\Models\AccountBalanceCalculator;+use FireflyIII\TransactionRules\Engine\RuleEngineInterface;+use Illuminate\Support\Collection;+use Illuminate\Support\Facades\Log;++trait SupportsGroupProcessingTrait+{+ private function recalculateCredit(Collection $accounts): void+ {+ Log::debug(sprintf('Will now recalculateCredit for %d account(s)', $accounts->count()));++ /** @var CreditRecalculateService $object */+ $object = app(CreditRecalculateService::class);+ $object->setAccounts($accounts);+ $object->recalculate();+ }++ private function fireWebhooks(Collection $journals, WebhookTrigger $trigger): void+ {+ // collect transaction groups by set ids.+ $groups = TransactionGroup::whereIn('id', array_unique($journals->pluck('transaction_group_id')->toArray()))->get();++ Log::debug(__METHOD__);++ /** @var TransactionJournal $first */+ $first = $journals->first();+ $user = $first->user;++ /** @var MessageGeneratorInterface $engine */+ $engine = app(MessageGeneratorInterface::class);+ $engine->setUser($user);++ // tell the generator which trigger it should look for+ $engine->setTrigger($trigger);+ // tell the generator which objects to process+ $engine->setObjects($groups);+ // tell the generator to generate the messages+ $engine->generateMessages();+ }++ protected function removePeriodStatistics(TransactionGroupEventObjects $set): void+ {+ if (auth()->check()) {+ Log::debug('Always remove period statistics');++ /** @var PeriodStatisticRepositoryInterface $repository */+ $repository = app(PeriodStatisticRepositoryInterface::class);+ $repository->deleteStatisticsForCollection($set->transactionJournals);+ // FIXME extend for categories, accounts, etc.+ }+ }+++ protected function processRules(Collection $set, string $type): void+ {+ Log::debug(sprintf('Will now processRules("%s") for %d journal(s)', $type, $set->count()));+ $array = $set->pluck('id')->toArray();++ /** @var TransactionJournal $first */+ $first = $set->first();+ $journalIds = implode(',', $array);+ $user = $first->user;+ Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds));++ // collect rules:+ $ruleGroupRepository = app(RuleGroupRepositoryInterface::class);+ $ruleGroupRepository->setUser($user);++ // add the groups to the rule engine.+ // it should run the rules in the group and cancel the group if necessary.+ Log::debug(sprintf('Fire processRules with ALL %s rule groups.', $type));+ $groups = $ruleGroupRepository->getRuleGroupsWithRules($type);++ // create and fire rule engine.+ $newRuleEngine = app(RuleEngineInterface::class);+ $newRuleEngine->setUser($user);+ $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]);+ $newRuleEngine->setRuleGroups($groups);+ $newRuleEngine->fire();+ }++ protected function recalculateRunningBalance(TransactionGroupEventObjects $objects): void+ {+ if (true === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data) {+ return;+ }+ Log::debug('Now in recalculateRunningBalance');+ // find the earliest date in the set, based on date and _internal_previous_date+ $earliest = $objects->transactionJournals->pluck('date')->sort()->first();+ $fromInternalDate = $this->getFromInternalDate($objects->transactionJournals->pluck('id')->toArray());+ $earliest = $fromInternalDate->lt($earliest) ? $fromInternalDate : $earliest;+ Log::debug(sprintf('Found earliest date: %s', $earliest->toW3cString()));++ $accounts = Account::whereIn('id', $objects->accounts->pluck('id')->toArray())->get(['accounts.*']);++ Log::debug('Found accounts to process', $accounts->pluck('id')->toArray());++ AccountBalanceCalculator::optimizedCalculation($accounts, $earliest);+ }++ private function getFromInternalDate(array $ids): Carbon+ {+ $entries = TransactionJournalMeta::whereIn('transaction_journal_id', $ids)->where('name', '_internal_previous_date')->get(['journal_meta.*']);+ $array = $entries->toArray();+ $return = today()->subDay();+ if (count($array) > 0) {+ usort($array, function (array $a, array $b) {+ return Carbon::parse($a['data'])->gt(Carbon::parse($b['data']));+ });++ $date = Carbon::parse($array[0]['data']);+ $return = $date->lt($return) ? $date : $return;+ }++ return $return;+ }+}diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.phpindex 98f3f7ef91..7ba764a249 100644--- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php+++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php@@ -29,6 +29,8 @@ use Exception;use FireflyIII\Enums\TransactionTypeEnum;use FireflyIII\Events\Model\TransactionGroup\CreatedSingleTransactionGroup;use FireflyIII\Events\Model\TransactionGroup\TransactionGroupEventFlags;+use FireflyIII\Events\Model\TransactionGroup\TransactionGroupEventObjects;+use FireflyIII\Events\Model\Webhook\WebhookMessagesRequestSending;use FireflyIII\Exceptions\DuplicateTransactionException;use FireflyIII\Exceptions\FireflyException;use FireflyIII\Factory\TransactionGroupFactory;@@ -413,12 +415,15 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,}Preferences::mark();+ $objects = TransactionGroupEventObjects::collectFromTransactionGroup($transactionGroup);$flags = new TransactionGroupEventFlags();$flags->applyRules = $data['apply_rules'] ?? true;$flags->fireWebhooks = $data['fire_webhooks'] ?? true;$flags->batchSubmission = $data['batch_submission'] ?? false;Log::debug('CreatedSingleTransactionGroup');- event(new CreatedSingleTransactionGroup($transactionGroup, $flags));+ event(new CreatedSingleTransactionGroup($flags, $objects));+ Log::debug(sprintf('send event WebhookMessagesRequestSending from %s', __METHOD__));+ event(new WebhookMessagesRequestSending());return $transactionGroup;}diff --git a/app/Services/Internal/Support/CreditRecalculateService.php b/app/Services/Internal/Support/CreditRecalculateService.phpindex 1f00552ef4..01d8a4ef54 100644--- a/app/Services/Internal/Support/CreditRecalculateService.php+++ b/app/Services/Internal/Support/CreditRecalculateService.php@@ -45,12 +45,14 @@ class CreditRecalculateServiceprivate ?Account $account = null;private ?TransactionGroup $group = null;private Collection $journals;+ private Collection $accounts;private AccountRepositoryInterface $repository;private array $work = [];public function __construct(){$this->journals = new Collection();+ $this->accounts = new Collection();}public function recalculate(): void@@ -65,6 +67,9 @@ class CreditRecalculateService// work based on account.$this->processAccount();}+ if($this->accounts->count() > 0) {+ $this->processAccounts();+ }if ($this->journals->count() > 0) {$this->processJournals();}@@ -206,7 +211,7 @@ class CreditRecalculateService->orderBy('transaction_journals.date', 'ASC')->get(['transactions.*']);- $transactions->count();+ // $transactions->count();// Log::debug(sprintf('Found %d transaction(s) to process.', $total));/** @var Transaction $transaction */@@ -493,4 +498,22 @@ class CreditRecalculateService{$this->journals = $journals;}++ private function processAccounts(): void+ {+ $valid = config('firefly.valid_liabilities');+ /** @var Account $account */+ foreach($this->accounts as $account) {+ if (in_array($account->accountType->type, $valid, true)) {+ $this->work[] = $account;+ }+ }+ }++ public function setAccounts(Collection $accounts): void+ {+ $this->accounts = $accounts;+ }++}diff --git a/app/Services/Internal/Update/GroupCloneService.php b/app/Services/Internal/Update/GroupCloneService.phpindex 0dc6778bfa..54540afc4a 100644--- a/app/Services/Internal/Update/GroupCloneService.php+++ b/app/Services/Internal/Update/GroupCloneService.php@@ -26,6 +26,8 @@ namespace FireflyIII\Services\Internal\Update;use FireflyIII\Events\Model\TransactionGroup\CreatedSingleTransactionGroup;use FireflyIII\Events\Model\TransactionGroup\TransactionGroupEventFlags;+use FireflyIII\Events\Model\TransactionGroup\TransactionGroupEventObjects;+use FireflyIII\Events\Model\Webhook\WebhookMessagesRequestSending;use FireflyIII\Factory\PiggyBankEventFactory;use FireflyIII\Models\Budget;use FireflyIII\Models\Category;@@ -36,6 +38,7 @@ use FireflyIII\Models\Transaction;use FireflyIII\Models\TransactionGroup;use FireflyIII\Models\TransactionJournal;use FireflyIII\Models\TransactionJournalMeta;+use Illuminate\Support\Facades\Log;/*** Class GroupCloneService@@ -52,7 +55,11 @@ class GroupCloneService// event!$flags = new TransactionGroupEventFlags();- event(new CreatedSingleTransactionGroup($newGroup, $flags));+ $objects = TransactionGroupEventObjects::collectFromTransactionGroup($newGroup);+ event(new CreatedSingleTransactionGroup($flags, $objects));++ Log::debug(sprintf('send event WebhookMessagesRequestSending from %s', __METHOD__));+ event(new WebhookMessagesRequestSending());return $newGroup;}