chore: reformat code.

This commit is contained in:
James Cole
2023-06-21 12:34:58 +02:00
parent 8d87abde64
commit 3dcb35710b
799 changed files with 23319 additions and 22173 deletions

View File

@@ -32,7 +32,7 @@ interface ActionInterface
* Execute the action on an array. Returns "true" if the action was a success and the action
* was applied. Returns false if otherwise.
*
* @param array $journal
* @param array $journal
*
* @return bool
*/

View File

@@ -41,7 +41,7 @@ class AddTag implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -38,7 +38,7 @@ class AppendDescription implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -40,7 +40,7 @@ class AppendDescriptionToNotes implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -39,7 +39,7 @@ class AppendNotes implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -43,7 +43,7 @@ class AppendNotesToDescription implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -39,7 +39,7 @@ class ClearBudget implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -39,7 +39,7 @@ class ClearCategory implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -39,7 +39,7 @@ class ClearNotes implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -48,7 +48,7 @@ class ConvertToDeposit implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{
@@ -86,7 +86,7 @@ class ConvertToDeposit implements ActionInterface
try {
$res = $this->convertWithdrawalArray($object);
} catch (JsonException|FireflyException $e) {
} catch (JsonException | FireflyException $e) {
Log::debug('Could not convert withdrawal to deposit.');
Log::error($e->getMessage());
return false;
@@ -101,7 +101,7 @@ class ConvertToDeposit implements ActionInterface
try {
$res = $this->convertTransferArray($object);
} catch (JsonException|FireflyException $e) {
} catch (JsonException | FireflyException $e) {
Log::debug('Could not convert transfer to deposit.');
Log::error($e->getMessage());
return false;
@@ -114,65 +114,11 @@ 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.
*
* @param TransactionJournal $journal
* @param TransactionJournal $journal
*
* @return bool
* @throws FireflyException
@@ -229,7 +175,7 @@ class ConvertToDeposit implements ActionInterface
}
/**
* @param TransactionJournal $journal
* @param TransactionJournal $journal
* @return Account
* @throws FireflyException
*/
@@ -244,7 +190,7 @@ class ConvertToDeposit implements ActionInterface
}
/**
* @param TransactionJournal $journal
* @param TransactionJournal $journal
* @return Account
* @throws FireflyException
*/
@@ -257,4 +203,58 @@ class ConvertToDeposit implements ActionInterface
}
return $sourceTransaction->account;
}
/**
* 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;
}
}

View File

@@ -45,7 +45,7 @@ class ConvertToTransfer implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{
@@ -140,45 +140,33 @@ class ConvertToTransfer implements ActionInterface
}
/**
* A deposit is from Revenue to Asset.
* We replace the Revenue with another asset.
*
* @param TransactionJournal $journal
* @param Account $opposing
*
* @return bool
* @throws FireflyException
* @param int $journalId
* @return string
*/
private function convertDepositArray(TransactionJournal $journal, Account $opposing): bool
private function getSourceType(int $journalId): string
{
$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;
/** @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;
}
// 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 int $journalId
* @return string
*/
private function getDestinationType(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;
}
/**
@@ -186,8 +174,8 @@ class ConvertToTransfer implements ActionInterface
* We replace the Expense with another asset.
* So this replaces the destination
*
* @param TransactionJournal $journal
* @param Account $opposing
* @param TransactionJournal $journal
* @param Account $opposing
*
* @return bool
* @throws FireflyException
@@ -225,37 +213,7 @@ class ConvertToTransfer implements ActionInterface
}
/**
* @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;
}
/**
* @param int $journalId
* @return string
*/
private function getDestinationType(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 TransactionJournal $journal
* @param TransactionJournal $journal
* @return Account
* @throws FireflyException
*/
@@ -270,17 +228,59 @@ class ConvertToTransfer implements ActionInterface
}
/**
* @param int $journalId
* @return string
* 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 getSourceType(int $journalId): string
private function convertDepositArray(TransactionJournal $journal, Account $opposing): bool
{
/** @var TransactionJournal $journal */
$journal = TransactionJournal::find($journalId);
if (null === $journal) {
Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId));
return '';
$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;
}
return (string)$journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type;
// 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 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

@@ -48,7 +48,7 @@ class ConvertToWithdrawal implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{
@@ -84,7 +84,7 @@ class ConvertToWithdrawal implements ActionInterface
Log::debug('Going to transform a deposit to a withdrawal.');
try {
$res = $this->convertDepositArray($object);
} catch (JsonException|FireflyException $e) {
} catch (JsonException | FireflyException $e) {
Log::debug('Could not convert transfer to deposit.');
Log::error($e->getMessage());
return false;
@@ -98,7 +98,7 @@ class ConvertToWithdrawal implements ActionInterface
try {
$res = $this->convertTransferArray($object);
} catch (JsonException|FireflyException $e) {
} catch (JsonException | FireflyException $e) {
Log::debug('Could not convert transfer to deposit.');
Log::error($e->getMessage());
return false;
@@ -112,7 +112,7 @@ class ConvertToWithdrawal implements ActionInterface
}
/**
* @param TransactionJournal $journal
* @param TransactionJournal $journal
* @return bool
* @throws FireflyException
* @throws JsonException
@@ -165,11 +165,41 @@ 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
* @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;
}
/**
* 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
@@ -216,34 +246,4 @@ class ConvertToWithdrawal implements ActionInterface
return true;
}
/**
* @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;
}
/**
* @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

@@ -41,7 +41,7 @@ class DeleteTransaction implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -43,7 +43,7 @@ class LinkToBill implements ActionInterface
* TriggerInterface constructor.
*
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -41,7 +41,7 @@ class MoveDescriptionToNotes implements ActionInterface
* TriggerInterface constructor.
*
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -47,7 +47,7 @@ class MoveNotesToDescription implements ActionInterface
* TriggerInterface constructor.
*
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -38,7 +38,7 @@ class PrependDescription implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -39,7 +39,7 @@ class PrependNotes implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -39,7 +39,7 @@ class RemoveAllTags implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -40,7 +40,7 @@ class RemoveTag implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -41,7 +41,7 @@ class SetBudget implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -41,7 +41,7 @@ class SetCategory implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -39,7 +39,7 @@ class SetDescription implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -45,7 +45,7 @@ class SetDestinationAccount implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{
@@ -133,7 +133,7 @@ class SetDestinationAccount implements ActionInterface
}
/**
* @param string $type
* @param string $type
*
* @return Account|null
*/

View File

@@ -39,7 +39,7 @@ class SetNotes implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{

View File

@@ -45,7 +45,7 @@ class SetSourceAccount implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{
@@ -128,7 +128,7 @@ class SetSourceAccount implements ActionInterface
}
/**
* @param string $type
* @param string $type
*
* @return Account|null
*/

View File

@@ -44,7 +44,7 @@ class UpdatePiggybank implements ActionInterface
/**
* TriggerInterface constructor.
*
* @param RuleAction $action
* @param RuleAction $action
*/
public function __construct(RuleAction $action)
{
@@ -135,9 +135,56 @@ class UpdatePiggybank implements ActionInterface
}
/**
* @param PiggyBank $piggyBank
* @param TransactionJournal $journal
* @param string $amount
* @param User $user
*
* @return PiggyBank|null
*/
private function findPiggyBank(User $user): ?PiggyBank
{
return $user->piggyBanks()->where('piggy_banks.name', $this->action->action_value)->first();
}
/**
* @param PiggyBank $piggyBank
* @param TransactionJournal $journal
* @param string $amount
* @return void
*/
private function removeAmount(PiggyBank $piggyBank, TransactionJournal $journal, string $amount): void
{
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUser($journal->user);
// how much can we remove from this piggy bank?
$toRemove = $repository->getCurrentAmount($piggyBank);
Log::debug(sprintf('Amount is %s, max to remove is %s', $amount, $toRemove));
// if $amount is bigger than $toRemove, shrink it.
$amount = -1 === bccomp($amount, $toRemove) ? $amount : $toRemove;
Log::debug(sprintf('Amount is now %s', $amount));
// if amount is zero, stop.
if (0 === bccomp('0', $amount)) {
app('log')->warning('Amount left is zero, stop.');
return;
}
// make sure we can remove amount:
if (false === $repository->canRemoveAmount($piggyBank, $amount)) {
app('log')->warning(sprintf('Cannot remove %s from piggy bank.', $amount));
return;
}
Log::debug(sprintf('Will now remove %s from piggy bank.', $amount));
$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
@@ -176,51 +223,4 @@ class UpdatePiggybank implements ActionInterface
$repository->addAmount($piggyBank, $amount, $journal);
}
/**
* @param User $user
*
* @return PiggyBank|null
*/
private function findPiggyBank(User $user): ?PiggyBank
{
return $user->piggyBanks()->where('piggy_banks.name', $this->action->action_value)->first();
}
/**
* @param PiggyBank $piggyBank
* @param TransactionJournal $journal
* @param string $amount
* @return void
*/
private function removeAmount(PiggyBank $piggyBank, TransactionJournal $journal, string $amount): void
{
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUser($journal->user);
// how much can we remove from this piggy bank?
$toRemove = $repository->getCurrentAmount($piggyBank);
Log::debug(sprintf('Amount is %s, max to remove is %s', $amount, $toRemove));
// if $amount is bigger than $toRemove, shrink it.
$amount = -1 === bccomp($amount, $toRemove) ? $amount : $toRemove;
Log::debug(sprintf('Amount is now %s', $amount));
// if amount is zero, stop.
if (0 === bccomp('0', $amount)) {
app('log')->warning('Amount left is zero, stop.');
return;
}
// make sure we can remove amount:
if (false === $repository->canRemoveAmount($piggyBank, $amount)) {
app('log')->warning(sprintf('Cannot remove %s from piggy bank.', $amount));
return;
}
Log::debug(sprintf('Will now remove %s from piggy bank.', $amount));
$repository->removeAmount($piggyBank, $amount, $journal);
}
}

View File

@@ -34,7 +34,7 @@ interface RuleEngineInterface
/**
* Add operators added to each search by the rule engine.
*
* @param array $operator
* @param array $operator
*/
public function addOperator(array $operator): void;
@@ -56,7 +56,7 @@ interface RuleEngineInterface
public function getResults(): int;
/**
* @param bool $refreshTriggers
* @param bool $refreshTriggers
* @return void
*/
public function setRefreshTriggers(bool $refreshTriggers): void;
@@ -64,19 +64,19 @@ interface RuleEngineInterface
/**
* Add entire rule groups for the engine to execute.
*
* @param Collection $ruleGroups
* @param Collection $ruleGroups
*/
public function setRuleGroups(Collection $ruleGroups): void;
/**
* Add rules for the engine to execute.
*
* @param Collection $rules
* @param Collection $rules
*/
public function setRules(Collection $rules): void;
/**
* @param User $user
* @param User $user
*/
public function setUser(User $user): void;
}

View File

@@ -91,79 +91,129 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* @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!');
}
/**
* Return the number of changed transactions from the previous "fire" action.
* Finds the transactions a strict rule will execute on.
*
* @return int
* @param Rule $rule
*
* @return Collection
*/
public function getResults(): int
private function findStrictRule(Rule $rule): Collection
{
return count($this->resultCount);
}
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;
}
/**
* @param bool $refreshTriggers
*/
public function setRefreshTriggers(bool $refreshTriggers): void
{
$this->refreshTriggers = $refreshTriggers;
}
/** @var RuleTrigger $ruleTrigger */
foreach ($triggers as $ruleTrigger) {
if (false === $ruleTrigger->active) {
continue;
}
/**
* @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 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();
}
/**
* @inheritDoc
* 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
*/
public function setRules(Collection $rules): void
private function hasSpecificJournalTrigger(array $array): bool
{
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('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 array $array
*
* @return Carbon
*/
private function setDateFromJournalTrigger(array $array): Carbon
{
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')));
return $date;
}
}
Log::debug('Found no journal, return default date.');
return today(config('app.timezone'));
}
/**
@@ -176,7 +226,7 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* @param Rule $rule
* @param Rule $rule
*
* @return Collection
*/
@@ -259,118 +309,39 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* 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
* @inheritDoc
* @throws FireflyException
*/
private function fireGroup(RuleGroup $group): void
public function fire(): 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;
}
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));
$this->resultCount = [];
Log::debug('SearchRuleEngine::fire()!');
return;
// 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);
}
}
}
/**
* 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;
Log::debug('SearchRuleEngine:: done processing all rules!');
}
/**
* Returns true if the rule has been triggered.
*
* @param Rule $rule
* @param Rule $rule
*
* @return bool
* @throws FireflyException
@@ -396,7 +367,7 @@ class SearchRuleEngine implements RuleEngineInterface
/**
* Return true if the rule is fired (the collection is larger than zero).
*
* @param Rule $rule
* @param Rule $rule
*
* @return bool
* @throws FireflyException
@@ -421,38 +392,8 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* 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
* @param Rule $rule
* @param Collection $collection
*
* @throws FireflyException
*/
@@ -466,8 +407,45 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* @param RuleAction $ruleAction
* @param array $transaction
* @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
*
* @return bool
* @throws FireflyException
@@ -504,70 +482,92 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
* @param Rule $rule
* @param array $group
* Return true if the rule is fired (the collection is larger than zero).
*
* @param Rule $rule
*
* @return bool
* @throws FireflyException
*/
private function processTransactionGroup(Rule $rule, array $group): void
private function fireNonStrictRule(Rule $rule): bool
{
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);
}
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;
}
/**
* @param Rule $rule
* @param array $transaction
* @param RuleGroup $group
*
* @return void
* @throws FireflyException
*/
private function processTransactionJournal(Rule $rule, array $transaction): void
private function fireGroup(RuleGroup $group): 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;
$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;
}
$break = $this->processRuleAction($ruleAction, $transaction);
if (true === $break) {
break;
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;
}
}
}
/**
* @param array $array
* Return the number of changed transactions from the previous "fire" action.
*
* @return Carbon
* @return int
*/
private function setDateFromJournalTrigger(array $array): Carbon
public function getResults(): int
{
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));
return count($this->resultCount);
}
/**
* @param bool $refreshTriggers
*/
public function setRefreshTriggers(bool $refreshTriggers): void
{
$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'));
}
}

View File

@@ -45,7 +45,7 @@ class ActionFactory
* with value "Groceries" this method will return a corresponding SetCategory object preset
* to "Groceries". Any transaction journal then fed to this object will have its category changed.
*
* @param RuleAction $action
* @param RuleAction $action
*
* @return ActionInterface
*
@@ -64,7 +64,7 @@ class ActionFactory
* that will match the given action type (ie. "change_category") to the matching class name
* (SetCategory) using the configuration (firefly.php).
*
* @param string $actionType
* @param string $actionType
*
* @return string
*
@@ -75,12 +75,12 @@ class ActionFactory
$actionTypes = self::getActionTypes();
if (!array_key_exists($actionType, $actionTypes)) {
throw new FireflyException('No such action exists ("'.e($actionType).'").');
throw new FireflyException('No such action exists ("' . e($actionType) . '").');
}
$class = $actionTypes[$actionType];
if (!class_exists($class)) {
throw new FireflyException('Could not instantiate class for rule action type "'.e($actionType).'" ('.e($class).').');
throw new FireflyException('Could not instantiate class for rule action type "' . e($actionType) . '" (' . e($class) . ').');
}
return $class;