Skip to content

Firefly III: a personal finances manager

Finish up rule groups API

James Cole9a2e5c36a1bf
diff --git a/app/Api/V1/Controllers/RuleGroupController.php b/app/Api/V1/Controllers/RuleGroupController.php
index f36bfebb3a..1f1f5a15dd 100644
--- a/app/Api/V1/Controllers/RuleGroupController.php
+++ b/app/Api/V1/Controllers/RuleGroupController.php
@@ -23,19 +23,31 @@ declare(strict_types=1);
namespace FireflyIII\Api\V1\Controllers;
+use Carbon\Carbon;
use FireflyIII\Api\V1\Requests\RuleGroupRequest;
+use FireflyIII\Exceptions\FireflyException;
+use FireflyIII\Jobs\ExecuteRuleOnExistingTransactions;
+use FireflyIII\Models\AccountType;
+use FireflyIII\Models\Rule;
use FireflyIII\Models\RuleGroup;
+use FireflyIII\Repositories\Account\AccountRepositoryInterface;
+use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
+use FireflyIII\TransactionRules\TransactionMatcher;
use FireflyIII\Transformers\RuleGroupTransformer;
+use FireflyIII\Transformers\RuleTransformer;
+use FireflyIII\Transformers\TransactionTransformer;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
+use Illuminate\Support\Collection;
use League\Fractal\Manager;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Resource\Collection as FractalCollection;
use League\Fractal\Resource\Item;
use League\Fractal\Serializer\JsonApiSerializer;
+use Log;
/**
@@ -43,6 +55,8 @@ use League\Fractal\Serializer\JsonApiSerializer;
*/
class RuleGroupController extends Controller
{
+ /** @var AccountRepositoryInterface Account repository */
+ private $accountRepository;
/** @var RuleGroupRepositoryInterface The rule group repository */
private $ruleGroupRepository;
@@ -60,6 +74,9 @@ class RuleGroupController extends Controller
$this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
$this->ruleGroupRepository->setUser($user);
+ $this->accountRepository = app(AccountRepositoryInterface::class);
+ $this->accountRepository->setUser($user);
+
return $next($request);
}
);
@@ -112,6 +129,39 @@ class RuleGroupController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json');
}
+ /**
+ * @param Request $request
+ * @param RuleGroup $group
+ *
+ * @return JsonResponse
+ */
+ public function rules(Request $request, RuleGroup $group): JsonResponse
+ {
+ // create some objects:
+ $manager = new Manager;
+ $baseUrl = $request->getSchemeAndHttpHost() . '/api/v1';
+
+ // types to get, page size:
+ $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
+
+ // get list of budgets. Count it and split it.
+ $collection = $this->ruleGroupRepository->getRules($group);
+ $count = $collection->count();
+ $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
+
+ // make paginator:
+ $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page'));
+ $paginator->setPath(route('api.v1.rule_groups.rules', [$group->id]) . $this->buildParams());
+
+ // present to user.
+ $manager->setSerializer(new JsonApiSerializer($baseUrl));
+ $resource = new FractalCollection($rules, new RuleTransformer($this->parameters), 'rules');
+ $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
+
+ return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json');
+
+ }
+
/**
* List single resource.
*
@@ -156,6 +206,131 @@ class RuleGroupController extends Controller
}
+ /**
+ * @param Request $request
+ * @param RuleGroup $group
+ *
+ * @return JsonResponse
+ * @throws FireflyException
+ */
+ public function testGroup(Request $request, RuleGroup $group): JsonResponse
+ {
+ Log::debug('Now in testGroup()');
+ /** @var Collection $rules */
+ $rules = $this->ruleGroupRepository->getActiveRules($group);
+ if (0 === $rules->count()) {
+ throw new FireflyException('No rules in this rule group.');
+ }
+ $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data;
+ $page = 0 === (int)$request->query('page') ? 1 : (int)$request->query('page');
+ $startDate = null === $request->query('start_date') ? null : Carbon::createFromFormat('Y-m-d', $request->query('start_date'));
+ $endDate = null === $request->query('end_date') ? null : Carbon::createFromFormat('Y-m-d', $request->query('end_date'));
+ $searchLimit = 0 === (int)$request->query('search_limit') ? (int)config('firefly.test-triggers.limit') : (int)$request->query('search_limit');
+ $triggerLimit = 0 === (int)$request->query('triggered_limit') ? (int)config('firefly.test-triggers.range') : (int)$request->query('triggered_limit');
+ $accountList = '' === (string)$request->query('accounts') ? [] : explode(',', $request->query('accounts'));
+ $accounts = new Collection;
+
+ foreach ($accountList as $accountId) {
+ Log::debug(sprintf('Searching for asset account with id "%s"', $accountId));
+ $account = $this->accountRepository->findNull((int)$accountId);
+ if (null !== $account && AccountType::ASSET === $account->accountType->type) {
+ Log::debug(sprintf('Found account #%d ("%s") and its an asset account', $account->id, $account->name));
+ $accounts->push($account);
+ }
+ if (null === $account) {
+ Log::debug(sprintf('No asset account with id "%s"', $accountId));
+ }
+ }
+
+ $matchingTransactions = new Collection;
+ Log::debug(sprintf('Going to test %d rules', $rules->count()));
+ /** @var Rule $rule */
+ foreach ($rules as $rule) {
+ Log::debug(sprintf('Now testing rule #%d, "%s"', $rule->id, $rule->title));
+ /** @var TransactionMatcher $matcher */
+ $matcher = app(TransactionMatcher::class);
+ // set all parameters:
+ $matcher->setRule($rule);
+ $matcher->setStartDate($startDate);
+ $matcher->setEndDate($endDate);
+ $matcher->setSearchLimit($searchLimit);
+ $matcher->setTriggeredLimit($triggerLimit);
+ $matcher->setAccounts($accounts);
+
+ $result = $matcher->findTransactionsByRule();
+ $matchingTransactions = $result->merge($matchingTransactions);
+ }
+ $matchingTransactions = $matchingTransactions->unique('id');
+
+ // make paginator out of results.
+ $count = $matchingTransactions->count();
+ $transactions = $matchingTransactions->slice(($page - 1) * $pageSize, $pageSize);
+ // make paginator:
+ $paginator = new LengthAwarePaginator($transactions, $count, $pageSize, $this->parameters->get('page'));
+ $paginator->setPath(route('api.v1.rule_groups.test', [$group->id]) . $this->buildParams());
+
+ // resulting list is presented as JSON thing.
+ $manager = new Manager();
+ $baseUrl = $request->getSchemeAndHttpHost() . '/api/v1';
+ $manager->setSerializer(new JsonApiSerializer($baseUrl));
+ $repository = app(JournalRepositoryInterface::class);
+
+
+ $resource = new FractalCollection($matchingTransactions, new TransactionTransformer($this->parameters, $repository), 'transactions');
+ $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
+
+ return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json');
+ }
+
+ /**
+ * Execute the given rule group on a set of existing transactions.
+ *
+ * @param Request $request
+ * @param RuleGroup $group
+ *
+ * @return JsonResponse
+ */
+ public function triggerGroup(Request $request, RuleGroup $group): JsonResponse
+ {
+ // Get parameters specified by the user
+ /** @var User $user */
+ $user = auth()->user();
+ $startDate = new Carbon($request->get('start_date'));
+ $endDate = new Carbon($request->get('end_date'));
+ $accountList = '' === (string)$request->query('accounts') ? [] : explode(',', $request->query('accounts'));
+ $accounts = new Collection;
+
+ foreach ($accountList as $accountId) {
+ Log::debug(sprintf('Searching for asset account with id "%s"', $accountId));
+ $account = $this->accountRepository->findNull((int)$accountId);
+ if (null !== $account && AccountType::ASSET === $account->accountType->type) {
+ Log::debug(sprintf('Found account #%d ("%s") and its an asset account', $account->id, $account->name));
+ $accounts->push($account);
+ }
+ if (null === $account) {
+ Log::debug(sprintf('No asset account with id "%s"', $accountId));
+ }
+ }
+
+ /** @var Collection $rules */
+ $rules = $this->ruleGroupRepository->getActiveRules($group);
+ foreach ($rules as $rule) {
+ // Create a job to do the work asynchronously
+ $job = new ExecuteRuleOnExistingTransactions($rule);
+
+ // Apply parameters to the job
+ $job->setUser($user);
+ $job->setAccounts($accounts);
+ $job->setStartDate($startDate);
+ $job->setEndDate($endDate);
+
+ // Dispatch a new job to execute it in a queue
+ $this->dispatch($job);
+ }
+
+ return response()->json([], 204);
+ }
+
/**
* Update a rule group.
* TODO update order of rule group
diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php
index c257af8385..cecfff130b 100644
--- a/app/Repositories/RuleGroup/RuleGroupRepository.php
+++ b/app/Repositories/RuleGroup/RuleGroupRepository.php
@@ -118,6 +118,18 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface
return $user->ruleGroups()->where('rule_groups.active', 1)->orderBy('order', 'ASC')->get(['rule_groups.*']);
}
+ /**
+ * @param RuleGroup $group
+ *
+ * @return Collection
+ */
+ public function getActiveRules(RuleGroup $group): Collection
+ {
+ return $group->rules()
+ ->where('rules.active', 1)
+ ->get(['rules.*']);
+ }
+
/**
* @param RuleGroup $group
*
@@ -184,6 +196,17 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface
)->get();
}
+ /**
+ * @param RuleGroup $group
+ *
+ * @return Collection
+ */
+ public function getRules(RuleGroup $group): Collection
+ {
+ return $group->rules()
+ ->get(['rules.*']);
+ }
+
/**
* @param RuleGroup $ruleGroup
*
diff --git a/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php b/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php
index 8bd103ed1a..d21029d8c4 100644
--- a/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php
+++ b/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php
@@ -65,6 +65,20 @@ interface RuleGroupRepositoryInterface
*/
public function getActiveGroups(User $user): Collection;
+ /**
+ * @param RuleGroup $group
+ *
+ * @return Collection
+ */
+ public function getActiveRules(RuleGroup $group): Collection;
+
+ /**
+ * @param RuleGroup $group
+ *
+ * @return Collection
+ */
+ public function getRules(RuleGroup $group): Collection;
+
/**
* @param RuleGroup $group
*
diff --git a/app/TransactionRules/TransactionMatcher.php b/app/TransactionRules/TransactionMatcher.php
index a115f2095e..920642dd28 100644
--- a/app/TransactionRules/TransactionMatcher.php
+++ b/app/TransactionRules/TransactionMatcher.php
@@ -22,6 +22,8 @@ declare(strict_types=1);
namespace FireflyIII\TransactionRules;
+use Carbon\Carbon;
+use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Collector\TransactionCollectorInterface;
use FireflyIII\Helpers\Filter\InternalTransferFilter;
use FireflyIII\Models\Rule;
@@ -37,28 +39,41 @@ use Log;
*/
class TransactionMatcher
{
+ /** @var Collection Asset accounts to search in. */
+ private $accounts;
+ /** @var Carbon Start date of the matched transactions */
+ private $endDate;
/** @var string */
private $exactAmount;
- /** @var int Limit of matcher */
- private $limit = 10;
/** @var string */
private $maxAmount;
/** @var string */
private $minAmount;
- /** @var int Maximum number of transaction to search in (for performance reasons) * */
- private $range = 200;
/** @var Rule The rule to apply */
private $rule;
+ /** @var int Maximum number of transaction to search in (for performance reasons) */
+ private $searchLimit;
+ /** @var Carbon Start date of the matched transactions */
+ private $startDate;
/** @var bool */
private $strict;
/** @var array Types that can be matched using this matcher */
private $transactionTypes = [TransactionType::DEPOSIT, TransactionType::WITHDRAWAL, TransactionType::TRANSFER];
+ /** @var int Max number of results */
+ private $triggeredLimit;
/** @var array List of triggers to match */
private $triggers = [];
+ /**
+ * TransactionMatcher constructor.
+ */
public function __construct()
{
- $this->strict = false;
+ $this->strict = false;
+ $this->startDate = null;
+ $this->endDate = null;
+ $this->accounts = new Collection;
+ Log::debug('Created new transaction matcher');
}
/**
@@ -71,11 +86,13 @@ class TransactionMatcher
*/
public function findTransactionsByRule(): Collection
{
+ Log::debug('Now in findTransactionsByRule()');
if (0 === \count($this->rule->ruleTriggers)) {
+ Log::error('Rule has no triggers!');
return new Collection;
}
- // Variables used within the loop
+ // Variables used within the loop.
/** @var Processor $processor */
$processor = app(Processor::class);
$processor->make($this->rule, false);
@@ -83,7 +100,7 @@ class TransactionMatcher
// 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
- $result = $result->slice(0, $this->limit);
+ $result = $result->slice(0, $this->searchLimit);
return $result;
}
@@ -111,107 +128,99 @@ class TransactionMatcher
// 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
- $result = $result->slice(0, $this->limit);
+ $result = $result->slice(0, $this->searchLimit);
return $result;
}
/**
- * Return limit
+ * Get triggers
*
- * @return int
+ * @return array
*/
- public function getLimit(): int
+ public function getTriggers(): array
{
- return $this->limit;
+ return $this->triggers;
}
/**
- * Set limit
+ * Set triggers
*
- * @param int $limit
+ * @param array $triggers
*
* @return TransactionMatcher
*/
- public function setLimit(int $limit): TransactionMatcher
+ public function setTriggers(array $triggers): TransactionMatcher
{
- $this->limit = $limit;
+ $this->triggers = $triggers;
return $this;
}
/**
- * Get range
- *
- * @return int
+ * @return bool
*/
- public function getRange(): int
+ public function isStrict(): bool
{
- return $this->range;
+ return $this->strict;
}
/**
- * Set range
- *
- * @param int $range
- *
- * @return TransactionMatcher
+ * @param bool $strict
*/
- public function setRange(int $range): TransactionMatcher
+ public function setStrict(bool $strict): void
{
- $this->range = $range;
+ $this->strict = $strict;
+ }
- return $this;
+ /**
+ * @param Collection $accounts
+ */
+ public function setAccounts(Collection $accounts): void
+ {
+ $this->accounts = $accounts;
}
/**
- * Get triggers
- *
- * @return array
+ * @param Carbon|null $endDate
*/
- public function getTriggers(): array
+ public function setEndDate(Carbon $endDate = null): void
{
- return $this->triggers;
+ $this->endDate = $endDate;
}
/**
- * Set triggers
- *
- * @param array $triggers
+ * Set rule
*
- * @return TransactionMatcher
+ * @param Rule $rule
*/
- public function setTriggers(array $triggers): TransactionMatcher
+ public function setRule(Rule $rule): void
{
- $this->triggers = $triggers;
-
- return $this;
+ $this->rule = $rule;
}
/**
- * @return bool
+ * @param int $searchLimit
*/
- public function isStrict(): bool
+ public function setSearchLimit(int $searchLimit): void
{
- return $this->strict;
+ $this->searchLimit = $searchLimit;
}
/**
- * @param bool $strict
+ * @param Carbon|null $startDate
*/
- public function setStrict(bool $strict): void
+ public function setStartDate(Carbon $startDate = null): void
{
- $this->strict = $strict;
+ $this->startDate = $startDate;
}
/**
- * Set rule
- *
- * @param Rule $rule
+ * @param int $triggeredLimit
*/
- public function setRule(Rule $rule): void
+ public function setTriggeredLimit(int $triggeredLimit): void
{
- $this->rule = $rule;
+ $this->triggeredLimit = $triggeredLimit;
}
/**
@@ -249,27 +258,43 @@ class TransactionMatcher
*/
private function runProcessor(Processor $processor): Collection
{
+ Log::debug('Now in runprocessor()');
// 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
- $pageSize = min($this->range / 2, $this->limit * 2);
+ $pageSize = min($this->searchLimit, min($this->triggeredLimit, 50));
$processed = 0;
$page = 1;
- $result = new Collection();
+ $result = new Collection;
+
+ Log::debug(sprintf('Search limit is %d, triggered limit is %d, so page size is %d', $this->searchLimit, $this->triggeredLimit, $pageSize));
+
do {
+ Log::debug('Start of do-loop');
// Fetch a batch of transactions from the database
/** @var TransactionCollectorInterface $collector */
$collector = app(TransactionCollectorInterface::class);
$collector->setUser(auth()->user());
$collector->withOpposingAccount();
- $collector->setAllAssetAccounts()->setLimit($pageSize)->setPage($page)->setTypes($this->transactionTypes);
+
+ // limit asset accounts:
+ if (0 === $this->accounts->count()) {
+ $collector->setAllAssetAccounts();
+ }
+ if ($this->accounts->count() > 0) {
+ $collector->setAccounts($this->accounts);
+ }
+ if(null !== $this->startDate && null !== $this->endDate) {
+ $collector->setRange($this->startDate, $this->endDate);
+ }
+
+ $collector->setLimit($pageSize)->setPage($page)->setTypes($this->transactionTypes);
if (null !== $this->maxAmount) {
Log::debug(sprintf('Amount must be less than %s', $this->maxAmount));
$collector->amountLess($this->maxAmount);
@@ -290,7 +315,7 @@ class TransactionMatcher
// Filter transactions that match the given triggers.
$filtered = $set->filter(
function (Transaction $transaction) use ($processor) {
- Log::debug(sprintf('Test these triggers on journal #%d (transaction #%d)', $transaction->transaction_journal_id, $transaction->id));
+ Log::debug(sprintf('Test the triggers on journal #%d (transaction #%d)', $transaction->transaction_journal_id, $transaction->id));
return $processor->handleTransaction($transaction);
}
@@ -311,13 +336,14 @@ class TransactionMatcher
// Check for conditions to finish the loop
$reachedEndOfList = $set->count() < 1;
- $foundEnough = $result->count() >= $this->limit;
- $searchedEnough = ($processed >= $this->range);
+ $foundEnough = $result->count() >= $this->triggeredLimit;
+ $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);
+ Log::debug('End of do-loop');
return $result;
}
diff --git a/app/Transformers/PiggyBankTransformer.php b/app/Transformers/PiggyBankTransformer.php
index 7490b89f02..af41ba7087 100644
--- a/app/Transformers/PiggyBankTransformer.php
+++ b/app/Transformers/PiggyBankTransformer.php
@@ -40,18 +40,7 @@ use Symfony\Component\HttpFoundation\ParameterBag;
*/
class PiggyBankTransformer extends TransformerAbstract
{
- /**
- * List of resources possible to include
- *
- * @var array
- */
- protected $availableIncludes = ['account', 'user', 'piggy_bank_events'];
- /**
- * List of resources to automatically include
- *
- * @var array
- */
- protected $defaultIncludes = [];
+
/** @var ParameterBag */
protected $parameters;
@@ -68,46 +57,6 @@ class PiggyBankTransformer extends TransformerAbstract
$this->parameters = $parameters;
}
- /**
- * Include account.
- *
- * @codeCoverageIgnore
- *
- * @param PiggyBank $piggyBank
- *
- * @return Item
- */
- public function includeAccount(PiggyBank $piggyBank): Item
- {
- return $this->item($piggyBank->account, new AccountTransformer($this->parameters), 'accounts');
- }
-
- /**
- * Include events.
- *
- * @codeCoverageIgnore
- *
- * @param PiggyBank $piggyBank
- *
- * @return FractalCollection
- */
- public function includePiggyBankEvents(PiggyBank $piggyBank): FractalCollection
- {
- return $this->collection($piggyBank->piggyBankEvents, new PiggyBankEventTransformer($this->parameters), 'piggy_bank_events');
- }
-
- /**
- * Include the user.
- *
- * @param PiggyBank $piggyBank
- *
- * @codeCoverageIgnore
- * @return Item
- */
- public function includeUser(PiggyBank $piggyBank): Item
- {
- return $this->item($piggyBank->account->user, new UserTransformer($this->parameters), 'users');
- }
/**
* Transform the piggy bank.
diff --git a/app/Transformers/PreferenceTransformer.php b/app/Transformers/PreferenceTransformer.php
index 254c11bf3c..bbafaf4122 100644
--- a/app/Transformers/PreferenceTransformer.php
+++ b/app/Transformers/PreferenceTransformer.php
@@ -33,18 +33,6 @@ use Symfony\Component\HttpFoundation\ParameterBag;
*/
class PreferenceTransformer extends TransformerAbstract
{
- /**
- * List of resources possible to include.
- *
- * @var array
- */
- protected $availableIncludes = ['user'];
- /**
- * List of resources to automatically include
- *
- * @var array
- */
- protected $defaultIncludes = [];
/** @var ParameterBag */
protected $parameters;
diff --git a/app/Transformers/RecurrenceTransformer.php b/app/Transformers/RecurrenceTransformer.php
index f3eccd0c1d..1d9bb1cb4f 100644
--- a/app/Transformers/RecurrenceTransformer.php
+++ b/app/Transformers/RecurrenceTransformer.php
@@ -46,19 +46,6 @@ use Symfony\Component\HttpFoundation\ParameterBag;
*/
class RecurrenceTransformer extends TransformerAbstract
{
- /** @noinspection ClassOverridesFieldOfSuperClassInspection */
- /**
- * List of resources possible to include.
- *
- * @var array
- */
- protected $availableIncludes = ['user', 'transactions'];
- /**
- * List of resources to automatically include
- *
- * @var array
- */
- protected $defaultIncludes = [];
/** @var ParameterBag */
protected $parameters;
@@ -76,21 +63,6 @@ class RecurrenceTransformer extends TransformerAbstract
$this->parameters = $parameters;
}
- /**
- * Include user data in end result.
- *
- * @codeCoverageIgnore
- *
- * @param Recurrence $recurrence
- *
- *
- * @return Item
- */
- public function includeUser(Recurrence $recurrence): Item
- {
- return $this->item($recurrence->user, new UserTransformer($this->parameters), 'users');
- }
-
/**
* Transform the recurring transaction.
*
diff --git a/app/Transformers/RuleActionTransformer.php b/app/Transformers/RuleActionTransformer.php
index 731a062946..29aadd9a86 100644
--- a/app/Transformers/RuleActionTransformer.php
+++ b/app/Transformers/RuleActionTransformer.php
@@ -33,18 +33,6 @@ use Symfony\Component\HttpFoundation\ParameterBag;
*/
class RuleActionTransformer extends TransformerAbstract
{
- /**
- * List of resources possible to include
- *
- * @var array
- */
- protected $availableIncludes = [];
- /**
- * List of resources to automatically include
- *
- * @var array
- */
- protected $defaultIncludes = [];
/** @var ParameterBag */
protected $parameters;
diff --git a/app/Transformers/RuleTransformer.php b/app/Transformers/RuleTransformer.php
index 6e6b6cdb70..db0454c3f7 100644
--- a/app/Transformers/RuleTransformer.php
+++ b/app/Transformers/RuleTransformer.php
@@ -25,8 +25,8 @@ namespace FireflyIII\Transformers;
use FireflyIII\Models\Rule;
-use League\Fractal\Resource\Collection as FractalCollection;
-use League\Fractal\Resource\Item;
+use FireflyIII\Models\RuleAction;
+use FireflyIII\Models\RuleTrigger;
use League\Fractal\TransformerAbstract;
use Symfony\Component\HttpFoundation\ParameterBag;
@@ -35,19 +35,6 @@ use Symfony\Component\HttpFoundation\ParameterBag;
*/
class RuleTransformer extends TransformerAbstract
{
- /**
- * List of resources possible to include
- *
- * @var array
- */
- protected $availableIncludes = ['rule_group', 'rule_triggers', 'rule_actions', 'user'];
- /**
- * List of resources to automatically include
- *
- * @var array
- */
- protected $defaultIncludes = ['rule_group', 'rule_triggers', 'rule_actions'];
-
/** @var ParameterBag */
protected $parameters;
@@ -63,52 +50,6 @@ class RuleTransformer extends TransformerAbstract
$this->parameters = $parameters;
}
- /**
- * @param Rule $rule
- *
- * @return FractalCollection
- */
- public function includeRuleActions(Rule $rule): FractalCollection
- {
- return $this->collection($rule->ruleActions, new RuleActionTransformer($this->parameters), 'rule_actions');
- }
-
- /**
- * Include the rule group.
- *
- * @param Rule $rule
- *
- * @codeCoverageIgnore
- * @return Item
- */
- public function includeRuleGroup(Rule $rule): Item
- {
- return $this->item($rule->ruleGroup, new RuleGroupTransformer($this->parameters), 'rule_groups');
- }
-
- /**
- * @param Rule $rule
- *
- * @return FractalCollection
- */
- public function includeRuleTriggers(Rule $rule): FractalCollection
- {
- return $this->collection($rule->ruleTriggers, new RuleTriggerTransformer($this->parameters), 'rule_triggers');
- }
-
- /**
- * Include the user.
- *
- * @param Rule $rule
- *
- * @codeCoverageIgnore
- * @return Item
- */
- public function includeUser(Rule $rule): Item
- {
- return $this->item($rule->user, new UserTransformer($this->parameters), 'users');
- }
-
/**
* Transform the rule.
*
@@ -123,11 +64,13 @@ class RuleTransformer extends TransformerAbstract
'updated_at' => $rule->updated_at->toAtomString(),
'created_at' => $rule->created_at->toAtomString(),
'title' => $rule->title,
- 'text' => $rule->text,
+ 'description' => $rule->text,
'order' => (int)$rule->order,
'active' => $rule->active,
'stop_processing' => $rule->stop_processing,
'strict' => $rule->strict,
+ 'triggers' => $this->triggers($rule),
+ 'actions' => $this->actions($rule),
'links' => [
[
'rel' => 'self',
@@ -138,4 +81,56 @@ class RuleTransformer extends TransformerAbstract
return $data;
}
+
+ /**
+ * @param Rule $rule
+ *
+ * @return array
+ */
+ private function actions(Rule $rule): array
+ {
+ $result = [];
+ $actions = $rule->ruleActions()->orderBy('order', 'ASC')->get();
+ /** @var RuleAction $ruleAction */
+ foreach ($actions as $ruleAction) {
+ $result[] = [
+ 'id' => (int)$ruleAction->id,
+ 'updated_at' => $ruleAction->updated_at->toAtomString(),
+ 'created_at' => $ruleAction->created_at->toAtomString(),
+ 'type' => $ruleAction->action_type,
+ 'value' => $ruleAction->action_value,
+ 'order' => $ruleAction->order,
+ 'active' => $ruleAction->active,
+ 'stop_processing' => $ruleAction->stop_processing,
+ ];
+ }
+
+ return $result;
+ }
+
+ /**
+ * @param Rule $rule
+ *
+ * @return array
+ */
+ private function triggers(Rule $rule): array
+ {
+ $result = [];
+ $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->get();
+ /** @var RuleTrigger $ruleTrigger */
+ foreach ($triggers as $ruleTrigger) {
+ $result[] = [
+ 'id' => (int)$ruleTrigger->id,
+ 'updated_at' => $ruleTrigger->updated_at->toAtomString(),
+ 'created_at' => $ruleTrigger->created_at->toAtomString(),
+ 'type' => $ruleTrigger->trigger_type,
+ 'value' => $ruleTrigger->trigger_value,
+ 'order' => $ruleTrigger->order,
+ 'active' => $ruleTrigger->active,
+ 'stop_processing' => $ruleTrigger->stop_processing,
+ ];
+ }
+
+ return $result;
+ }
}
diff --git a/app/Transformers/RuleTriggerTransformer.php b/app/Transformers/RuleTriggerTransformer.php
index ad25279614..076c569746 100644
--- a/app/Transformers/RuleTriggerTransformer.php
+++ b/app/Transformers/RuleTriggerTransformer.php
@@ -33,19 +33,6 @@ use Symfony\Component\HttpFoundation\ParameterBag;
*/
class RuleTriggerTransformer extends TransformerAbstract
{
- /**
- * List of resources possible to include
- *
- * @var array
- */
- protected $availableIncludes = [];
- /**
- * List of resources to automatically include
- *
- * @var array
- */
- protected $defaultIncludes = [];
-
/** @var ParameterBag */
protected $parameters;
diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php
index 851e87e13b..929cd3e7d6 100644
--- a/app/Transformers/UserTransformer.php
+++ b/app/Transformers/UserTransformer.php
@@ -35,19 +35,6 @@ use Symfony\Component\HttpFoundation\ParameterBag;
*/
class UserTransformer extends TransformerAbstract
{
- /**
- * List of resources possible to include.
- *
- * @var array
- */
- protected $availableIncludes = ['accounts', 'attachments', 'bills', 'budgets', 'categories', 'piggy_banks', 'tags', 'transactions'];
- /**
- * List of resources to automatically include
- *
- * @var array
- */
- protected $defaultIncludes = [];
-
/** @var ParameterBag */
protected $parameters;
@@ -62,117 +49,6 @@ class UserTransformer extends TransformerAbstract
{
$this->parameters = $parameters;
}
-
- /**
- * Include accounts.
- *
- * @codeCoverageIgnore
- *
- * @param User $user
- *
- * @return FractalCollection
- */
- public function includeAccounts(User $user): FractalCollection
- {
- return $this->collection($user->accounts, new AccountTransformer($this->parameters), 'accounts');
- }
-
- /**
- * Include attachments.
- *
- * @codeCoverageIgnore
- *
- * @param User $user
- *
- * @return FractalCollection
- */
- public function includeAttachments(User $user): FractalCollection
- {
- return $this->collection($user->attachments, new AttachmentTransformer($this->parameters), 'attachments');
- }
-
- /**
- * @codeCoverageIgnore
- *
- * @param User $user
- *
- * @return FractalCollection
- */
- public function includeBills(User $user): FractalCollection
- {
- return $this->collection($user->bills, new BillTransformer($this->parameters), 'bills');
- }
-
- /**
- * Include budgets.
- *
- * @codeCoverageIgnore
- *
- * @param User $user
- *
- * @return FractalCollection
- */
- public function includeBudgets(User $user): FractalCollection
- {
- return $this->collection($user->budgets, new BudgetTransformer($this->parameters), 'budgets');
- }
-
- /**
- * Include categories.
- *
- * @codeCoverageIgnore
- *
- * @param User $user
- *
- * @return FractalCollection
- */
- public function includeCategories(User $user): FractalCollection
- {
- return $this->collection($user->categories, new CategoryTransformer($this->parameters), 'categories');
- }
-
- /**
- * Include piggy banks.
- *
- * @codeCoverageIgnore
- *
- * @param User $user
- *
- * @return FractalCollection
- */
- public function includePiggyBanks(User $user): FractalCollection
- {
- return $this->collection($user->piggyBanks, new PiggyBankTransformer($this->parameters), 'piggy_banks');
- }
-
- /**
- * Include tags.
- *
- * @codeCoverageIgnore
- *
- * @param User $user
- *
- * @return FractalCollection
- */
- public function includeTags(User $user): FractalCollection
- {
- return $this->collection($user->tags, new TagTransformer($this->parameters), 'tags');
- }
-
- /**
- * Include transactions.
- *
- * @codeCoverageIgnore
- *
- * @param User $user
- *
- * @return FractalCollection
- */
- public function includeTransactions(User $user): FractalCollection
- {
- return $this->collection($user->transactions, new TransactionTransformer($this->parameters), 'transactions');
- }
-
/**
* Transform user.
*