chore: code cleanup.

This commit is contained in:
James Cole
2023-05-29 13:56:55 +02:00
parent 7f7644c92f
commit 1b52147a05
295 changed files with 12418 additions and 12324 deletions

View File

@@ -72,7 +72,7 @@ class AppendNotesToDescription implements ActionInterface
// only append if there is something to append
if ('' !== $note->text) {
$before = $object->description;
$object->description = trim(sprintf("%s %s", $object->description, (string)$this->clearString($note->text, false)));
$object->description = trim(sprintf('%s %s', $object->description, (string)$this->clearString($note->text, false)));
$object->save();
Log::debug(sprintf('Journal description is updated to "%s".', $object->description));

View File

@@ -114,6 +114,60 @@ class ConvertToDeposit implements ActionInterface
return false;
}
/**
* Input is a transfer from A to B.
* Output is a deposit from C to B.
* The source account is replaced.
*
* @param TransactionJournal $journal
*
* @return bool
* @throws FireflyException
* @throws JsonException
*/
private function convertTransferArray(TransactionJournal $journal): bool
{
$user = $journal->user;
// find or create revenue account.
/** @var AccountFactory $factory */
$factory = app(AccountFactory::class);
$factory->setUser($user);
$repository = app(AccountRepositoryInterface::class);
$repository->setUser($user);
$sourceAccount = $this->getSourceAccount($journal);
// get the action value, or use the original source name in case the action value is empty:
// this becomes a new or existing (revenue) account, which is the source of the new deposit.
$opposingName = '' === $this->action->action_value ? $sourceAccount->name : $this->action->action_value;
// we check all possible source account types if one exists:
$validTypes = config('firefly.expected_source_types.source.Deposit');
$opposingAccount = $repository->findByName($opposingName, $validTypes);
if (null === $opposingAccount) {
$opposingAccount = $factory->findOrCreate($opposingName, AccountType::REVENUE);
}
Log::debug(sprintf('ConvertToDeposit. Action value is "%s", revenue name is "%s"', $this->action->action_value, $opposingAccount->name));
// update source transaction(s) to be revenue account
DB::table('transactions')
->where('transaction_journal_id', '=', $journal->id)
->where('amount', '<', 0)
->update(['account_id' => $opposingAccount->id]);
// change transaction type of journal:
$newType = TransactionType::whereType(TransactionType::DEPOSIT)->first();
DB::table('transaction_journals')
->where('id', '=', $journal->id)
->update(['transaction_type_id' => $newType->id, 'bill_id' => null]);
Log::debug('Converted transfer to deposit.');
return true;
}
/**
* Input is a withdrawal from A to B
* Is converted to a deposit from C to A.
@@ -175,57 +229,18 @@ class ConvertToDeposit implements ActionInterface
}
/**
* Input is a transfer from A to B.
* Output is a deposit from C to B.
* The source account is replaced.
*
* @param TransactionJournal $journal
*
* @return bool
* @return Account
* @throws FireflyException
* @throws JsonException
*/
private function convertTransferArray(TransactionJournal $journal): bool
private function getDestinationAccount(TransactionJournal $journal): Account
{
$user = $journal->user;
// find or create revenue account.
/** @var AccountFactory $factory */
$factory = app(AccountFactory::class);
$factory->setUser($user);
$repository = app(AccountRepositoryInterface::class);
$repository->setUser($user);
$sourceAccount = $this->getSourceAccount($journal);
// get the action value, or use the original source name in case the action value is empty:
// this becomes a new or existing (revenue) account, which is the source of the new deposit.
$opposingName = '' === $this->action->action_value ? $sourceAccount->name : $this->action->action_value;
// we check all possible source account types if one exists:
$validTypes = config('firefly.expected_source_types.source.Deposit');
$opposingAccount = $repository->findByName($opposingName, $validTypes);
if (null === $opposingAccount) {
$opposingAccount = $factory->findOrCreate($opposingName, AccountType::REVENUE);
/** @var Transaction|null $destAccount */
$destAccount = $journal->transactions()->where('amount', '>', 0)->first();
if (null === $destAccount) {
throw new FireflyException(sprintf('Cannot find destination transaction for journal #%d', $journal->id));
}
Log::debug(sprintf('ConvertToDeposit. Action value is "%s", revenue name is "%s"', $this->action->action_value, $opposingAccount->name));
// update source transaction(s) to be revenue account
DB::table('transactions')
->where('transaction_journal_id', '=', $journal->id)
->where('amount', '<', 0)
->update(['account_id' => $opposingAccount->id]);
// change transaction type of journal:
$newType = TransactionType::whereType(TransactionType::DEPOSIT)->first();
DB::table('transaction_journals')
->where('id', '=', $journal->id)
->update(['transaction_type_id' => $newType->id, 'bill_id' => null]);
Log::debug('Converted transfer to deposit.');
return true;
return $destAccount->account;
}
/**
@@ -242,19 +257,4 @@ class ConvertToDeposit implements ActionInterface
}
return $sourceTransaction->account;
}
/**
* @param TransactionJournal $journal
* @return Account
* @throws FireflyException
*/
private function getDestinationAccount(TransactionJournal $journal): Account
{
/** @var Transaction|null $destAccount */
$destAccount = $journal->transactions()->where('amount', '>', 0)->first();
if (null === $destAccount) {
throw new FireflyException(sprintf('Cannot find destination transaction for journal #%d', $journal->id));
}
return $destAccount->account;
}
}

View File

@@ -139,6 +139,48 @@ class ConvertToTransfer implements ActionInterface
return false;
}
/**
* A deposit is from Revenue to Asset.
* We replace the Revenue with another asset.
*
* @param TransactionJournal $journal
* @param Account $opposing
*
* @return bool
* @throws FireflyException
*/
private function convertDepositArray(TransactionJournal $journal, Account $opposing): bool
{
$destAccount = $this->getDestinationAccount($journal);
if ((int)$destAccount->id === (int)$opposing->id) {
Log::error(
vsprintf(
'Journal #%d has already has "%s" as a destination asset. ConvertToTransfer failed. (rule #%d).',
[$journal->id, $opposing->name, $this->action->rule_id]
)
);
return false;
}
// update source transaction:
DB::table('transactions')
->where('transaction_journal_id', '=', $journal->id)
->where('amount', '<', 0)
->update(['account_id' => $opposing->id]);
// change transaction type of journal:
$newType = TransactionType::whereType(TransactionType::TRANSFER)->first();
DB::table('transaction_journals')
->where('id', '=', $journal->id)
->update(['transaction_type_id' => $newType->id, 'bill_id' => null]);
Log::debug('Converted deposit to transfer.');
return true;
}
/**
* A withdrawal is from Asset to Expense.
* We replace the Expense with another asset.
@@ -182,63 +224,6 @@ class ConvertToTransfer implements ActionInterface
return true;
}
/**
* A deposit is from Revenue to Asset.
* We replace the Revenue with another asset.
*
* @param TransactionJournal $journal
* @param Account $opposing
*
* @return bool
* @throws FireflyException
*/
private function convertDepositArray(TransactionJournal $journal, Account $opposing): bool
{
$destAccount = $this->getDestinationAccount($journal);
if ((int)$destAccount->id === (int)$opposing->id) {
Log::error(
vsprintf(
'Journal #%d has already has "%s" as a destination asset. ConvertToTransfer failed. (rule #%d).',
[$journal->id, $opposing->name, $this->action->rule_id]
)
);
return false;
}
// update source transaction:
DB::table('transactions')
->where('transaction_journal_id', '=', $journal->id)
->where('amount', '<', 0)
->update(['account_id' => $opposing->id]);
// change transaction type of journal:
$newType = TransactionType::whereType(TransactionType::TRANSFER)->first();
DB::table('transaction_journals')
->where('id', '=', $journal->id)
->update(['transaction_type_id' => $newType->id, 'bill_id' => null]);
Log::debug('Converted deposit to transfer.');
return true;
}
/**
* @param TransactionJournal $journal
* @return Account
* @throws FireflyException
*/
private function getSourceAccount(TransactionJournal $journal): Account
{
/** @var Transaction|null $sourceTransaction */
$sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $sourceTransaction) {
throw new FireflyException(sprintf('Cannot find source transaction for journal #%d', $journal->id));
}
return $sourceTransaction->account;
}
/**
* @param TransactionJournal $journal
* @return Account
@@ -254,21 +239,6 @@ class ConvertToTransfer implements ActionInterface
return $destAccount->account;
}
/**
* @param int $journalId
* @return string
*/
private function getSourceType(int $journalId): string
{
/** @var TransactionJournal $journal */
$journal = TransactionJournal::find($journalId);
if (null === $journal) {
Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId));
return '';
}
return (string)$journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type;
}
/**
* @param int $journalId
* @return string
@@ -283,4 +253,34 @@ class ConvertToTransfer implements ActionInterface
}
return (string)$journal->transactions()->where('amount', '>', 0)->first()?->account?->accountType?->type;
}
/**
* @param TransactionJournal $journal
* @return Account
* @throws FireflyException
*/
private function getSourceAccount(TransactionJournal $journal): Account
{
/** @var Transaction|null $sourceTransaction */
$sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $sourceTransaction) {
throw new FireflyException(sprintf('Cannot find source transaction for journal #%d', $journal->id));
}
return $sourceTransaction->account;
}
/**
* @param int $journalId
* @return string
*/
private function getSourceType(int $journalId): string
{
/** @var TransactionJournal $journal */
$journal = TransactionJournal::find($journalId);
if (null === $journal) {
Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId));
return '';
}
return (string)$journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type;
}
}

View File

@@ -34,7 +34,6 @@ use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\User;
use Illuminate\Support\Facades\Log;
use JsonException;
@@ -113,7 +112,7 @@ class ConvertToWithdrawal implements ActionInterface
}
/**
* @param TransactionJournal $journal
* @param TransactionJournal $journal
* @return bool
* @throws FireflyException
* @throws JsonException
@@ -170,7 +169,7 @@ class ConvertToWithdrawal implements ActionInterface
* Input is a transfer from A to B.
* Output is a withdrawal from A to C.
*
* @param TransactionJournal $journal
* @param TransactionJournal $journal
*
* @return bool
* @throws FireflyException
@@ -187,7 +186,7 @@ class ConvertToWithdrawal implements ActionInterface
$repository = app(AccountRepositoryInterface::class);
$repository->setUser($user);
$destAccount = $this->getDestinationAccount($journal);
$destAccount = $this->getDestinationAccount($journal);
// get the action value, or use the original source name in case the action value is empty:
// this becomes a new or existing (expense) account, which is the destination of the new withdrawal.
@@ -218,21 +217,6 @@ class ConvertToWithdrawal implements ActionInterface
return true;
}
/**
* @param TransactionJournal $journal
* @return Account
* @throws FireflyException
*/
private function getSourceAccount(TransactionJournal $journal): Account
{
/** @var Transaction|null $sourceTransaction */
$sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $sourceTransaction) {
throw new FireflyException(sprintf('Cannot find source transaction for journal #%d', $journal->id));
}
return $sourceTransaction->account;
}
/**
* @param TransactionJournal $journal
* @return Account
@@ -247,4 +231,19 @@ class ConvertToWithdrawal implements ActionInterface
}
return $destAccount->account;
}
/**
* @param TransactionJournal $journal
* @return Account
* @throws FireflyException
*/
private function getSourceAccount(TransactionJournal $journal): Account
{
/** @var Transaction|null $sourceTransaction */
$sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $sourceTransaction) {
throw new FireflyException(sprintf('Cannot find source transaction for journal #%d', $journal->id));
}
return $sourceTransaction->account;
}
}

View File

@@ -134,6 +134,49 @@ class UpdatePiggybank implements ActionInterface
return false;
}
/**
* @param PiggyBank $piggyBank
* @param TransactionJournal $journal
* @param string $amount
* @return void
*/
private function addAmount(PiggyBank $piggyBank, TransactionJournal $journal, string $amount): void
{
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUser($journal->user);
// how much can we add to the piggy bank?
if (0 !== bccomp($piggyBank->targetamount, '0')) {
$toAdd = bcsub($piggyBank->targetamount, $repository->getCurrentAmount($piggyBank));
Log::debug(sprintf('Max amount to add to piggy bank is %s, amount is %s', $toAdd, $amount));
// update amount to fit:
$amount = -1 === bccomp($amount, $toAdd) ? $amount : $toAdd;
Log::debug(sprintf('Amount is now %s', $amount));
}
if (0 === bccomp($piggyBank->targetamount, '0')) {
Log::debug('Target amount is zero, can add anything.');
}
// if amount is zero, stop.
if (0 === bccomp('0', $amount)) {
app('log')->warning('Amount left is zero, stop.');
return;
}
// make sure we can add amount:
if (false === $repository->canAddAmount($piggyBank, $amount)) {
app('log')->warning(sprintf('Cannot add %s to piggy bank.', $amount));
return;
}
Log::debug(sprintf('Will now add %s to piggy bank.', $amount));
$repository->addAmount($piggyBank, $amount, $journal);
}
/**
* @param User $user
*
@@ -180,47 +223,4 @@ class UpdatePiggybank implements ActionInterface
$repository->removeAmount($piggyBank, $amount, $journal);
}
/**
* @param PiggyBank $piggyBank
* @param TransactionJournal $journal
* @param string $amount
* @return void
*/
private function addAmount(PiggyBank $piggyBank, TransactionJournal $journal, string $amount): void
{
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUser($journal->user);
// how much can we add to the piggy bank?
if (0 !== bccomp($piggyBank->targetamount, '0')) {
$toAdd = bcsub($piggyBank->targetamount, $repository->getCurrentAmount($piggyBank));
Log::debug(sprintf('Max amount to add to piggy bank is %s, amount is %s', $toAdd, $amount));
// update amount to fit:
$amount = -1 === bccomp($amount, $toAdd) ? $amount : $toAdd;
Log::debug(sprintf('Amount is now %s', $amount));
}
if (0 === bccomp($piggyBank->targetamount, '0')) {
Log::debug('Target amount is zero, can add anything.');
}
// if amount is zero, stop.
if (0 === bccomp('0', $amount)) {
app('log')->warning('Amount left is zero, stop.');
return;
}
// make sure we can add amount:
if (false === $repository->canAddAmount($piggyBank, $amount)) {
app('log')->warning(sprintf('Cannot add %s to piggy bank.', $amount));
return;
}
Log::debug(sprintf('Will now add %s to piggy bank.', $amount));
$repository->addAmount($piggyBank, $amount, $journal);
}
}

View File

@@ -55,6 +55,12 @@ interface RuleEngineInterface
*/
public function getResults(): int;
/**
* @param bool $refreshTriggers
* @return void
*/
public function setRefreshTriggers(bool $refreshTriggers): void;
/**
* Add entire rule groups for the engine to execute.
*
@@ -73,10 +79,4 @@ interface RuleEngineInterface
* @param User $user
*/
public function setUser(User $user): void;
/**
* @param bool $refreshTriggers
* @return void
*/
public function setRefreshTriggers(bool $refreshTriggers): void;
}

View File

@@ -44,10 +44,10 @@ class SearchRuleEngine implements RuleEngineInterface
{
private Collection $groups;
private array $operators;
private bool $refreshTriggers;
private array $resultCount;
private Collection $rules;
private User $user;
private bool $refreshTriggers;
public function __construct()
{
@@ -91,129 +91,79 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* Finds the transactions a strict rule will execute on.
*
* @param Rule $rule
*
* @return Collection
* @inheritDoc
* @throws FireflyException
*/
private function findStrictRule(Rule $rule): Collection
public function fire(): void
{
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;
}
$this->resultCount = [];
Log::debug('SearchRuleEngine::fire()!');
/** @var RuleTrigger $ruleTrigger */
foreach ($triggers as $ruleTrigger) {
if (false === $ruleTrigger->active) {
continue;
// 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!');
// if needs no context, value is different:
$needsContext = config(sprintf('search.operators.%s.needs_context', $ruleTrigger->trigger_type)) ?? true;
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);
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);
}
}
// 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();
Log::debug('SearchRuleEngine:: done processing all rules!');
}
/**
* 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.
* Return the number of changed transactions from the previous "fire" action.
*
* @param array $array
*
* @return bool
* @return int
*/
private function hasSpecificJournalTrigger(array $array): bool
public function getResults(): int
{
Log::debug('Now in hasSpecificJournalTrigger.');
$journalTrigger = false;
$dateTrigger = false;
foreach ($array as $triggerName => $values) {
if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
Log::debug('Found a journal_id trigger with 1 journal, true.');
$journalTrigger = true;
}
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;
return count($this->resultCount);
}
/**
* @param array $array
*
* @return Carbon
* @param bool $refreshTriggers
*/
private function setDateFromJournalTrigger(array $array): Carbon
public function setRefreshTriggers(bool $refreshTriggers): void
{
Log::debug('Now in setDateFromJournalTrigger()');
$journalId = 0;
foreach ($array as $triggerName => $values) {
if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
$journalId = (int)trim(($values[0] ?? '"0"'), '"'); // follows format "123".
Log::debug(sprintf('Found journal ID #%d', $journalId));
$this->refreshTriggers = $refreshTriggers;
}
/**
* @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);
}
}
if (0 !== $journalId) {
$repository = app(JournalRepositoryInterface::class);
$repository->setUser($this->user);
$journal = $repository->find($journalId);
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;
/**
* @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);
}
}
Log::debug('Found no journal, return default date.');
return today(config('app.timezone'));
}
/**
@@ -309,33 +259,112 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* @inheritDoc
* Finds the transactions a strict rule will execute on.
*
* @param Rule $rule
*
* @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;
}
/** @var RuleTrigger $ruleTrigger */
foreach ($triggers as $ruleTrigger) {
if (false === $ruleTrigger->active) {
continue;
}
// if needs no context, value is different:
$needsContext = config(sprintf('search.operators.%s.needs_context', $ruleTrigger->trigger_type)) ?? true;
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);
}
}
// 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();
}
/**
* @param RuleGroup $group
*
* @return void
* @throws FireflyException
*/
public function fire(): void
private function fireGroup(RuleGroup $group): 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);
$all = false;
Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $group->rules->count()));
/** @var Rule $rule */
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;
}
Log::debug('SearchRuleEngine:: done processing all rules!');
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));
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);
return;
}
}
Log::debug('SearchRuleEngine:: done processing all rules!');
}
/**
* Return true if the rule is fired (the collection is larger than zero).
*
* @param Rule $rule
*
* @return bool
* @throws FireflyException
*/
private function fireNonStrictRule(Rule $rule): bool
{
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));
return $collection->count() > 0;
}
/**
@@ -391,6 +420,36 @@ class SearchRuleEngine implements RuleEngineInterface
return false;
}
/**
* 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.
*
* @param array $array
*
* @return bool
*/
private function hasSpecificJournalTrigger(array $array): bool
{
Log::debug('Now in hasSpecificJournalTrigger.');
$journalTrigger = false;
$dateTrigger = false;
foreach ($array as $triggerName => $values) {
if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
Log::debug('Found a journal_id trigger with 1 journal, true.');
$journalTrigger = true;
}
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;
}
/**
* @param Rule $rule
* @param Collection $collection
@@ -406,43 +465,6 @@ class SearchRuleEngine implements RuleEngineInterface
}
}
/**
* @param Rule $rule
* @param array $group
*
* @throws FireflyException
*/
private function processTransactionGroup(Rule $rule, array $group): void
{
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);
}
}
/**
* @param Rule $rule
* @param array $transaction
*
* @throws FireflyException
*/
private function processTransactionJournal(Rule $rule, array $transaction): void
{
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 */
foreach ($actions as $ruleAction) {
if (false === $ruleAction->active) {
continue;
}
$break = $this->processRuleAction($ruleAction, $transaction);
if (true === $break) {
break;
}
}
}
/**
* @param RuleAction $ruleAction
* @param array $transaction
@@ -482,92 +504,70 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* Return true if the rule is fired (the collection is larger than zero).
*
* @param Rule $rule
* @param array $group
*
* @return bool
* @throws FireflyException
*/
private function fireNonStrictRule(Rule $rule): bool
private function processTransactionGroup(Rule $rule, array $group): void
{
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));
return $collection->count() > 0;
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);
}
}
/**
* @param RuleGroup $group
* @param Rule $rule
* @param array $transaction
*
* @return void
* @throws FireflyException
*/
private function fireGroup(RuleGroup $group): void
private function processTransactionJournal(Rule $rule, array $transaction): void
{
$all = false;
Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $group->rules->count()));
/** @var Rule $rule */
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;
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 */
foreach ($actions as $ruleAction) {
if (false === $ruleAction->active) {
continue;
}
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));
return;
$break = $this->processRuleAction($ruleAction, $transaction);
if (true === $break) {
break;
}
}
}
/**
* Return the number of changed transactions from the previous "fire" action.
* @param array $array
*
* @return int
* @return Carbon
*/
public function getResults(): int
private function setDateFromJournalTrigger(array $array): Carbon
{
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);
Log::debug('Now in setDateFromJournalTrigger()');
$journalId = 0;
foreach ($array as $triggerName => $values) {
if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
$journalId = (int)trim(($values[0] ?? '"0"'), '"'); // follows format "123".
Log::debug(sprintf('Found journal ID #%d', $journalId));
}
}
}
if (0 !== $journalId) {
$repository = app(JournalRepositoryInterface::class);
$repository->setUser($this->user);
$journal = $repository->find($journalId);
if (null !== $journal) {
$date = $journal->date;
Log::debug(sprintf('Found journal #%d with date %s.', $journal->id, $journal->date->format('Y-m-d')));
/**
* @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);
return $date;
}
}
}
Log::debug('Found no journal, return default date.');
/**
* @param bool $refreshTriggers
*/
public function setRefreshTriggers(bool $refreshTriggers): void
{
$this->refreshTriggers = $refreshTriggers;
return today(config('app.timezone'));
}
}