firefly-iii/app/TransactionRules/Engine/SearchRuleEngine.php

574 lines
19 KiB
PHP
Raw Normal View History

2020-08-22 06:01:37 -05:00
<?php
2021-01-29 11:50:35 -06:00
/*
* SearchRuleEngine.php
* Copyright (c) 2021 james@firefly-iii.org
*
* 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/>.
*/
2020-09-18 05:16:47 -05:00
declare(strict_types=1);
2020-08-22 06:01:37 -05:00
namespace FireflyIII\TransactionRules\Engine;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Rule;
use FireflyIII\Models\RuleAction;
2020-12-18 12:16:56 -06:00
use FireflyIII\Models\RuleGroup;
use FireflyIII\Models\RuleTrigger;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Support\Search\SearchInterface;
use FireflyIII\TransactionRules\Factory\ActionFactory;
use FireflyIII\User;
use Illuminate\Support\Collection;
use Log;
2020-08-22 06:01:37 -05:00
/**
* Class SearchRuleEngine
*/
class SearchRuleEngine implements RuleEngineInterface
{
2020-12-18 12:16:56 -06:00
private Collection $groups;
2021-03-21 03:15:40 -05:00
private array $operators;
2021-02-08 08:12:04 -06:00
private array $resultCount;
2021-03-21 03:15:40 -05:00
private Collection $rules;
private User $user;
private bool $refreshTriggers;
public function __construct()
{
2022-10-30 08:24:37 -05:00
$this->rules = new Collection();
$this->groups = new Collection();
2021-02-08 08:12:04 -06:00
$this->operators = [];
$this->resultCount = [];
// always collect the triggers from the database, unless indicated otherwise.
$this->refreshTriggers = true;
}
/**
* @inheritDoc
*/
2021-03-21 03:15:40 -05:00
public function addOperator(array $operator): void
{
2021-03-21 03:15:40 -05:00
Log::debug('Add extra operator: ', $operator);
$this->operators[] = $operator;
}
/**
2021-03-21 03:15:40 -05:00
*
*/
2021-03-21 03:15:40 -05:00
public function find(): Collection
{
2021-03-21 03:15:40 -05:00
Log::debug('SearchRuleEngine::find()');
2022-10-30 08:24:37 -05:00
$collection = new Collection();
2021-03-21 03:15:40 -05:00
foreach ($this->rules as $rule) {
2022-10-30 08:24:37 -05:00
$found = new Collection();
2021-03-21 03:15:40 -05:00
if (true === $rule->strict) {
$found = $this->findStrictRule($rule);
}
2021-03-21 03:15:40 -05:00
if (false === $rule->strict) {
$found = $this->findNonStrictRule($rule);
2020-12-18 12:16:56 -06:00
}
2021-03-21 03:15:40 -05:00
$collection = $collection->merge($found);
2020-12-18 12:16:56 -06:00
}
2021-03-21 03:15:40 -05:00
return $collection->unique();
}
2021-03-21 03:15:40 -05:00
/**
* Finds the transactions a strict rule will execute on.
*
2022-12-29 12:42:26 -06:00
* @param Rule $rule
2021-03-21 03:15:40 -05:00
*
* @return Collection
*/
private function findStrictRule(Rule $rule): Collection
{
Log::debug(sprintf('Now in findStrictRule(#%d)', $rule->id ?? 0));
$searchArray = [];
$triggers = [];
if ($this->refreshTriggers) {
$triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->get();
}
if (!$this->refreshTriggers) {
$triggers = $rule->ruleTriggers;
}
2021-05-01 11:54:11 -05:00
2021-03-21 03:15:40 -05:00
/** @var RuleTrigger $ruleTrigger */
2021-05-01 11:54:11 -05:00
foreach ($triggers as $ruleTrigger) {
if (false === $ruleTrigger->active) {
continue;
}
2021-03-21 03:15:40 -05:00
// if needs no context, value is different:
2022-03-20 11:11:33 -05:00
$needsContext = config(sprintf('search.operators.%s.needs_context', $ruleTrigger->trigger_type)) ?? true;
2021-03-21 03:15:40 -05:00
if (false === $needsContext) {
Log::debug(sprintf('SearchRuleEngine:: add a rule trigger: %s:true', $ruleTrigger->trigger_type));
$searchArray[$ruleTrigger->trigger_type][] = 'true';
}
if (true === $needsContext) {
Log::debug(sprintf('SearchRuleEngine:: add a rule trigger: %s:"%s"', $ruleTrigger->trigger_type, $ruleTrigger->trigger_value));
$searchArray[$ruleTrigger->trigger_type][] = sprintf('"%s"', $ruleTrigger->trigger_value);
}
}
2021-05-01 11:54:11 -05:00
2021-03-21 03:15:40 -05:00
// add local operators:
foreach ($this->operators as $operator) {
Log::debug(sprintf('SearchRuleEngine:: add local added operator: %s:"%s"', $operator['type'], $operator['value']));
$searchArray[$operator['type']][] = sprintf('"%s"', $operator['value']);
}
$date = today(config('app.timezone'));
if ($this->hasSpecificJournalTrigger($searchArray)) {
$date = $this->setDateFromJournalTrigger($searchArray);
}
// build and run the search engine.
$searchEngine = app(SearchInterface::class);
$searchEngine->setUser($this->user);
$searchEngine->setPage(1);
$searchEngine->setLimit(31337);
$searchEngine->setDate($date);
foreach ($searchArray as $type => $searches) {
foreach ($searches as $value) {
$searchEngine->parseQuery(sprintf('%s:%s', $type, $value));
}
}
$result = $searchEngine->searchTransactions();
return $result->getCollection();
}
/**
* Search in the triggers of this particular search and if it contains
* one search operator for "journal_id" it means the date ranges
* in the search may need to be updated.
*
2022-12-29 12:42:26 -06:00
* @param array $array
2021-03-21 03:15:40 -05:00
*
* @return bool
*/
private function hasSpecificJournalTrigger(array $array): bool
{
Log::debug('Now in hasSpecificJournalTrigger.');
$journalTrigger = false;
$dateTrigger = false;
foreach ($array as $triggerName => $values) {
2021-05-24 01:06:56 -05:00
if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
Log::debug('Found a journal_id trigger with 1 journal, true.');
$journalTrigger = true;
2021-03-21 03:15:40 -05:00
}
if (in_array($triggerName, ['date_is', 'date', 'on', 'date_before', 'before', 'date_after', 'after'], true)) {
Log::debug('Found a date related trigger, set to true.');
$dateTrigger = true;
}
}
$result = $journalTrigger && $dateTrigger;
Log::debug(sprintf('Result of hasSpecificJournalTrigger is %s.', var_export($result, true)));
return $result;
}
/**
2022-12-29 12:42:26 -06:00
* @param array $array
2021-03-21 03:15:40 -05:00
*
* @return Carbon
*/
private function setDateFromJournalTrigger(array $array): Carbon
{
Log::debug('Now in setDateFromJournalTrigger()');
$journalId = 0;
foreach ($array as $triggerName => $values) {
2021-05-24 01:06:56 -05:00
if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
2022-12-29 12:42:26 -06:00
$journalId = (int)trim(($values[0] ?? '"0"'), '"'); // follows format "123".
2021-05-24 01:06:56 -05:00
Log::debug(sprintf('Found journal ID #%d', $journalId));
2021-03-21 03:15:40 -05:00
}
}
if (0 !== $journalId) {
$repository = app(JournalRepositoryInterface::class);
$repository->setUser($this->user);
2021-06-29 23:17:38 -05:00
$journal = $repository->find($journalId);
2021-03-21 03:15:40 -05:00
if (null !== $journal) {
$date = $journal->date;
Log::debug(sprintf('Found journal #%d with date %s.', $journal->id, $journal->date->format('Y-m-d')));
return $date;
}
}
Log::debug('Found no journal, return default date.');
return today(config('app.timezone'));
}
/**
2022-12-29 12:42:26 -06:00
* @inheritDoc
*/
public function setUser(User $user): void
{
$this->user = $user;
$this->operators = [];
}
/**
* @param Rule $rule
*
* @return Collection
*/
private function findNonStrictRule(Rule $rule): Collection
{
// start a search query for individual each trigger:
$total = new Collection();
$count = 0;
$triggers = [];
if ($this->refreshTriggers) {
$triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->get();
}
if (!$this->refreshTriggers) {
$triggers = $rule->ruleTriggers;
}
/** @var RuleTrigger $ruleTrigger */
foreach ($triggers as $ruleTrigger) {
if (false === $ruleTrigger->active) {
continue;
}
if ('user_action' === $ruleTrigger->trigger_type) {
Log::debug('Skip trigger type.');
continue;
}
$searchArray = [];
2022-03-20 11:11:33 -05:00
$needsContext = config(sprintf('search.operators.%s.needs_context', $ruleTrigger->trigger_type)) ?? true;
if (false === $needsContext) {
Log::debug(sprintf('SearchRuleEngine:: non strict, will search for: %s:true', $ruleTrigger->trigger_type));
$searchArray[$ruleTrigger->trigger_type] = 'true';
}
if (true === $needsContext) {
Log::debug(sprintf('SearchRuleEngine:: non strict, will search for: %s:"%s"', $ruleTrigger->trigger_type, $ruleTrigger->trigger_value));
$searchArray[$ruleTrigger->trigger_type] = sprintf('"%s"', $ruleTrigger->trigger_value);
}
// then, add local operators as well:
foreach ($this->operators as $operator) {
Log::debug(sprintf('SearchRuleEngine:: add local added operator: %s:"%s"', $operator['type'], $operator['value']));
$searchArray[$operator['type']] = sprintf('"%s"', $operator['value']);
}
// build and run the search engine.
$searchEngine = app(SearchInterface::class);
$searchEngine->setUser($this->user);
$searchEngine->setPage(1);
$searchEngine->setLimit(31337);
foreach ($searchArray as $type => $value) {
$searchEngine->parseQuery(sprintf('%s:%s', $type, $value));
}
$result = $searchEngine->searchTransactions();
$collection = $result->getCollection();
Log::debug(sprintf('Found in this run, %d transactions', $collection->count()));
$total = $total->merge($collection);
Log::debug(sprintf('Total collection is now %d transactions', $total->count()));
$count++;
}
Log::debug(sprintf('Total collection is now %d transactions', $total->count()));
Log::debug(sprintf('Done running %d trigger(s)', $count));
// make collection unique
$unique = $total->unique(
function (array $group) {
$str = '';
foreach ($group['transactions'] as $transaction) {
$str = sprintf('%s%d', $str, $transaction['transaction_journal_id']);
}
$key = sprintf('%d%s', $group['id'], $str);
Log::debug(sprintf('Return key: %s ', $key));
return $key;
}
);
Log::debug(sprintf('SearchRuleEngine:: Found %d transactions using search engine.', $unique->count()));
return $unique;
}
2022-03-29 08:00:29 -05:00
/**
* @inheritDoc
* @throws FireflyException
*/
public function fire(): void
{
$this->resultCount = [];
Log::debug('SearchRuleEngine::fire()!');
// if rules and no rule groups, file each rule separately.
if (0 !== $this->rules->count()) {
Log::debug(sprintf('SearchRuleEngine:: found %d rule(s) to fire.', $this->rules->count()));
foreach ($this->rules as $rule) {
$this->fireRule($rule);
}
Log::debug('SearchRuleEngine:: done processing all rules!');
return;
}
if (0 !== $this->groups->count()) {
Log::debug(sprintf('SearchRuleEngine:: found %d rule group(s) to fire.', $this->groups->count()));
// fire each group:
/** @var RuleGroup $group */
foreach ($this->groups as $group) {
$this->fireGroup($group);
}
}
Log::debug('SearchRuleEngine:: done processing all rules!');
}
/**
* Returns true if the rule has been triggered.
*
2022-12-29 12:42:26 -06:00
* @param Rule $rule
*
* @return bool
* @throws FireflyException
*/
private function fireRule(Rule $rule): bool
{
Log::debug(sprintf('Now going to fire rule #%d', $rule->id));
if (false === $rule->active) {
Log::debug(sprintf('Rule #%d is not active!', $rule->id));
return false;
}
if (true === $rule->strict) {
Log::debug(sprintf('Rule #%d is a strict rule.', $rule->id));
return $this->fireStrictRule($rule);
}
Log::debug(sprintf('Rule #%d is not strict rule.', $rule->id));
return $this->fireNonStrictRule($rule);
}
/**
* Return true if the rule is fired (the collection is larger than zero).
*
2022-12-29 12:42:26 -06:00
* @param Rule $rule
*
* @return bool
* @throws FireflyException
*/
private function fireStrictRule(Rule $rule): bool
{
Log::debug(sprintf('SearchRuleEngine::fireStrictRule(%d)!', $rule->id));
$collection = $this->findStrictRule($rule);
$this->processResults($rule, $collection);
Log::debug(sprintf('SearchRuleEngine:: done processing strict rule #%d', $rule->id));
$result = $collection->count() > 0;
if (true === $result) {
Log::debug(sprintf('SearchRuleEngine:: rule #%d was triggered (on %d transaction(s)).', $rule->id, $collection->count()));
return true;
}
Log::debug(sprintf('SearchRuleEngine:: rule #%d was not triggered (on %d transaction(s)).', $rule->id, $collection->count()));
return false;
}
/**
2022-12-29 12:42:26 -06:00
* @param Rule $rule
* @param Collection $collection
2020-12-18 12:16:56 -06:00
*
* @throws FireflyException
*/
private function processResults(Rule $rule, Collection $collection): void
{
2020-08-23 09:26:39 -05:00
Log::debug(sprintf('SearchRuleEngine:: Going to process %d results.', $collection->count()));
/** @var array $group */
foreach ($collection as $group) {
$this->processTransactionGroup($rule, $group);
}
}
/**
2022-12-29 12:42:26 -06:00
* @param Rule $rule
* @param array $group
2020-12-18 12:16:56 -06:00
*
* @throws FireflyException
*/
private function processTransactionGroup(Rule $rule, array $group): void
{
2020-08-23 09:26:39 -05:00
Log::debug(sprintf('SearchRuleEngine:: Will now execute actions on transaction group #%d', $group['id']));
/** @var array $transaction */
foreach ($group['transactions'] as $transaction) {
$this->processTransactionJournal($rule, $transaction);
}
}
/**
2022-12-29 12:42:26 -06:00
* @param Rule $rule
* @param array $transaction
2020-12-18 12:16:56 -06:00
*
* @throws FireflyException
*/
private function processTransactionJournal(Rule $rule, array $transaction): void
{
2020-08-23 09:26:39 -05:00
Log::debug(sprintf('SearchRuleEngine:: Will now execute actions on transaction journal #%d', $transaction['transaction_journal_id']));
$actions = $rule->ruleActions()->orderBy('order', 'ASC')->get();
/** @var RuleAction $ruleAction */
2022-01-30 09:53:57 -06:00
foreach ($actions as $ruleAction) {
2022-03-29 08:00:29 -05:00
if (false === $ruleAction->active) {
2022-01-30 09:53:57 -06:00
continue;
}
$break = $this->processRuleAction($ruleAction, $transaction);
if (true === $break) {
break;
}
}
}
2020-08-22 06:01:37 -05:00
/**
2022-12-29 12:42:26 -06:00
* @param RuleAction $ruleAction
* @param array $transaction
2020-12-18 12:16:56 -06:00
*
* @return bool
* @throws FireflyException
*/
private function processRuleAction(RuleAction $ruleAction, array $transaction): bool
{
Log::debug(sprintf('Executing rule action "%s" with value "%s"', $ruleAction->action_type, $ruleAction->action_value));
$actionClass = ActionFactory::getAction($ruleAction);
2021-02-08 08:12:04 -06:00
$result = $actionClass->actOnArray($transaction);
$journalId = $transaction['transaction_journal_id'] ?? 0;
if (true === $result) {
2021-04-06 06:30:09 -05:00
$this->resultCount[$journalId] = array_key_exists($journalId, $this->resultCount) ? $this->resultCount[$journalId]++ : 1;
2021-02-08 08:12:04 -06:00
Log::debug(
sprintf(
'Action "%s" on journal #%d was executed, so count a result. Updated transaction journal count is now %d.',
$ruleAction->action_type,
$transaction['transaction_journal_id'] ?? 0,
count($this->resultCount),
)
);
}
if (false === $result) {
Log::debug(sprintf('Action "%s" reports NO changes were made.', $ruleAction->action_type));
}
// pick up from the action if it actually acted or not:
if ($ruleAction->stop_processing) {
2021-02-08 08:12:04 -06:00
Log::debug(sprintf('Rule action "%s" asks to break, so break!', $ruleAction->action_type));
2020-12-18 12:16:56 -06:00
return true;
}
2020-12-18 12:16:56 -06:00
return false;
}
2020-08-24 00:03:17 -05:00
2020-08-24 00:31:50 -05:00
/**
2020-12-18 12:16:56 -06:00
* Return true if the rule is fired (the collection is larger than zero).
*
2022-12-29 12:42:26 -06:00
* @param Rule $rule
2020-12-18 12:16:56 -06:00
*
* @return bool
2020-08-24 00:31:50 -05:00
* @throws FireflyException
*/
2020-12-18 12:16:56 -06:00
private function fireNonStrictRule(Rule $rule): bool
2020-08-24 00:31:50 -05:00
{
Log::debug(sprintf('SearchRuleEngine::fireNonStrictRule(%d)!', $rule->id));
$collection = $this->findNonStrictRule($rule);
$this->processResults($rule, $collection);
Log::debug(sprintf('SearchRuleEngine:: done processing non-strict rule #%d', $rule->id));
2020-12-18 12:16:56 -06:00
return $collection->count() > 0;
2020-08-24 00:31:50 -05:00
}
2020-12-18 12:16:56 -06:00
/**
2022-12-29 12:42:26 -06:00
* @param RuleGroup $group
2020-12-18 12:16:56 -06:00
*
2022-03-29 08:10:05 -05:00
* @return void
2021-09-18 03:21:29 -05:00
* @throws FireflyException
2020-12-18 12:16:56 -06:00
*/
2022-03-29 08:10:05 -05:00
private function fireGroup(RuleGroup $group): void
2020-12-18 12:16:56 -06:00
{
$all = false;
Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $group->rules->count()));
2021-04-06 06:30:09 -05:00
/** @var Rule $rule */
2020-12-18 12:16:56 -06:00
foreach ($group->rules as $rule) {
Log::debug(sprintf('Going to fire rule #%d from group #%d', $rule->id, $group->id));
$result = $this->fireRule($rule);
if (true === $result) {
$all = true;
}
if (true === $result && true === $rule->stop_processing) {
Log::debug(sprintf('The rule was triggered and rule->stop_processing = true, so group #%d will stop processing further rules.', $group->id));
2022-03-29 08:10:05 -05:00
return;
2020-12-18 12:16:56 -06:00
}
}
}
2022-03-29 08:00:29 -05:00
/**
* Return the number of changed transactions from the previous "fire" action.
*
* @return int
*/
public function getResults(): int
{
return count($this->resultCount);
}
/**
* @inheritDoc
*/
public function setRuleGroups(Collection $ruleGroups): void
{
Log::debug(__METHOD__);
foreach ($ruleGroups as $group) {
if ($group instanceof RuleGroup) {
Log::debug(sprintf('Adding a rule group to the SearchRuleEngine: #%d ("%s")', $group->id, $group->title));
$this->groups->push($group);
}
}
}
/**
* @inheritDoc
*/
public function setRules(Collection $rules): void
{
Log::debug(__METHOD__);
foreach ($rules as $rule) {
if ($rule instanceof Rule) {
Log::debug(sprintf('Adding a rule to the SearchRuleEngine: #%d ("%s")', $rule->id, $rule->title));
$this->rules->push($rule);
}
}
}
/**
* @param bool $refreshTriggers
*/
public function setRefreshTriggers(bool $refreshTriggers): void
{
$this->refreshTriggers = $refreshTriggers;
}
2020-12-21 22:35:06 -06:00
}