firefly-iii/app/TransactionRules/TransactionMatcher.php

347 lines
11 KiB
PHP
Raw Normal View History

<?php
/**
* TransactionMatcher.php
2020-02-16 06:57:05 -06:00
* Copyright (c) 2019 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.
2017-10-21 01:40:00 -05:00
*
* This program is distributed in the hope that it will be useful,
2017-10-21 01:40:00 -05:00
* 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.
2017-10-21 01:40:00 -05:00
*
* 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/>.
*/
declare(strict_types=1);
2017-09-13 00:49:58 -05:00
namespace FireflyIII\TransactionRules;
2018-12-07 08:36:04 -06:00
use Carbon\Carbon;
2019-08-17 03:47:29 -05:00
use FireflyIII\Exceptions\FireflyException;
2019-05-31 06:35:33 -05:00
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Rule;
2018-04-14 16:06:27 -05:00
use FireflyIII\Models\RuleTrigger;
use FireflyIII\Models\TransactionType;
2019-05-31 06:35:33 -05:00
use FireflyIII\User;
use Illuminate\Support\Collection;
use Log;
/**
2016-02-17 10:32:02 -06:00
* Class TransactionMatcher is used to find a list of
2017-11-15 05:25:49 -06:00
* transaction matching a set of triggers.
*/
class TransactionMatcher
{
2018-12-07 08:36:04 -06:00
/** @var Collection Asset accounts to search in. */
private $accounts;
/** @var Carbon Start date of the matched transactions */
private $endDate;
2018-04-14 16:06:27 -05:00
/** @var string */
private $exactAmount;
/** @var string */
private $maxAmount;
/** @var string */
private $minAmount;
2017-11-25 08:20:53 -06:00
/** @var Rule The rule to apply */
private $rule;
2018-12-07 08:36:04 -06:00
/** @var int Maximum number of transaction to search in (for performance reasons) */
private $searchLimit;
/** @var Carbon Start date of the matched transactions */
private $startDate;
2018-09-01 13:45:05 -05:00
/** @var bool */
private $strict;
2017-11-25 08:20:53 -06:00
/** @var array Types that can be matched using this matcher */
private $transactionTypes = [TransactionType::DEPOSIT, TransactionType::WITHDRAWAL, TransactionType::TRANSFER];
2018-12-07 08:36:04 -06:00
/** @var int Max number of results */
private $triggeredLimit;
2016-02-17 10:32:02 -06:00
/** @var array List of triggers to match */
private $triggers = [];
2018-12-07 08:36:04 -06:00
/**
* TransactionMatcher constructor.
*/
public function __construct()
{
$this->strict = false;
$this->accounts = new Collection;
2018-12-07 08:36:04 -06:00
Log::debug('Created new transaction matcher');
}
2016-02-17 23:54:50 -06:00
/**
* This method will search the user's transaction journal (with an upper limit of $range) for
* transaction journals matching the given rule. This is accomplished by trying to fire these
2016-02-17 23:54:50 -06:00
* triggers onto each transaction journal until enough matches are found ($limit).
2016-02-17 10:32:02 -06:00
*
2019-05-31 06:35:33 -05:00
* @return array
2019-08-17 03:47:29 -05:00
* @throws FireflyException
*/
2019-05-31 06:35:33 -05:00
public function findTransactionsByRule(): array
2016-02-17 10:32:02 -06:00
{
2018-12-07 08:36:04 -06:00
Log::debug('Now in findTransactionsByRule()');
if (0 === count($this->rule->ruleTriggers)) {
2018-12-07 08:36:04 -06:00
Log::error('Rule has no triggers!');
2019-05-31 06:35:33 -05:00
return [];
2016-02-17 23:54:50 -06:00
}
2016-02-17 10:32:02 -06:00
2018-12-07 08:36:04 -06:00
// Variables used within the loop.
2018-09-01 13:45:05 -05:00
/** @var Processor $processor */
$processor = app(Processor::class);
$processor->make($this->rule, false);
$result = $this->runProcessor($processor);
2016-02-17 10:32:02 -06:00
// If the list of matchingTransactions is larger than the maximum number of results
// (e.g. if a large percentage of the transactions match), truncate the list
2019-05-31 06:35:33 -05:00
$result = array_slice($result, 0, $this->searchLimit);
return $result;
}
/**
* This method will search the user's transaction journal (with an upper limit of $range) for
* transaction journals matching the given $triggers. This is accomplished by trying to fire these
* triggers onto each transaction journal until enough matches are found ($limit).
*
2019-08-14 13:23:11 -05:00
* @return array
2019-08-17 03:47:29 -05:00
* @throws FireflyException
*/
2019-08-14 13:23:11 -05:00
public function findTransactionsByTriggers(): array
{
if (0 === count($this->triggers)) {
return new Collection;
}
// Variables used within the loop
/** @var Processor $processor */
$processor = app(Processor::class);
$processor->makeFromStringArray($this->triggers);
$processor->setStrict($this->strict);
$result = $this->runProcessor($processor);
2016-02-17 10:32:02 -06:00
// If the list of matchingTransactions is larger than the maximum number of results
// (e.g. if a large percentage of the transactions match), truncate the list
2019-08-14 13:23:11 -05:00
return array_slice($result, 0, $this->searchLimit);
}
2016-02-17 10:32:02 -06:00
/**
2018-12-07 08:36:04 -06:00
* Get triggers
2017-12-22 11:32:43 -06:00
*
2018-12-07 08:36:04 -06:00
* @return array
*/
2018-12-07 08:36:04 -06:00
public function getTriggers(): array
2016-02-17 10:32:02 -06:00
{
2018-12-07 08:36:04 -06:00
return $this->triggers;
}
/**
2018-12-07 08:36:04 -06:00
* Set triggers
2017-11-25 08:20:53 -06:00
*
2018-12-07 08:36:04 -06:00
* @param array $triggers
2016-02-17 23:24:39 -06:00
*
* @return TransactionMatcher
*/
2018-12-07 08:36:04 -06:00
public function setTriggers(array $triggers): TransactionMatcher
2016-02-17 10:32:02 -06:00
{
2018-12-07 08:36:04 -06:00
$this->triggers = $triggers;
2016-02-17 23:24:39 -06:00
return $this;
}
2016-02-17 10:32:02 -06:00
/**
2018-12-07 08:36:04 -06:00
* @return bool
*/
2018-12-07 08:36:04 -06:00
public function isStrict(): bool
2016-02-17 10:32:02 -06:00
{
2018-12-07 08:36:04 -06:00
return $this->strict;
2016-02-17 13:25:54 -06:00
}
2016-02-17 10:32:02 -06:00
2016-02-17 13:25:54 -06:00
/**
2018-12-07 08:36:04 -06:00
* @param bool $strict
2016-02-17 13:25:54 -06:00
*/
2018-12-07 08:36:04 -06:00
public function setStrict(bool $strict): void
2016-02-17 13:25:54 -06:00
{
2018-12-07 08:36:04 -06:00
$this->strict = $strict;
}
2016-02-17 23:24:39 -06:00
2018-12-07 08:36:04 -06:00
/**
* @param Collection $accounts
*/
public function setAccounts(Collection $accounts): void
{
$this->accounts = $accounts;
}
2016-02-17 10:32:02 -06:00
/**
2018-12-07 08:36:04 -06:00
* @param Carbon|null $endDate
*/
2018-12-07 08:36:04 -06:00
public function setEndDate(Carbon $endDate = null): void
2016-02-17 10:32:02 -06:00
{
2018-12-07 08:36:04 -06:00
$this->endDate = $endDate;
}
/**
2018-12-07 08:36:04 -06:00
* Set rule
2016-02-17 23:24:39 -06:00
*
2018-12-07 08:36:04 -06:00
* @param Rule $rule
*/
2018-12-07 08:36:04 -06:00
public function setRule(Rule $rule): void
2016-02-17 10:32:02 -06:00
{
2018-12-07 08:36:04 -06:00
$this->rule = $rule;
2016-02-17 10:32:02 -06:00
}
2018-09-01 13:45:05 -05:00
/**
2018-12-07 08:36:04 -06:00
* @param int $searchLimit
2018-09-01 13:45:05 -05:00
*/
2018-12-07 08:36:04 -06:00
public function setSearchLimit(int $searchLimit): void
2018-09-01 13:45:05 -05:00
{
2018-12-07 08:36:04 -06:00
$this->searchLimit = $searchLimit;
2018-09-01 13:45:05 -05:00
}
/**
2018-12-07 08:36:04 -06:00
* @param Carbon|null $startDate
2018-09-01 13:45:05 -05:00
*/
2018-12-07 08:36:04 -06:00
public function setStartDate(Carbon $startDate = null): void
2018-09-01 13:45:05 -05:00
{
2018-12-07 08:36:04 -06:00
$this->startDate = $startDate;
2018-09-01 13:45:05 -05:00
}
/**
2018-12-07 08:36:04 -06:00
* @param int $triggeredLimit
*/
2018-12-07 08:36:04 -06:00
public function setTriggeredLimit(int $triggeredLimit): void
{
2018-12-07 08:36:04 -06:00
$this->triggeredLimit = $triggeredLimit;
}
2018-04-14 16:06:27 -05:00
/**
*
*/
private function readTriggers(): void
{
$valid = ['amount_less', 'amount_more', 'amount_exactly'];
if (null !== $this->rule) {
$allTriggers = $this->rule->ruleTriggers()->whereIn('trigger_type', $valid)->get();
/** @var RuleTrigger $trigger */
foreach ($allTriggers as $trigger) {
2018-08-06 12:14:30 -05:00
if ('amount_less' === $trigger->trigger_type) {
2018-04-14 16:06:27 -05:00
$this->maxAmount = $trigger->trigger_value;
2018-04-14 16:09:24 -05:00
Log::debug(sprintf('Set max amount to be %s', $trigger->trigger_value));
2018-04-14 16:06:27 -05:00
}
2018-08-06 12:14:30 -05:00
if ('amount_more' === $trigger->trigger_type) {
2018-04-14 16:06:27 -05:00
$this->minAmount = $trigger->trigger_value;
2018-04-14 16:09:24 -05:00
Log::debug(sprintf('Set min amount to be %s', $trigger->trigger_value));
2018-04-14 16:06:27 -05:00
}
2018-08-06 12:14:30 -05:00
if ('amount_exactly' === $trigger->trigger_type) {
2018-04-14 16:06:27 -05:00
$this->exactAmount = $trigger->trigger_value;
2018-04-14 16:09:24 -05:00
Log::debug(sprintf('Set exact amount to be %s', $trigger->trigger_value));
2018-04-14 16:06:27 -05:00
}
}
}
}
/**
2017-11-25 08:20:53 -06:00
* Run the processor.
*
* @param Processor $processor
*
2019-08-14 13:23:11 -05:00
* @return array
*/
2019-05-31 06:35:33 -05:00
private function runProcessor(Processor $processor): array
{
2018-12-07 08:36:04 -06:00
Log::debug('Now in runprocessor()');
2018-04-14 16:06:27 -05:00
// since we have a rule in $this->rule, we can add some of the triggers
// to the Journal Collector.
// Firefly III will then have to search through less transactions.
$this->readTriggers();
// Start a loop to fetch batches of transactions. The loop will finish if:
// - all transactions have been fetched from the database
// - the maximum number of transactions to return has been found
// - the maximum number of transactions to search in have been searched
2019-08-14 13:23:11 -05:00
$pageSize = $this->searchLimit;
$processed = 0;
$page = 1;
$totalResult = [];
2018-12-07 08:36:04 -06:00
Log::debug(sprintf('Search limit is %d, triggered limit is %d, so page size is %d', $this->searchLimit, $this->triggeredLimit, $pageSize));
do {
2018-12-07 08:36:04 -06:00
Log::debug('Start of do-loop');
// Fetch a batch of transactions from the database
2019-05-31 06:35:33 -05:00
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
/** @var User $user */
$user = auth()->user();
$collector->setUser($user);
2018-12-07 08:36:04 -06:00
// limit asset accounts:
if ($this->accounts->count() > 0) {
$collector->setAccounts($this->accounts);
}
if (null !== $this->startDate && null !== $this->endDate) {
2018-12-07 08:36:04 -06:00
$collector->setRange($this->startDate, $this->endDate);
}
$collector->setLimit($pageSize)->setPage($page)->setTypes($this->transactionTypes);
2018-04-14 16:06:27 -05:00
if (null !== $this->maxAmount) {
2018-04-14 16:09:24 -05:00
Log::debug(sprintf('Amount must be less than %s', $this->maxAmount));
2018-04-14 16:06:27 -05:00
$collector->amountLess($this->maxAmount);
}
if (null !== $this->minAmount) {
2018-04-14 16:09:24 -05:00
Log::debug(sprintf('Amount must be more than %s', $this->minAmount));
2018-04-14 16:06:27 -05:00
$collector->amountMore($this->minAmount);
}
if (null !== $this->exactAmount) {
2018-04-14 16:09:24 -05:00
Log::debug(sprintf('Amount must be exactly %s', $this->exactAmount));
2018-04-14 16:06:27 -05:00
$collector->amountIs($this->exactAmount);
}
2018-04-14 02:59:04 -05:00
2019-05-31 06:35:33 -05:00
$journals = $collector->getExtractedJournals();
Log::debug(sprintf('Found %d transaction journals to check. ', count($journals)));
// Filter transactions that match the given triggers.
2019-05-31 06:35:33 -05:00
$filtered = [];
/** @var array $journal */
foreach ($journals as $journal) {
$result = $processor->handleJournalArray($journal);
if ($result) {
$filtered[] = $journal;
}
2019-05-31 06:35:33 -05:00
}
2019-05-31 06:35:33 -05:00
Log::debug(sprintf('Found %d journals that match.', count($filtered)));
// merge:
$totalResult = $totalResult + $filtered;
Log::debug(sprintf('Total count is now %d', count($totalResult)));
// Update counters
2017-11-15 05:25:49 -06:00
++$page;
2019-05-31 06:35:33 -05:00
$processed += count($journals);
Log::debug(sprintf('Page is now %d, processed is %d', $page, $processed));
// Check for conditions to finish the loop
2019-05-31 06:35:33 -05:00
$reachedEndOfList = count($journals) < 1;
$foundEnough = count($totalResult) >= $this->triggeredLimit;
2018-12-07 08:36:04 -06:00
$searchedEnough = ($processed >= $this->searchLimit);
Log::debug(sprintf('reachedEndOfList: %s', var_export($reachedEndOfList, true)));
Log::debug(sprintf('foundEnough: %s', var_export($foundEnough, true)));
Log::debug(sprintf('searchedEnough: %s', var_export($searchedEnough, true)));
} while (!$reachedEndOfList && !$foundEnough && !$searchedEnough);
2018-12-07 08:36:04 -06:00
Log::debug('End of do-loop');
return $totalResult;
}
}