Skip to content

Firefly III: a personal finances manager

Expand query search.

James Coleaca008c9119f
diff --git a/app/Helpers/Collector/Extensions/AccountCollection.php b/app/Helpers/Collector/Extensions/AccountCollection.php
index 762c47c7a4..41f3aa35b7 100644
--- a/app/Helpers/Collector/Extensions/AccountCollection.php
+++ b/app/Helpers/Collector/Extensions/AccountCollection.php
@@ -216,9 +216,9 @@ trait AccountCollection
$this->query->leftJoin('account_types as dest_account_type', 'dest_account_type.id', '=', 'dest_account.account_type_id');
// and add fields:
- $this->fields[] = 'dest_account.name as destination_account_name';
- $this->fields[] = 'dest_account.iban as destination_account_iban';
- $this->fields[] = 'dest_account_type.type as destination_account_type';
+ $this->fields[] = 'dest_account.name as destination_account_name';
+ $this->fields[] = 'dest_account.iban as destination_account_iban';
+ $this->fields[] = 'dest_account_type.type as destination_account_type';
$this->hasAccountInfo = true;
}
diff --git a/app/Helpers/Collector/Extensions/CollectorProperties.php b/app/Helpers/Collector/Extensions/CollectorProperties.php
index 92b74ab5c3..544478e881 100644
--- a/app/Helpers/Collector/Extensions/CollectorProperties.php
+++ b/app/Helpers/Collector/Extensions/CollectorProperties.php
@@ -32,20 +32,20 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
*/
trait CollectorProperties
{
- private array $fields;
- private bool $hasAccountInfo;
- private bool $hasBillInformation;
- private bool $hasBudgetInformation;
- private bool $hasCatInformation;
- private bool $hasJoinedAttTables;
- private bool $hasJoinedMetaTables;
- private bool $hasJoinedTagTables;
- private bool $hasNotesInformation;
- private array $integerFields;
- private ?int $limit;
- private ?int $page;
+ private array $fields;
+ private bool $hasAccountInfo;
+ private bool $hasBillInformation;
+ private bool $hasBudgetInformation;
+ private bool $hasCatInformation;
+ private bool $hasJoinedAttTables;
+ private bool $hasJoinedMetaTables;
+ private bool $hasJoinedTagTables;
+ private bool $hasNotesInformation;
+ private array $integerFields;
+ private ?int $limit;
+ private ?int $page;
+ private array $postFilters;
private HasMany $query;
- private int $total;
- private ?User $user;
- private array $postFilters;
+ private int $total;
+ private ?User $user;
}
diff --git a/app/Helpers/Collector/Extensions/MetaCollection.php b/app/Helpers/Collector/Extensions/MetaCollection.php
index 0d8666f9fd..de0843fe49 100644
--- a/app/Helpers/Collector/Extensions/MetaCollection.php
+++ b/app/Helpers/Collector/Extensions/MetaCollection.php
@@ -39,6 +39,50 @@ use Log;
*/
trait MetaCollection
{
+ /**
+ * @inheritDoc
+ */
+ public function externalIdContains(string $externalId): GroupCollectorInterface
+ {
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ }
+ $this->query->where('journal_meta.name', '=', 'external_id');
+ $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s%%', $externalId));
+
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function externalIdEnds(string $externalId): GroupCollectorInterface
+ {
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ }
+ $this->query->where('journal_meta.name', '=', 'external_id');
+ $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s"', $externalId));
+
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function externalIdStarts(string $externalId): GroupCollectorInterface
+ {
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ }
+ $this->query->where('journal_meta.name', '=', 'external_id');
+ $this->query->where('journal_meta.data', 'LIKE', sprintf('"%s%%', $externalId));
+
+ return $this;
+ }
/**
* Where has no tags.
@@ -53,6 +97,82 @@ trait MetaCollection
return $this;
}
+ /**
+ * @return GroupCollectorInterface
+ */
+ public function withTagInformation(): GroupCollectorInterface
+ {
+ $this->fields[] = 'tags.id as tag_id';
+ $this->fields[] = 'tags.tag as tag_name';
+ $this->fields[] = 'tags.date as tag_date';
+ $this->fields[] = 'tags.description as tag_description';
+ $this->fields[] = 'tags.latitude as tag_latitude';
+ $this->fields[] = 'tags.longitude as tag_longitude';
+ $this->fields[] = 'tags.zoomLevel as tag_zoom_level';
+
+ $this->joinTagTables();
+
+ return $this;
+ }
+
+ /**
+ * Join table to get tag information.
+ */
+ protected function joinTagTables(): void
+ {
+ if (false === $this->hasJoinedTagTables) {
+ // join some extra tables:
+ $this->hasJoinedTagTables = true;
+ $this->query->leftJoin('tag_transaction_journal', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+ $this->query->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id');
+ }
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function internalReferenceContains(string $externalId): GroupCollectorInterface
+ {
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ }
+ $this->query->where('journal_meta.name', '=', 'internal_reference');
+ $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s%%', $externalId));
+
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function internalReferenceEnds(string $externalId): GroupCollectorInterface
+ {
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ }
+ $this->query->where('journal_meta.name', '=', 'internal_reference');
+ $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s"', $externalId));
+
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function internalReferenceStarts(string $externalId): GroupCollectorInterface
+ {
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ }
+ $this->query->where('journal_meta.name', '=', 'internal_reference');
+ $this->query->where('journal_meta.data', 'LIKE', sprintf('"%s%%', $externalId));
+
+ return $this;
+ }
+
/**
* @param string $value
*
@@ -66,6 +186,29 @@ trait MetaCollection
return $this;
}
+ /**
+ * @inheritDoc
+ */
+ public function withNotes(): GroupCollectorInterface
+ {
+ if (false === $this->hasNotesInformation) {
+ // join bill table
+ $this->query->leftJoin(
+ 'notes',
+ static function (JoinClause $join) {
+ $join->on('notes.noteable_id', '=', 'transaction_journals.id');
+ $join->where('notes.noteable_type', '=', 'FireflyIII\Models\TransactionJournal');
+ $join->whereNull('notes.deleted_at');
+ }
+ );
+ // add fields
+ $this->fields[] = 'notes.text as notes';
+ $this->hasNotesInformation = true;
+ }
+
+ return $this;
+ }
+
/**
* @param string $value
*
@@ -120,6 +263,25 @@ trait MetaCollection
return $this;
}
+ /**
+ * Will include bill name + ID, if any.
+ *
+ * @return GroupCollectorInterface
+ */
+ public function withBillInformation(): GroupCollectorInterface
+ {
+ if (false === $this->hasBillInformation) {
+ // join bill table
+ $this->query->leftJoin('bills', 'bills.id', '=', 'transaction_journals.bill_id');
+ // add fields
+ $this->fields[] = 'bills.id as bill_id';
+ $this->fields[] = 'bills.name as bill_name';
+ $this->hasBillInformation = true;
+ }
+
+ return $this;
+ }
+
/**
* Limit the search to a specific set of bills.
*
@@ -150,6 +312,27 @@ trait MetaCollection
return $this;
}
+ /**
+ * Will include budget ID + name, if any.
+ *
+ * @return GroupCollectorInterface
+ */
+ public function withBudgetInformation(): GroupCollectorInterface
+ {
+ if (false === $this->hasBudgetInformation) {
+ // join link table
+ $this->query->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+ // join cat table
+ $this->query->leftJoin('budgets', 'budget_transaction_journal.budget_id', '=', 'budgets.id');
+ // add fields
+ $this->fields[] = 'budgets.id as budget_id';
+ $this->fields[] = 'budgets.name as budget_name';
+ $this->hasBudgetInformation = true;
+ }
+
+ return $this;
+ }
+
/**
* Limit the search to a specific set of budgets.
*
@@ -185,61 +368,37 @@ trait MetaCollection
}
/**
- * Limit the search to a specific category.
- *
- * @param Category $category
+ * Will include category ID + name, if any.
*
* @return GroupCollectorInterface
*/
- public function setCategory(Category $category): GroupCollectorInterface
- {
- $this->withCategoryInformation();
- $this->query->where('categories.id', $category->id);
-
- return $this;
- }
-
- /**
- * @inheritDoc
- */
- public function setExternalId(string $externalId): GroupCollectorInterface
- {
- if (false === $this->hasJoinedMetaTables) {
- $this->hasJoinedMetaTables = true;
- $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
- }
- $this->query->where('journal_meta.name', '=', 'external_id');
- $this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($externalId)));
-
- return $this;
- }
-
- /**
- * @inheritDoc
- */
- public function externalIdContains(string $externalId): GroupCollectorInterface
+ public function withCategoryInformation(): GroupCollectorInterface
{
- if (false === $this->hasJoinedMetaTables) {
- $this->hasJoinedMetaTables = true;
- $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ if (false === $this->hasCatInformation) {
+ // join link table
+ $this->query->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+ // join cat table
+ $this->query->leftJoin('categories', 'category_transaction_journal.category_id', '=', 'categories.id');
+ // add fields
+ $this->fields[] = 'categories.id as category_id';
+ $this->fields[] = 'categories.name as category_name';
+ $this->hasCatInformation = true;
}
- $this->query->where('journal_meta.name', '=', 'external_id');
- $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s%%', $externalId));
return $this;
}
/**
- * @inheritDoc
+ * Limit the search to a specific category.
+ *
+ * @param Category $category
+ *
+ * @return GroupCollectorInterface
*/
- public function externalIdEnds(string $externalId): GroupCollectorInterface
+ public function setCategory(Category $category): GroupCollectorInterface
{
- if (false === $this->hasJoinedMetaTables) {
- $this->hasJoinedMetaTables = true;
- $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
- }
- $this->query->where('journal_meta.name', '=', 'external_id');
- $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s"', $externalId));
+ $this->withCategoryInformation();
+ $this->query->where('categories.id', $category->id);
return $this;
}
@@ -247,50 +406,14 @@ trait MetaCollection
/**
* @inheritDoc
*/
- public function externalIdStarts(string $externalId): GroupCollectorInterface
+ public function setExternalId(string $externalId): GroupCollectorInterface
{
if (false === $this->hasJoinedMetaTables) {
$this->hasJoinedMetaTables = true;
$this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
}
$this->query->where('journal_meta.name', '=', 'external_id');
- $this->query->where('journal_meta.data', 'LIKE', sprintf('"%s%%', $externalId));
-
- return $this;
- }
-
- /**
- * @inheritDoc
- */
- public function withoutExternalUrl(): GroupCollectorInterface
- {
- if (false === $this->hasJoinedMetaTables) {
- $this->hasJoinedMetaTables = true;
- $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
- }
- $this->query->where(function (Builder $q1) {
- $q1->where(function (Builder $q2) {
- $q2->where('journal_meta.name', '=', 'external_url');
- $q2->whereNull('journal_meta.data');
- })->orWhere(function (Builder $q3) {
- $q3->where('journal_meta.name', '!=', 'external_url');
- });
- });
-
- return $this;
- }
-
- /**
- * @inheritDoc
- */
- public function withExternalUrl(): GroupCollectorInterface
- {
- if (false === $this->hasJoinedMetaTables) {
- $this->hasJoinedMetaTables = true;
- $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
- }
- $this->query->where('journal_meta.name', '=', 'external_url');
- $this->query->whereNotNull('journal_meta.data');
+ $this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($externalId)));
return $this;
}
@@ -353,11 +476,11 @@ trait MetaCollection
$this->withTagInformation();
// this method adds a "postFilter" to the collector.
- $list = $tags->pluck('tag')->toArray();
- $filter = function (int $index, array $object) use ($list): bool {
- foreach($object['transactions'] as $transaction) {
- foreach($transaction['tags'] as $tag) {
- if(in_array($tag['name'], $list)) {
+ $list = $tags->pluck('tag')->toArray();
+ $filter = function (int $index, array $object) use ($list): bool {
+ foreach ($object['transactions'] as $transaction) {
+ foreach ($transaction['tags'] as $tag) {
+ if (in_array($tag['name'], $list)) {
return false;
}
}
@@ -394,25 +517,6 @@ trait MetaCollection
return $this;
}
- /**
- * Will include bill name + ID, if any.
- *
- * @return GroupCollectorInterface
- */
- public function withBillInformation(): GroupCollectorInterface
- {
- if (false === $this->hasBillInformation) {
- // join bill table
- $this->query->leftJoin('bills', 'bills.id', '=', 'transaction_journals.bill_id');
- // add fields
- $this->fields[] = 'bills.id as bill_id';
- $this->fields[] = 'bills.name as bill_name';
- $this->hasBillInformation = true;
- }
-
- return $this;
- }
-
/**
* Limit results to a transactions without a budget..
*
@@ -426,27 +530,6 @@ trait MetaCollection
return $this;
}
- /**
- * Will include budget ID + name, if any.
- *
- * @return GroupCollectorInterface
- */
- public function withBudgetInformation(): GroupCollectorInterface
- {
- if (false === $this->hasBudgetInformation) {
- // join link table
- $this->query->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
- // join cat table
- $this->query->leftJoin('budgets', 'budget_transaction_journal.budget_id', '=', 'budgets.id');
- // add fields
- $this->fields[] = 'budgets.id as budget_id';
- $this->fields[] = 'budgets.name as budget_name';
- $this->hasBudgetInformation = true;
- }
-
- return $this;
- }
-
/**
* Limit results to a transactions without a category.
*
@@ -460,64 +543,17 @@ trait MetaCollection
return $this;
}
- /**
- * Will include category ID + name, if any.
- *
- * @return GroupCollectorInterface
- */
- public function withCategoryInformation(): GroupCollectorInterface
- {
- if (false === $this->hasCatInformation) {
- // join link table
- $this->query->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
- // join cat table
- $this->query->leftJoin('categories', 'category_transaction_journal.category_id', '=', 'categories.id');
- // add fields
- $this->fields[] = 'categories.id as category_id';
- $this->fields[] = 'categories.name as category_name';
- $this->hasCatInformation = true;
- }
-
- return $this;
- }
-
/**
* @inheritDoc
*/
- public function withNotes(): GroupCollectorInterface
+ public function withExternalUrl(): GroupCollectorInterface
{
- if (false === $this->hasNotesInformation) {
- // join bill table
- $this->query->leftJoin(
- 'notes',
- static function (JoinClause $join) {
- $join->on('notes.noteable_id', '=', 'transaction_journals.id');
- $join->where('notes.noteable_type', '=', 'FireflyIII\Models\TransactionJournal');
- $join->whereNull('notes.deleted_at');
- }
- );
- // add fields
- $this->fields[] = 'notes.text as notes';
- $this->hasNotesInformation = true;
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
}
-
- return $this;
- }
-
- /**
- * @return GroupCollectorInterface
- */
- public function withTagInformation(): GroupCollectorInterface
- {
- $this->fields[] = 'tags.id as tag_id';
- $this->fields[] = 'tags.tag as tag_name';
- $this->fields[] = 'tags.date as tag_date';
- $this->fields[] = 'tags.description as tag_description';
- $this->fields[] = 'tags.latitude as tag_latitude';
- $this->fields[] = 'tags.longitude as tag_longitude';
- $this->fields[] = 'tags.zoomLevel as tag_zoom_level';
-
- $this->joinTagTables();
+ $this->query->where('journal_meta.name', '=', 'external_url');
+ $this->query->whereNotNull('journal_meta.data');
return $this;
}
@@ -560,6 +596,27 @@ trait MetaCollection
return $this;
}
+ /**
+ * @inheritDoc
+ */
+ public function withoutExternalUrl(): GroupCollectorInterface
+ {
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ }
+ $this->query->where(function (Builder $q1) {
+ $q1->where(function (Builder $q2) {
+ $q2->where('journal_meta.name', '=', 'external_url');
+ $q2->whereNull('journal_meta.data');
+ })->orWhere(function (Builder $q3) {
+ $q3->where('journal_meta.name', '!=', 'external_url');
+ });
+ });
+
+ return $this;
+ }
+
/**
* @return GroupCollectorInterface
*/
@@ -586,17 +643,4 @@ trait MetaCollection
return $this;
}
-
- /**
- * Join table to get tag information.
- */
- protected function joinTagTables(): void
- {
- if (false === $this->hasJoinedTagTables) {
- // join some extra tables:
- $this->hasJoinedTagTables = true;
- $this->query->leftJoin('tag_transaction_journal', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
- $this->query->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id');
- }
- }
}
diff --git a/app/Helpers/Collector/Extensions/TimeCollection.php b/app/Helpers/Collector/Extensions/TimeCollection.php
index 938fc29315..fd238b7f81 100644
--- a/app/Helpers/Collector/Extensions/TimeCollection.php
+++ b/app/Helpers/Collector/Extensions/TimeCollection.php
@@ -33,6 +33,45 @@ use FireflyIII\Helpers\Collector\GroupCollectorInterface;
trait TimeCollection
{
+ public function dayAfter(string $day): GroupCollectorInterface
+ {
+ $this->query->whereDay('transaction_journals.date', '>=', $day);
+ return $this;
+ }
+
+ public function dayBefore(string $day): GroupCollectorInterface
+ {
+ $this->query->whereDay('transaction_journals.date', '<=', $day);
+ return $this;
+ }
+
+ public function dayIs(string $day): GroupCollectorInterface
+ {
+ $this->query->whereDay('transaction_journals.date', '=', $day);
+ return $this;
+ }
+
+ public function monthAfter(string $month): GroupCollectorInterface
+ {
+ $this->query->whereMonth('transaction_journals.date', '>=', $month);
+ return $this;
+
+ }
+
+ public function monthBefore(string $month): GroupCollectorInterface
+ {
+ $this->query->whereMonth('transaction_journals.date', '<=', $month);
+ return $this;
+
+ }
+
+ public function monthIs(string $month): GroupCollectorInterface
+ {
+ $this->query->whereMonth('transaction_journals.date', '=', $month);
+ return $this;
+
+ }
+
/**
* Collect transactions after a specific date.
*
@@ -120,60 +159,21 @@ trait TimeCollection
return $this;
}
- public function yearIs(string $year): GroupCollectorInterface
- {
- $this->query->whereYear('transaction_journals.date', '=', $year);
- return $this;
- }
-
- public function monthIs(string $month): GroupCollectorInterface
- {
- $this->query->whereMonth('transaction_journals.date', '=', $month);
- return $this;
-
- }
-
- public function dayIs(string $day): GroupCollectorInterface
- {
- $this->query->whereDay('transaction_journals.date', '=', $day);
- return $this;
- }
-
- public function yearBefore(string $year): GroupCollectorInterface
- {
- $this->query->whereYear('transaction_journals.date', '<=', $year);
- return $this;
- }
-
- public function monthBefore(string $month): GroupCollectorInterface
- {
- $this->query->whereMonth('transaction_journals.date', '<=', $month);
- return $this;
-
- }
-
- public function dayBefore(string $day): GroupCollectorInterface
- {
- $this->query->whereDay('transaction_journals.date', '<=', $day);
- return $this;
- }
-
public function yearAfter(string $year): GroupCollectorInterface
{
$this->query->whereYear('transaction_journals.date', '>=', $year);
return $this;
}
- public function monthAfter(string $month): GroupCollectorInterface
+ public function yearBefore(string $year): GroupCollectorInterface
{
- $this->query->whereMonth('transaction_journals.date', '>=', $month);
+ $this->query->whereYear('transaction_journals.date', '<=', $year);
return $this;
-
}
- public function dayAfter(string $day): GroupCollectorInterface
+ public function yearIs(string $year): GroupCollectorInterface
{
- $this->query->whereDay('transaction_journals.date', '>=', $day);
+ $this->query->whereYear('transaction_journals.date', '=', $year);
return $this;
}
}
diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php
index 6ecbde2139..257f1ab0e9 100644
--- a/app/Helpers/Collector/GroupCollector.php
+++ b/app/Helpers/Collector/GroupCollector.php
@@ -203,6 +203,26 @@ class GroupCollector implements GroupCollectorInterface
return $this;
}
+ /**
+ *
+ */
+ public function dumpQuery(): void
+ {
+ echo $this->query->select($this->fields)->toSql();
+ echo '<pre>';
+ print_r($this->query->getBindings());
+ echo '</pre>';
+ }
+
+ /**
+ *
+ */
+ public function dumpQueryInLogs(): void
+ {
+ Log::debug($this->query->select($this->fields)->toSql());
+ Log::debug('Bindings', $this->query->getBindings());
+ }
+
/**
* @inheritDoc
*/
@@ -264,235 +284,291 @@ class GroupCollector implements GroupCollectorInterface
}
/**
- * Same as getGroups but everything is in a paginator.
+ * @param Collection $collection
*
- * @return LengthAwarePaginator
+ * @return Collection
*/
- public function getPaginatedGroups(): LengthAwarePaginator
+ private function parseArray(Collection $collection): Collection
{
- $set = $this->getGroups();
- if (0 === $this->limit) {
- $this->setLimit(50);
+ $groups = [];
+ /** @var TransactionJournal $augumentedJournal */
+ foreach ($collection as $augumentedJournal) {
+ $groupId = $augumentedJournal->transaction_group_id;
+
+ if (!array_key_exists($groupId, $groups)) {
+ // make new array
+ $parsedGroup = $this->parseAugmentedJournal($augumentedJournal);
+ $groupArray = [
+ 'id' => (int) $augumentedJournal->transaction_group_id,
+ 'user_id' => (int) $augumentedJournal->user_id,
+ 'title' => $augumentedJournal->transaction_group_title,
+ 'transaction_type' => $parsedGroup['transaction_type_type'],
+ 'count' => 1,
+ 'sums' => [],
+ 'transactions' => [],
+ ];
+ $journalId = (int) $augumentedJournal->transaction_journal_id;
+ $groupArray['transactions'][$journalId] = $parsedGroup;
+ $groups[$groupId] = $groupArray;
+ continue;
+ }
+ // or parse the rest.
+ $journalId = (int) $augumentedJournal->transaction_journal_id;
+ if (array_key_exists($journalId, $groups[$groupId]['transactions'])) {
+ // append data to existing group + journal (for multiple tags or multiple attachments)
+ $groups[$groupId]['transactions'][$journalId] = $this->mergeTags($groups[$groupId]['transactions'][$journalId], $augumentedJournal);
+ $groups[$groupId]['transactions'][$journalId] = $this->mergeAttachments($groups[$groupId]['transactions'][$journalId], $augumentedJournal);
+ }
+
+ if (!array_key_exists($journalId, $groups[$groupId]['transactions'])) {
+ // create second, third, fourth split:
+ $groups[$groupId]['count']++;
+ $groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal);
+ }
}
- return new LengthAwarePaginator($set, $this->total, $this->limit, $this->page);
+ $groups = $this->parseSums($groups);
+
+ return new Collection($groups);
}
/**
- * Has attachments
+ * @param TransactionJournal $augumentedJournal
*
- * @return GroupCollectorInterface
+ * @return array
*/
- public function hasAttachments(): GroupCollectorInterface
+ private function parseAugmentedJournal(TransactionJournal $augumentedJournal): array
{
- Log::debug('Add filter on attachment ID.');
- $this->joinAttachmentTables();
- $this->query->whereNotNull('attachments.attachable_id');
+ $result = $augumentedJournal->toArray();
+ $result['tags'] = [];
+ $result['attachments'] = [];
+ try {
+ $result['date'] = new Carbon($result['date'], 'UTC');
+ $result['created_at'] = new Carbon($result['created_at'], 'UTC');
+ $result['updated_at'] = new Carbon($result['updated_at'], 'UTC');
- return $this;
- }
+ // this is going to happen a lot:
+ $result['date']->setTimezone(config('app.timezone'));
+ $result['created_at']->setTimezone(config('app.timezone'));
+ $result['updated_at']->setTimezone(config('app.timezone'));
+ } catch (Exception $e) { // @phpstan-ignore-line
+ Log::error($e->getMessage());
+ }
- /**
- * Limit results to a specific currency, either foreign or normal one.
- *
- * @param TransactionCurrency $currency
- *
- * @return GroupCollectorInterface
- */
- public function setCurrency(TransactionCurrency $currency): GroupCollectorInterface
- {
- $this->query->where(
- static function (EloquentBuilder $q) use ($currency) {
- $q->where('source.transaction_currency_id', $currency->id);
- $q->orWhere('source.foreign_currency_id', $currency->id);
+ // convert values to integers:
+ $result = $this->convertToInteger($result);
+
+ $result['reconciled'] = 1 === (int) $result['reconciled'];
+ if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well.
+ $tagId = (int) $augumentedJournal['tag_id'];
+ $tagDate = null;
+ try {
+ $tagDate = Carbon::parse($augumentedJournal['tag_date']);
+ } catch (InvalidDateException $e) {
+ Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
}
- );
- return $this;
- }
+ $result['tags'][$tagId] = [
+ 'id' => (int) $result['tag_id'],
+ 'name' => $result['tag_name'],
+ 'date' => $tagDate,
+ 'description' => $result['tag_description'],
+ ];
+ }
- /**
- * @inheritDoc
- */
- public function setForeignCurrency(TransactionCurrency $currency): GroupCollectorInterface
- {
- $this->query->where('source.foreign_currency_id', $currency->id);
+ // also merge attachments:
+ if (array_key_exists('attachment_id', $result)) {
+ $uploaded = 1 === (int) $result['attachment_uploaded'];
+ $attachmentId = (int) $augumentedJournal['attachment_id'];
+ if (0 !== $attachmentId && $uploaded) {
+ $result['attachments'][$attachmentId] = [
+ 'id' => $attachmentId,
+ ];
+ }
+ }
+ // unset various fields:
+ unset($result['tag_id'], $result['tag_name'], $result['tag_date'], $result['tag_description'], $result['tag_latitude'], $result['tag_longitude'], $result['tag_zoom_level']);
- return $this;
+ return $result;
}
/**
- * Limit the result to a set of specific transaction groups.
+ * Convert a selected set of fields to arrays.
*
- * @param array $groupIds
+ * @param array $array
*
- * @return GroupCollectorInterface
+ * @return array
*/
- public function setIds(array $groupIds): GroupCollectorInterface
+ private function convertToInteger(array $array): array
{
+ foreach ($this->integerFields as $field) {
+ $array[$field] = array_key_exists($field, $array) ? (int) $array[$field] : null;
+ }
- $this->query->whereIn('transaction_groups.id', $groupIds);
-
- return $this;
+ return $array;
}
/**
- * Limit the result to a set of specific journals.
- *
- * @param array $journalIds
+ * @param array $existingJournal
+ * @param TransactionJournal $newJournal
*
- * @return GroupCollectorInterface
+ * @return array
*/
- public function setJournalIds(array $journalIds): GroupCollectorInterface
+ private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array
{
- if (!empty($journalIds)) {
- // make all integers.
- $integerIDs = array_map('intval', $journalIds);
+ $newArray = $newJournal->toArray();
+ if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well.
+ $tagId = (int) $newJournal['tag_id'];
+ $tagDate = null;
+ try {
+ $tagDate = Carbon::parse($newArray['tag_date']);
+ } catch (InvalidDateException $e) {
+ Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
+ }
- $this->query->whereIn('transaction_journals.id', $integerIDs);
+ $existingJournal['tags'][$tagId] = [
+ 'id' => (int) $newArray['tag_id'],
+ 'name' => $newArray['tag_name'],
+ 'date' => $tagDate,
+ 'description' => $newArray['tag_description'],
+ ];
}
- return $this;
+ return $existingJournal;
}
/**
- * Limit the number of returned entries.
- *
- * @param int $limit
+ * @param array $existingJournal
+ * @param TransactionJournal $newJournal
*
- * @return GroupCollectorInterface
+ * @return array
*/
- public function setLimit(int $limit): GroupCollectorInterface
+ private function mergeAttachments(array $existingJournal, TransactionJournal $newJournal): array
{
- $this->limit = $limit;
- app('log')->debug(sprintf('GroupCollector: The limit is now %d', $limit));
+ $newArray = $newJournal->toArray();
+ if (array_key_exists('attachment_id', $newArray)) {
+ $attachmentId = (int) $newJournal['attachment_id'];
- return $this;
+ $existingJournal['attachments'][$attachmentId] = [
+ 'id' => $attachmentId,
+ ];
+ }
+
+ return $existingJournal;
}
/**
- * Set the page to get.
- *
- * @param int $page
+ * @param array $groups
*
- * @return GroupCollectorInterface
+ * @return array
*/
- public function setPage(int $page): GroupCollectorInterface
+ private function parseSums(array $groups): array
{
- $page = 0 === $page ? 1 : $page;
- $this->page = $page;
- app('log')->debug(sprintf('GroupCollector: page is now %d', $page));
+ /**
+ * @var int $groudId
+ * @var array $group
+ */
+ foreach ($groups as $groudId => $group) {
+ /** @var array $transaction */
+ foreach ($group['transactions'] as $transaction) {
+ $currencyId = (int) $transaction['currency_id'];
- return $this;
- }
+ // set default:
+ if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
+ $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;
+ $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code'];
+ $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol'];
+ $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places'];
+ $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
+ }
+ $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount'] ?? '0');
- /**
- * Search for words in descriptions.
- *
- * @param array $array
- *
- * @return GroupCollectorInterface
- */
- public function setSearchWords(array $array): GroupCollectorInterface
- {
- $this->query->where(
- static function (EloquentBuilder $q) use ($array) {
- $q->where(
- static function (EloquentBuilder $q1) use ($array) {
- foreach ($array as $word) {
- $keyword = sprintf('%%%s%%', $word);
- $q1->where('transaction_journals.description', 'LIKE', $keyword);
- }
- }
- );
- $q->orWhere(
- static function (EloquentBuilder $q2) use ($array) {
- foreach ($array as $word) {
- $keyword = sprintf('%%%s%%', $word);
- $q2->where('transaction_groups.title', 'LIKE', $keyword);
- }
+ if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) {
+ $currencyId = (int) $transaction['foreign_currency_id'];
+
+ // set default:
+ if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
+ $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;
+ $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code'];
+ $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol'];
+ $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places'];
+ $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
}
- );
+ $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd(
+ $groups[$groudId]['sums'][$currencyId]['amount'],
+ $transaction['foreign_amount'] ?? '0'
+ );
+ }
}
- );
+ }
- return $this;
+ return $groups;
}
/**
- * Limit the search to one specific transaction group.
- *
- * @param TransactionGroup $transactionGroup
- *
- * @return GroupCollectorInterface
+ * @param Collection $collection
+ * @return Collection
*/
- public function setTransactionGroup(TransactionGroup $transactionGroup): GroupCollectorInterface
+ private function postFilterCollection(Collection $collection): Collection
{
- $this->query->where('transaction_groups.id', $transactionGroup->id);
-
- return $this;
+ Log::debug('Now in postFilterCollection()');
+ $newCollection = new Collection;
+ foreach ($collection as $i => $item) {
+ Log::debug(sprintf('Now working on item #%d/%d', $i + 1, $collection->count()));
+ foreach ($this->postFilters as $func) {
+ if (false === $func($i, $item)) {
+ // skip other filters, continue to next item.
+ Log::debug('Filter returns false, jump to next item.');
+ continue 2;
+ }
+ Log::debug('Filter returns true');
+ }
+ $newCollection->push($item);
+ }
+ return $newCollection;
}
/**
- * Limit the included transaction types.
- *
- * @param array $types
+ * Same as getGroups but everything is in a paginator.
*
- * @return GroupCollectorInterface
+ * @return LengthAwarePaginator
*/
- public function setTypes(array $types): GroupCollectorInterface
+ public function getPaginatedGroups(): LengthAwarePaginator
{
- $this->query->whereIn('transaction_types.type', $types);
+ $set = $this->getGroups();
+ if (0 === $this->limit) {
+ $this->setLimit(50);
+ }
- return $this;
+ return new LengthAwarePaginator($set, $this->total, $this->limit, $this->page);
}
/**
- * Set the user object and start the query.
+ * Limit the number of returned entries.
*
- * @param User $user
+ * @param int $limit
*
* @return GroupCollectorInterface
*/
- public function setUser(User $user): GroupCollectorInterface
+ public function setLimit(int $limit): GroupCollectorInterface
{
- if (null === $this->user) {
- $this->user = $user;
- $this->startQuery();
-
- }
+ $this->limit = $limit;
+ app('log')->debug(sprintf('GroupCollector: The limit is now %d', $limit));
return $this;
}
/**
- * Automatically include all stuff required to make API calls work.
+ * Has attachments
*
* @return GroupCollectorInterface
*/
- public function withAPIInformation(): GroupCollectorInterface
- {
- // include source + destination account name and type.
- $this->withAccountInformation()
- // include category ID + name (if any)
- ->withCategoryInformation()
- // include budget ID + name (if any)
- ->withBudgetInformation()
- // include bill ID + name (if any)
- ->withBillInformation();
-
- return $this;
- }
-
- /**
- * @inheritDoc
- */
- public function withAttachmentInformation(): GroupCollectorInterface
+ public function hasAttachments(): GroupCollectorInterface
{
- $this->fields[] = 'attachments.id as attachment_id';
- $this->fields[] = 'attachments.uploaded as attachment_uploaded';
+ Log::debug('Add filter on attachment ID.');
$this->joinAttachmentTables();
+ $this->query->whereNotNull('attachments.attachable_id');
return $this;
}
@@ -517,311 +593,235 @@ class GroupCollector implements GroupCollectorInterface
}
/**
- * Build the query.
+ * Limit results to a specific currency, either foreign or normal one.
+ *
+ * @param TransactionCurrency $currency
+ *
+ * @return GroupCollectorInterface
*/
- private function startQuery(): void
+ public function setCurrency(TransactionCurrency $currency): GroupCollectorInterface
{
- //app('log')->debug('GroupCollector::startQuery');
- $this->query = $this->user
- //->transactionGroups()
- //->leftJoin('transaction_journals', 'transaction_journals.transaction_group_id', 'transaction_groups.id')
- ->transactionJournals()
- ->leftJoin('transaction_groups', 'transaction_journals.transaction_group_id', 'transaction_groups.id')
+ $this->query->where(
+ static function (EloquentBuilder $q) use ($currency) {
+ $q->where('source.transaction_currency_id', $currency->id);
+ $q->orWhere('source.foreign_currency_id', $currency->id);
+ }
+ );
- // join source transaction.
- ->leftJoin(
- 'transactions as source',
- function (JoinClause $join) {
- $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')
- ->where('source.amount', '<', 0);
- }
- )
- // join destination transaction
- ->leftJoin(
- 'transactions as destination',
- function (JoinClause $join) {
- $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')
- ->where('destination.amount', '>', 0);
- }
- )
- // left join transaction type.
- ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
- ->leftJoin('transaction_currencies as currency', 'currency.id', '=', 'source.transaction_currency_id')
- ->leftJoin('transaction_currencies as foreign_currency', 'foreign_currency.id', '=', 'source.foreign_currency_id')
- ->whereNull('transaction_groups.deleted_at')
- ->whereNull('transaction_journals.deleted_at')
- ->whereNull('source.deleted_at')
- ->whereNull('destination.deleted_at')
- ->orderBy('transaction_journals.date', 'DESC')
- ->orderBy('transaction_journals.order', 'ASC')
- ->orderBy('transaction_journals.id', 'DESC')
- ->orderBy('transaction_journals.description', 'DESC')
- ->orderBy('source.amount', 'DESC');
+ return $this;
}
/**
- *
+ * @inheritDoc
*/
- public function dumpQuery(): void
+ public function setForeignCurrency(TransactionCurrency $currency): GroupCollectorInterface
{
- echo $this->query->select($this->fields)->toSql();
- echo '<pre>';
- print_r($this->query->getBindings());
- echo '</pre>';
+ $this->query->where('source.foreign_currency_id', $currency->id);
+
+ return $this;
}
/**
+ * Limit the result to a set of specific transaction groups.
+ *
+ * @param array $groupIds
*
+ * @return GroupCollectorInterface
*/
- public function dumpQueryInLogs(): void
+ public function setIds(array $groupIds): GroupCollectorInterface
{
- Log::debug($this->query->select($this->fields)->toSql());
- Log::debug('Bindings', $this->query->getBindings());
+
+ $this->query->whereIn('transaction_groups.id', $groupIds);
+
+ return $this;
}
/**
- * Convert a selected set of fields to arrays.
+ * Limit the result to a set of specific journals.
*
- * @param array $array
+ * @param array $journalIds
*
- * @return array
+ * @return GroupCollectorInterface
*/
- private function convertToInteger(array $array): array
+ public function setJournalIds(array $journalIds): GroupCollectorInterface
{
- foreach ($this->integerFields as $field) {
- $array[$field] = array_key_exists($field, $array) ? (int) $array[$field] : null;
+ if (!empty($journalIds)) {
+ // make all integers.
+ $integerIDs = array_map('intval', $journalIds);
+
+
+ $this->query->whereIn('transaction_journals.id', $integerIDs);
}
- return $array;
+ return $this;
}
/**
- * @param array $existingJournal
- * @param TransactionJournal $newJournal
+ * Set the page to get.
*
- * @return array
+ * @param int $page
+ *
+ * @return GroupCollectorInterface
*/
- private function mergeAttachments(array $existingJournal, TransactionJournal $newJournal): array
+ public function setPage(int $page): GroupCollectorInterface
{
- $newArray = $newJournal->toArray();
- if (array_key_exists('attachment_id', $newArray)) {
- $attachmentId = (int) $newJournal['attachment_id'];
-
- $existingJournal['attachments'][$attachmentId] = [
- 'id' => $attachmentId,
- ];
- }
+ $page = 0 === $page ? 1 : $page;
+ $this->page = $page;
+ app('log')->debug(sprintf('GroupCollector: page is now %d', $page));
- return $existingJournal;
+ return $this;
}
/**
- * @param array $existingJournal
- * @param TransactionJournal $newJournal
+ * Search for words in descriptions.
*
- * @return array
+ * @param array $array
+ *
+ * @return GroupCollectorInterface
*/
- private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array
+ public function setSearchWords(array $array): GroupCollectorInterface
{
- $newArray = $newJournal->toArray();
- if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well.
- $tagId = (int) $newJournal['tag_id'];
-
- $tagDate = null;
- try {
- $tagDate = Carbon::parse($newArray['tag_date']);
- } catch (InvalidDateException $e) {
- Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
+ $this->query->where(
+ static function (EloquentBuilder $q) use ($array) {
+ $q->where(
+ static function (EloquentBuilder $q1) use ($array) {
+ foreach ($array as $word) {
+ $keyword = sprintf('%%%s%%', $word);
+ $q1->where('transaction_journals.description', 'LIKE', $keyword);
+ }
+ }
+ );
+ $q->orWhere(
+ static function (EloquentBuilder $q2) use ($array) {
+ foreach ($array as $word) {
+ $keyword = sprintf('%%%s%%', $word);
+ $q2->where('transaction_groups.title', 'LIKE', $keyword);
+ }
+ }
+ );
}
+ );
- $existingJournal['tags'][$tagId] = [
- 'id' => (int) $newArray['tag_id'],
- 'name' => $newArray['tag_name'],
- 'date' => $tagDate,
- 'description' => $newArray['tag_description'],
- ];
- }
-
- return $existingJournal;
+ return $this;
}
/**
- * @param Collection $collection
+ * Limit the search to one specific transaction group.
*
- * @return Collection
+ * @param TransactionGroup $transactionGroup
+ *
+ * @return GroupCollectorInterface
*/
- private function parseArray(Collection $collection): Collection
+ public function setTransactionGroup(TransactionGroup $transactionGroup): GroupCollectorInterface
{
- $groups = [];
- /** @var TransactionJournal $augumentedJournal */
- foreach ($collection as $augumentedJournal) {
- $groupId = $augumentedJournal->transaction_group_id;
-
- if (!array_key_exists($groupId, $groups)) {
- // make new array
- $parsedGroup = $this->parseAugmentedJournal($augumentedJournal);
- $groupArray = [
- 'id' => (int) $augumentedJournal->transaction_group_id,
- 'user_id' => (int) $augumentedJournal->user_id,
- 'title' => $augumentedJournal->transaction_group_title,
- 'transaction_type' => $parsedGroup['transaction_type_type'],
- 'count' => 1,
- 'sums' => [],
- 'transactions' => [],
- ];
- $journalId = (int) $augumentedJournal->transaction_journal_id;
- $groupArray['transactions'][$journalId] = $parsedGroup;
- $groups[$groupId] = $groupArray;
- continue;
- }
- // or parse the rest.
- $journalId = (int) $augumentedJournal->transaction_journal_id;
- if (array_key_exists($journalId, $groups[$groupId]['transactions'])) {
- // append data to existing group + journal (for multiple tags or multiple attachments)
- $groups[$groupId]['transactions'][$journalId] = $this->mergeTags($groups[$groupId]['transactions'][$journalId], $augumentedJournal);
- $groups[$groupId]['transactions'][$journalId] = $this->mergeAttachments($groups[$groupId]['transactions'][$journalId], $augumentedJournal);
- }
-
- if (!array_key_exists($journalId, $groups[$groupId]['transactions'])) {
- // create second, third, fourth split:
- $groups[$groupId]['count']++;
- $groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal);
- }
- }
-
- $groups = $this->parseSums($groups);
+ $this->query->where('transaction_groups.id', $transactionGroup->id);
- return new Collection($groups);
+ return $this;
}
/**
- * @param TransactionJournal $augumentedJournal
+ * Limit the included transaction types.
*
- * @return array
+ * @param array $types
+ *
+ * @return GroupCollectorInterface
*/
- private function parseAugmentedJournal(TransactionJournal $augumentedJournal): array
+ public function setTypes(array $types): GroupCollectorInterface
{
- $result = $augumentedJournal->toArray();
- $result['tags'] = [];
- $result['attachments'] = [];
- try {
- $result['date'] = new Carbon($result['date'], 'UTC');
- $result['created_at'] = new Carbon($result['created_at'], 'UTC');
- $result['updated_at'] = new Carbon($result['updated_at'], 'UTC');
-
- // this is going to happen a lot:
- $result['date']->setTimezone(config('app.timezone'));
- $result['created_at']->setTimezone(config('app.timezone'));
- $result['updated_at']->setTimezone(config('app.timezone'));
- } catch (Exception $e) { // @phpstan-ignore-line
- Log::error($e->getMessage());
- }
-
- // convert values to integers:
- $result = $this->convertToInteger($result);
+ $this->query->whereIn('transaction_types.type', $types);
- $result['reconciled'] = 1 === (int) $result['reconciled'];
- if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well.
- $tagId = (int) $augumentedJournal['tag_id'];
- $tagDate = null;
- try {
- $tagDate = Carbon::parse($augumentedJournal['tag_date']);
- } catch (InvalidDateException $e) {
- Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
- }
+ return $this;
+ }
- $result['tags'][$tagId] = [
- 'id' => (int) $result['tag_id'],
- 'name' => $result['tag_name'],
- 'date' => $tagDate,
- 'description' => $result['tag_description'],
- ];
- }
+ /**
+ * Set the user object and start the query.
+ *
+ * @param User $user
+ *
+ * @return GroupCollectorInterface
+ */
+ public function setUser(User $user): GroupCollectorInterface
+ {
+ if (null === $this->user) {
+ $this->user = $user;
+ $this->startQuery();
- // also merge attachments:
- if (array_key_exists('attachment_id', $result)) {
- $uploaded = 1 === (int) $result['attachment_uploaded'];
- $attachmentId = (int) $augumentedJournal['attachment_id'];
- if (0 !== $attachmentId && $uploaded) {
- $result['attachments'][$attachmentId] = [
- 'id' => $attachmentId,
- ];
- }
}
- // unset various fields:
- unset($result['tag_id'], $result['tag_name'], $result['tag_date'], $result['tag_description'], $result['tag_latitude'], $result['tag_longitude'], $result['tag_zoom_level']);
- return $result;
+ return $this;
}
/**
- * @param array $groups
- *
- * @return array
+ * Build the query.
*/
- private function parseSums(array $groups): array
+ private function startQuery(): void
{
- /**
- * @var int $groudId
- * @var array $group
- */
- foreach ($groups as $groudId => $group) {
- /** @var array $transaction */
- foreach ($group['transactions'] as $transaction) {
- $currencyId = (int) $transaction['currency_id'];
+ //app('log')->debug('GroupCollector::startQuery');
+ $this->query = $this->user
+ //->transactionGroups()
+ //->leftJoin('transaction_journals', 'transaction_journals.transaction_group_id', 'transaction_groups.id')
+ ->transactionJournals()
+ ->leftJoin('transaction_groups', 'transaction_journals.transaction_group_id', 'transaction_groups.id')
- // set default:
- if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
- $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;
- $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code'];
- $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol'];
- $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places'];
- $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
+ // join source transaction.
+ ->leftJoin(
+ 'transactions as source',
+ function (JoinClause $join) {
+ $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')
+ ->where('source.amount', '<', 0);
}
- $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount'] ?? '0');
-
- if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) {
- $currencyId = (int) $transaction['foreign_currency_id'];
-
- // set default:
- if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
- $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;
- $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code'];
- $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol'];
- $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places'];
- $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
- }
- $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd(
- $groups[$groudId]['sums'][$currencyId]['amount'],
- $transaction['foreign_amount'] ?? '0'
- );
+ )
+ // join destination transaction
+ ->leftJoin(
+ 'transactions as destination',
+ function (JoinClause $join) {
+ $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')
+ ->where('destination.amount', '>', 0);
}
- }
- }
+ )
+ // left join transaction type.
+ ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
+ ->leftJoin('transaction_currencies as currency', 'currency.id', '=', 'source.transaction_currency_id')
+ ->leftJoin('transaction_currencies as foreign_currency', 'foreign_currency.id', '=', 'source.foreign_currency_id')
+ ->whereNull('transaction_groups.deleted_at')
+ ->whereNull('transaction_journals.deleted_at')
+ ->whereNull('source.deleted_at')
+ ->whereNull('destination.deleted_at')
+ ->orderBy('transaction_journals.date', 'DESC')
+ ->orderBy('transaction_journals.order', 'ASC')
+ ->orderBy('transaction_journals.id', 'DESC')
+ ->orderBy('transaction_journals.description', 'DESC')
+ ->orderBy('source.amount', 'DESC');
+ }
- return $groups;
+ /**
+ * Automatically include all stuff required to make API calls work.
+ *
+ * @return GroupCollectorInterface
+ */
+ public function withAPIInformation(): GroupCollectorInterface
+ {
+ // include source + destination account name and type.
+ $this->withAccountInformation()
+ // include category ID + name (if any)
+ ->withCategoryInformation()
+ // include budget ID + name (if any)
+ ->withBudgetInformation()
+ // include bill ID + name (if any)
+ ->withBillInformation();
+
+ return $this;
}
/**
- * @param Collection $collection
- * @return Collection
+ * @inheritDoc
*/
- private function postFilterCollection(Collection $collection): Collection
+ public function withAttachmentInformation(): GroupCollectorInterface
{
- Log::debug('Now in postFilterCollection()');
- $newCollection = new Collection;
- foreach ($collection as $i => $item) {
- Log::debug(sprintf('Now working on item #%d/%d', $i + 1, $collection->count()));
- foreach ($this->postFilters as $func) {
- if (false === $func($i, $item)) {
- // skip other filters, continue to next item.
- Log::debug('Filter returns false, jump to next item.');
- continue 2;
- }
- Log::debug('Filter returns true');
- }
- $newCollection->push($item);
- }
- return $newCollection;
+ $this->fields[] = 'attachments.id as attachment_id';
+ $this->fields[] = 'attachments.uploaded as attachment_uploaded';
+ $this->joinAttachmentTables();
+
+ return $this;
}
}
diff --git a/app/Helpers/Collector/GroupCollectorInterface.php b/app/Helpers/Collector/GroupCollectorInterface.php
index f8ea25d59b..03e4a457d5 100644
--- a/app/Helpers/Collector/GroupCollectorInterface.php
+++ b/app/Helpers/Collector/GroupCollectorInterface.php
@@ -66,6 +66,24 @@ interface GroupCollectorInterface
*/
public function amountMore(string $amount): GroupCollectorInterface;
+ /**
+ * @param string $day
+ * @return GroupCollectorInterface
+ */
+ public function dayAfter(string $day): GroupCollectorInterface;
+
+ /**
+ * @param string $day
+ * @return GroupCollectorInterface
+ */
+ public function dayBefore(string $day): GroupCollectorInterface;
+
+ /**
+ * @param string $day
+ * @return GroupCollectorInterface
+ */
+ public function dayIs(string $day): GroupCollectorInterface;
+
/**
* End of the description must match:
*
@@ -111,6 +129,24 @@ interface GroupCollectorInterface
*/
public function excludeSourceAccounts(Collection $accounts): GroupCollectorInterface;
+ /**
+ * @param string $externalId
+ * @return GroupCollectorInterface
+ */
+ public function externalIdContains(string $externalId): GroupCollectorInterface;
+
+ /**
+ * @param string $externalId
+ * @return GroupCollectorInterface
+ */
+ public function externalIdEnds(string $externalId): GroupCollectorInterface;
+
+ /**
+ * @param string $externalId
+ * @return GroupCollectorInterface
+ */
+ public function externalIdStarts(string $externalId): GroupCollectorInterface;
+
/**
* Ensure the search will find nothing at all, zero results.
*
@@ -151,6 +187,42 @@ interface GroupCollectorInterface
*/
public function hasAttachments(): GroupCollectorInterface;
+ /**
+ * @param string $externalId
+ * @return GroupCollectorInterface
+ */
+ public function internalReferenceContains(string $externalId): GroupCollectorInterface;
+
+ /**
+ * @param string $externalId
+ * @return GroupCollectorInterface
+ */
+ public function internalReferenceEnds(string $externalId): GroupCollectorInterface;
+
+ /**
+ * @param string $externalId
+ * @return GroupCollectorInterface
+ */
+ public function internalReferenceStarts(string $externalId): GroupCollectorInterface;
+
+ /**
+ * @param string $month
+ * @return GroupCollectorInterface
+ */
+ public function monthAfter(string $month): GroupCollectorInterface;
+
+ /**
+ * @param string $month
+ * @return GroupCollectorInterface
+ */
+ public function monthBefore(string $month): GroupCollectorInterface;
+
+ /**
+ * @param string $month
+ * @return GroupCollectorInterface
+ */
+ public function monthIs(string $month): GroupCollectorInterface;
+
/**
* @param string $value
*
@@ -305,38 +377,6 @@ interface GroupCollectorInterface
*/
public function setExternalId(string $externalId): GroupCollectorInterface;
- /**
- * @param string $externalId
- * @return GroupCollectorInterface
- */
- public function externalIdContains(string $externalId): GroupCollectorInterface;
-
- /**
- * @param string $externalId
- * @return GroupCollectorInterface
- */
- public function externalIdStarts(string $externalId): GroupCollectorInterface;
-
- /**
- * @param string $externalId
- * @return GroupCollectorInterface
- */
- public function externalIdEnds(string $externalId): GroupCollectorInterface;
-
- /**
- * Transactions without an external URL
- *
- * @return GroupCollectorInterface
- */
- public function withoutExternalUrl(): GroupCollectorInterface;
-
- /**
- * Transactions with an external URL
- *
- * @return GroupCollectorInterface
- */
- public function withExternalUrl(): GroupCollectorInterface;
-
/**
* Limit results to a specific foreign currency.
*
@@ -437,15 +477,6 @@ interface GroupCollectorInterface
*/
public function setTags(Collection $tags): GroupCollectorInterface;
- /**
- * Only when does not have these tags
- *
- * @param Collection $tags
- *
- * @return GroupCollectorInterface
- */
- public function setWithoutSpecificTags(Collection $tags): GroupCollectorInterface;
-
/**
* Limit the search to one specific transaction group.
*
@@ -482,6 +513,15 @@ interface GroupCollectorInterface
*/
public function setUser(User $user): GroupCollectorInterface;
+ /**
+ * Only when does not have these tags
+ *
+ * @param Collection $tags
+ *
+ * @return GroupCollectorInterface
+ */
+ public function setWithoutSpecificTags(Collection $tags): GroupCollectorInterface;
+
/**
* Either account can be set, but NOT both. This effectively excludes internal transfers.
*
@@ -561,6 +601,13 @@ interface GroupCollectorInterface
*/
public function withCategoryInformation(): GroupCollectorInterface;
+ /**
+ * Transactions with an external URL
+ *
+ * @return GroupCollectorInterface
+ */
+ public function withExternalUrl(): GroupCollectorInterface;
+
/**
* Will include notes.
*
@@ -596,6 +643,13 @@ interface GroupCollectorInterface
*/
public function withoutCategory(): GroupCollectorInterface;
+ /**
+ * Transactions without an external URL
+ *
+ * @return GroupCollectorInterface
+ */
+ public function withoutExternalUrl(): GroupCollectorInterface;
+
/**
* @return GroupCollectorInterface
*/
@@ -606,15 +660,22 @@ interface GroupCollectorInterface
*/
public function withoutTags(): GroupCollectorInterface;
+ /**
+ * @param string $year
+ * @return GroupCollectorInterface
+ */
+ public function yearAfter(string $year): GroupCollectorInterface;
+
+ /**
+ * @param string $year
+ * @return GroupCollectorInterface
+ */
+ public function yearBefore(string $year): GroupCollectorInterface;
+ /**
+ * @param string $year
+ * @return GroupCollectorInterface
+ */
public function yearIs(string $year): GroupCollectorInterface;
- public function monthIs(string $month): GroupCollectorInterface;
- public function dayIs(string $day): GroupCollectorInterface;
- public function yearBefore(string $year): GroupCollectorInterface;
- public function monthBefore(string $month): GroupCollectorInterface;
- public function dayBefore(string $day): GroupCollectorInterface;
- public function yearAfter(string $year): GroupCollectorInterface;
- public function monthAfter(string $month): GroupCollectorInterface;
- public function dayAfter(string $day): GroupCollectorInterface;
}
diff --git a/app/Support/Search/OperatorQuerySearch.php b/app/Support/Search/OperatorQuerySearch.php
index fcd52121df..10de656277 100644
--- a/app/Support/Search/OperatorQuerySearch.php
+++ b/app/Support/Search/OperatorQuerySearch.php
@@ -757,9 +757,18 @@ class OperatorQuerySearch implements SearchInterface
case 'external_id_ends':
$this->collector->externalIdEnds($value);
break;
- case 'internal_reference':
+ case 'internal_reference_is':
$this->collector->setInternalReference($value);
break;
+ case 'internal_reference_contains':
+ $this->collector->internalReferenceContains($value);
+ break;
+ case 'internal_reference_starts':
+ $this->collector->internalReferenceStarts($value);
+ break;
+ case 'internal_reference_ends':
+ $this->collector->internalReferenceEnds($value);
+ break;
}
return true;
diff --git a/config/search.php b/config/search.php
index 3b296746c2..14b04aee37 100644
--- a/config/search.php
+++ b/config/search.php
@@ -31,7 +31,6 @@ return [
'from_account_ends' => ['alias' => true, 'alias_for' => 'source_account_ends', 'needs_context' => true,],
'source_account_starts' => ['alias' => false, 'needs_context' => true,],
'from_account_starts' => ['alias' => true, 'alias_for' => 'source_account_starts', 'needs_context' => true,],
-
'source_account_nr_is' => ['alias' => false, 'needs_context' => true,],
'from_account_nr_is' => ['alias' => true, 'alias_for' => 'source_account_nr_is', 'needs_context' => true,],
'source_account_nr_contains' => ['alias' => false, 'needs_context' => true,],
@@ -40,7 +39,6 @@ return [
'from_account_nr_ends' => ['alias' => true, 'alias_for' => 'source_account_nr_ends', 'needs_context' => true,],
'source_account_nr_starts' => ['alias' => false, 'needs_context' => true,],
'from_account_nr_starts' => ['alias' => true, 'alias_for' => 'source_account_nr_starts', 'needs_context' => true,],
-
'destination_account_is' => ['alias' => false, 'needs_context' => true,],
'to_account_is' => ['alias' => true, 'alias_for' => 'destination_account_is', 'needs_context' => true,],
'destination_account_contains' => ['alias' => false, 'needs_context' => true,],
@@ -51,7 +49,6 @@ return [
'to_account_ends' => ['alias' => true, 'alias_for' => 'destination_account_ends', 'needs_context' => true,],
'destination_account_starts' => ['alias' => false, 'needs_context' => true,],
'to_account_starts' => ['alias' => true, 'alias_for' => 'destination_account_starts', 'needs_context' => true,],
-
'destination_account_nr_is' => ['alias' => false, 'needs_context' => true,],
'to_account_nr_is' => ['alias' => true, 'alias_for' => 'destination_account_nr_is', 'needs_context' => true,],
'destination_account_nr_contains' => ['alias' => false, 'needs_context' => true,],
@@ -60,17 +57,14 @@ return [
'to_account_nr_ends' => ['alias' => true, 'alias_for' => 'destination_account_nr_ends', 'needs_context' => true,],
'destination_account_nr_starts' => ['alias' => false, 'needs_context' => true,],
'to_account_nr_starts' => ['alias' => true, 'alias_for' => 'destination_account_nr_starts', 'needs_context' => true,],
-
'account_is' => ['alias' => false, 'needs_context' => true,],
'account_contains' => ['alias' => false, 'needs_context' => true,],
'account_ends' => ['alias' => false, 'needs_context' => true,],
'account_starts' => ['alias' => false, 'needs_context' => true,],
-
'account_nr_is' => ['alias' => false, 'needs_context' => true,],
'account_nr_contains' => ['alias' => false, 'needs_context' => true,],
'account_nr_ends' => ['alias' => false, 'needs_context' => true,],
'account_nr_starts' => ['alias' => false, 'needs_context' => true,],
-
'category_is' => ['alias' => false, 'needs_context' => true,],
'category_contains' => ['alias' => false, 'needs_context' => true,],
'category' => ['alias' => true, 'alias_for' => 'category_contains', 'needs_context' => true,],
@@ -86,19 +80,19 @@ return [
'bill' => ['alias' => true, 'alias_for' => 'bill_contains', 'needs_context' => true,],
'bill_ends' => ['alias' => false, 'needs_context' => true,],
'bill_starts' => ['alias' => false, 'needs_context' => true,],
-
'external_id_is' => ['alias' => false, 'needs_context' => true,],
'external_id_contains' => ['alias' => false, 'needs_context' => true,],
'external_id' => ['alias' => true, 'alias_for' => 'external_id_contains', 'needs_context' => true,],
'external_id_ends' => ['alias' => false, 'needs_context' => true,],
'external_id_starts' => ['alias' => false, 'needs_context' => true,],
- // TODO here we are!
'internal_reference_is' => ['alias' => false, 'needs_context' => true,],
'internal_reference_contains' => ['alias' => false, 'needs_context' => true,],
'internal_reference' => ['alias' => true, 'alias_for' => 'internal_reference_contains', 'needs_context' => true,],
'internal_reference_ends' => ['alias' => false, 'needs_context' => true,],
'internal_reference_starts' => ['alias' => false, 'needs_context' => true,],
+
+ // TODO here we are.
'external_url_is' => ['alias' => false, 'needs_context' => true,],
'external_url_contains' => ['alias' => false, 'needs_context' => true,],
'external_url' => ['alias' => true, 'alias_for' => 'external_url_contains', 'needs_context' => true,],