firefly-iii/app/Repositories/TransactionGroup/TransactionGroupRepository.php

508 lines
17 KiB
PHP
Raw Normal View History

2019-03-25 09:14:09 -05:00
<?php
/**
* TransactionGroupRepository.php
2020-02-16 07:00:57 -06:00
* Copyright (c) 2019 james@firefly-iii.org
2019-03-25 09:14:09 -05:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2019-03-25 09:14:09 -05:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
2019-03-25 09:14:09 -05:00
*
* This program is distributed in the hope that it will be useful,
2019-03-25 09:14:09 -05:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2019-03-25 09:14:09 -05:00
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2019-03-25 09:14:09 -05:00
*/
declare(strict_types=1);
namespace FireflyIII\Repositories\TransactionGroup;
2019-03-25 09:14:09 -05:00
use Carbon\Carbon;
use DB;
use Exception;
use FireflyIII\Exceptions\DuplicateTransactionException;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\TransactionGroupFactory;
2019-04-18 13:05:40 -05:00
use FireflyIII\Models\AccountMeta;
2019-04-16 09:20:46 -05:00
use FireflyIII\Models\Attachment;
2021-02-16 03:19:20 -06:00
use FireflyIII\Models\Location;
2019-03-25 09:14:09 -05:00
use FireflyIII\Models\Note;
2019-04-18 13:05:40 -05:00
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionGroup;
2019-03-25 09:14:09 -05:00
use FireflyIII\Models\TransactionJournal;
2019-04-16 09:20:46 -05:00
use FireflyIII\Models\TransactionJournalLink;
2019-04-18 13:05:40 -05:00
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface;
2019-07-31 23:22:07 -05:00
use FireflyIII\Services\Internal\Destroy\TransactionGroupDestroyService;
use FireflyIII\Services\Internal\Update\GroupUpdateService;
2019-03-25 09:14:09 -05:00
use FireflyIII\Support\NullArrayObject;
2019-08-27 00:26:32 -05:00
use FireflyIII\User;
2023-02-19 01:43:28 -06:00
use Illuminate\Contracts\Auth\Authenticatable;
2019-04-16 09:20:46 -05:00
use Illuminate\Database\Eloquent\Builder;
2020-04-07 11:19:29 -05:00
use Illuminate\Support\Collection;
2022-12-29 12:42:26 -06:00
use JsonException;
2020-02-22 04:05:16 -06:00
use Log;
2019-03-25 09:14:09 -05:00
/**
* Class TransactionGroupRepository
*/
2019-08-27 00:26:32 -05:00
class TransactionGroupRepository implements TransactionGroupRepositoryInterface
2019-03-25 09:14:09 -05:00
{
2020-11-08 07:13:21 -06:00
private User $user;
2019-03-25 09:14:09 -05:00
2022-03-29 07:59:58 -05:00
/**
* @inheritDoc
*/
public function countAttachments(int $journalId): int
{
/** @var TransactionJournal $journal */
$journal = $this->user->transactionJournals()->find($journalId);
return $journal->attachments()->count();
}
2019-08-27 00:26:32 -05:00
/**
2022-12-29 12:42:26 -06:00
* Find a transaction group by its ID.
*
* @param int $groupId
*
* @return TransactionGroup|null
*/
public function find(int $groupId): ?TransactionGroup
{
return $this->user->transactionGroups()->find($groupId);
}
/**
* @param TransactionGroup $group
2019-08-27 00:26:32 -05:00
*/
public function destroy(TransactionGroup $group): void
{
2023-01-05 12:05:23 -06:00
Log::debug(sprintf('Now in %s', __METHOD__));
2022-10-30 08:24:37 -05:00
$service = new TransactionGroupDestroyService();
2019-08-27 00:26:32 -05:00
$service->destroy($group);
}
2020-02-07 23:42:07 -06:00
/**
* @inheritDoc
*/
public function expandGroup(TransactionGroup $group): array
{
$result = $group->toArray();
$result['transaction_journals'] = [];
/** @var TransactionJournal $journal */
foreach ($group->transactionJournals as $journal) {
$result['transaction_journals'][] = $this->expandJournal($journal);
}
return $result;
}
2022-03-29 07:59:58 -05:00
/**
2022-12-29 12:42:26 -06:00
* @param TransactionJournal $journal
2022-03-29 07:59:58 -05:00
*
* @return array
*/
private function expandJournal(TransactionJournal $journal): array
{
$array = $journal->toArray();
$array['transactions'] = [];
$array['meta'] = $journal->transactionJournalMeta->toArray();
$array['tags'] = $journal->tags->toArray();
$array['categories'] = $journal->categories->toArray();
$array['budgets'] = $journal->budgets->toArray();
$array['notes'] = $journal->notes->toArray();
$array['locations'] = [];
$array['attachments'] = $journal->attachments->toArray();
$array['links'] = [];
$array['piggy_bank_events'] = $journal->piggyBankEvents->toArray();
/** @var Transaction $transaction */
foreach ($journal->transactions as $transaction) {
$array['transactions'][] = $this->expandTransaction($transaction);
}
return $array;
}
/**
2022-12-29 12:42:26 -06:00
* @param Transaction $transaction
2022-03-29 07:59:58 -05:00
*
* @return array
*/
private function expandTransaction(Transaction $transaction): array
{
$array = $transaction->toArray();
$array['account'] = $transaction->account->toArray();
$array['budgets'] = [];
$array['categories'] = [];
foreach ($transaction->categories as $category) {
$array['categories'][] = $category->toArray();
}
foreach ($transaction->budgets as $budget) {
$array['budgets'][] = $budget->toArray();
}
return $array;
}
2019-04-16 09:20:46 -05:00
/**
* Return all attachments for all journals in the group.
*
2022-12-29 12:42:26 -06:00
* @param TransactionGroup $group
2019-04-16 09:20:46 -05:00
*
* @return array
*/
public function getAttachments(TransactionGroup $group): array
{
$repository = app(AttachmentRepositoryInterface::class);
$repository->setUser($this->user);
2019-04-16 09:20:46 -05:00
$journals = $group->transactionJournals->pluck('id')->toArray();
$set = Attachment::whereIn('attachable_id', $journals)
->where('attachable_type', TransactionJournal::class)
2021-05-01 13:04:58 -05:00
->where('uploaded', true)
2019-04-16 09:20:46 -05:00
->whereNull('deleted_at')->get();
$result = [];
/** @var Attachment $attachment */
foreach ($set as $attachment) {
2022-12-29 12:42:26 -06:00
$journalId = (int)$attachment->attachable_id;
2019-04-18 13:05:40 -05:00
$result[$journalId] = $result[$journalId] ?? [];
2019-04-16 09:20:46 -05:00
$current = $attachment->toArray();
$current['file_exists'] = true;
2022-03-29 07:59:58 -05:00
$current['notes'] = $repository->getNoteText($attachment);
2022-12-31 06:32:42 -06:00
// already determined that this attachable is a TransactionJournal.
$current['journal_title'] = $attachment->attachable->description; // @phpstan-ignore-line
2019-04-18 13:05:40 -05:00
$result[$journalId][] = $current;
2019-04-16 09:20:46 -05:00
}
return $result;
}
2022-12-29 12:42:26 -06:00
/**
2023-02-19 01:43:28 -06:00
* @param User|Authenticatable|null $user
2022-12-29 12:42:26 -06:00
*/
2023-02-19 01:43:28 -06:00
public function setUser(User|Authenticatable|null $user): void
2022-12-29 12:42:26 -06:00
{
2023-02-19 04:16:15 -06:00
if (null !== $user) {
2023-02-19 01:43:28 -06:00
$this->user = $user;
}
2022-12-29 12:42:26 -06:00
}
/**
* Get the note text for a journal (by ID).
*
* @param int $journalId
*
* @return string|null
*/
public function getNoteText(int $journalId): ?string
{
/** @var Note|null $note */
$note = Note::where('noteable_id', $journalId)
->where('noteable_type', TransactionJournal::class)
->first();
if (null === $note) {
return null;
}
return $note->text;
}
2019-04-16 09:20:46 -05:00
/**
* Return all journal links for all journals in the group.
*
2022-12-29 12:42:26 -06:00
* @param TransactionGroup $group
2019-04-16 09:20:46 -05:00
*
* @return array
*/
public function getLinks(TransactionGroup $group): array
{
$return = [];
$journals = $group->transactionJournals->pluck('id')->toArray();
2022-10-30 08:24:37 -05:00
$set = TransactionJournalLink::where(
2022-10-30 23:53:36 -05:00
static function (Builder $q) use ($journals) {
$q->whereIn('source_id', $journals);
$q->orWhereIn('destination_id', $journals);
}
)
2022-12-29 12:42:26 -06:00
->with(['source', 'destination', 'source.transactions'])
->leftJoin('link_types', 'link_types.id', '=', 'journal_links.link_type_id')
->get(['journal_links.*', 'link_types.inward', 'link_types.outward', 'link_types.editable']);
2019-04-16 09:20:46 -05:00
/** @var TransactionJournalLink $entry */
foreach ($set as $entry) {
$journalId = in_array($entry->source_id, $journals, true) ? $entry->source_id : $entry->destination_id;
$return[$journalId] = $return[$journalId] ?? [];
2019-04-18 13:05:40 -05:00
2022-12-31 06:32:42 -06:00
// phpstan: the editable field is provided by the query.
2019-04-16 09:20:46 -05:00
if ($journalId === $entry->source_id) {
2019-04-18 13:05:40 -05:00
$amount = $this->getFormattedAmount($entry->destination);
$foreignAmount = $this->getFormattedForeignAmount($entry->destination);
2019-04-16 09:20:46 -05:00
$return[$journalId][] = [
2019-07-19 23:47:34 -05:00
'id' => $entry->id,
2019-04-18 13:05:40 -05:00
'link' => $entry->outward,
'group' => $entry->destination->transaction_group_id,
'description' => $entry->destination->description,
2022-12-31 06:32:42 -06:00
'editable' => 1 === (int)$entry->editable, // @phpstan-ignore-line
2019-04-18 13:05:40 -05:00
'amount' => $amount,
'foreign_amount' => $foreignAmount,
2019-04-16 09:20:46 -05:00
];
}
if ($journalId === $entry->destination_id) {
2019-04-18 13:05:40 -05:00
$amount = $this->getFormattedAmount($entry->source);
$foreignAmount = $this->getFormattedForeignAmount($entry->source);
2019-04-16 09:20:46 -05:00
$return[$journalId][] = [
2019-07-19 23:47:34 -05:00
'id' => $entry->id,
2019-04-18 13:05:40 -05:00
'link' => $entry->inward,
'group' => $entry->source->transaction_group_id,
'description' => $entry->source->description,
2022-12-31 06:32:42 -06:00
'editable' => 1 === (int)$entry->editable, // @phpstan-ignore-line
2019-04-18 13:05:40 -05:00
'amount' => $amount,
'foreign_amount' => $foreignAmount,
2019-04-16 09:20:46 -05:00
];
}
}
return $return;
}
2022-03-29 07:59:58 -05:00
/**
2022-12-29 12:42:26 -06:00
* @param TransactionJournal $journal
2022-03-29 07:59:58 -05:00
*
* @return string
*/
private function getFormattedAmount(TransactionJournal $journal): string
{
/** @var Transaction $transaction */
$transaction = $journal->transactions->first();
$currency = $transaction->transactionCurrency;
$type = $journal->transactionType->type;
$amount = app('steam')->positive($transaction->amount);
$return = '';
if (TransactionType::WITHDRAWAL === $type) {
$return = app('amount')->formatAnything($currency, app('steam')->negative($amount));
}
if (TransactionType::WITHDRAWAL !== $type) {
$return = app('amount')->formatAnything($currency, $amount);
}
return $return;
}
/**
2022-12-29 12:42:26 -06:00
* @param TransactionJournal $journal
2022-03-29 07:59:58 -05:00
*
* @return string
*/
private function getFormattedForeignAmount(TransactionJournal $journal): string
{
/** @var Transaction $transaction */
$transaction = $journal->transactions->first();
2022-07-25 12:43:47 -05:00
if (null === $transaction->foreign_amount || '' === $transaction->foreign_amount) {
return '';
}
if (0 === bccomp('0', $transaction->foreign_amount)) {
2022-03-29 07:59:58 -05:00
return '';
}
$currency = $transaction->foreignCurrency;
$type = $journal->transactionType->type;
$amount = app('steam')->positive($transaction->foreign_amount);
$return = '';
if (TransactionType::WITHDRAWAL === $type) {
$return = app('amount')->formatAnything($currency, app('steam')->negative($amount));
}
if (TransactionType::WITHDRAWAL !== $type) {
$return = app('amount')->formatAnything($currency, $amount);
}
return $return;
}
2021-03-11 23:20:01 -06:00
/**
* @inheritDoc
*/
public function getLocation(int $journalId): ?Location
{
/** @var TransactionJournal $journal */
$journal = $this->user->transactionJournals()->find($journalId);
return $journal->locations()->first();
}
2019-03-25 09:14:09 -05:00
/**
* Return object with all found meta field things as Carbon objects.
*
2022-12-29 12:42:26 -06:00
* @param int $journalId
* @param array $fields
2019-03-25 09:14:09 -05:00
*
* @return NullArrayObject
* @throws Exception
*/
public function getMetaDateFields(int $journalId, array $fields): NullArrayObject
{
2022-10-30 08:24:37 -05:00
$query = DB::table('journal_meta')
2022-12-29 12:42:26 -06:00
->where('transaction_journal_id', $journalId)
->whereIn('name', $fields)
->whereNull('deleted_at')
->get(['name', 'data']);
2019-03-25 09:14:09 -05:00
$return = [];
foreach ($query as $row) {
2020-06-21 12:16:21 -05:00
$return[$row->name] = new Carbon(json_decode($row->data, true, 512, JSON_THROW_ON_ERROR));
2019-03-25 09:14:09 -05:00
}
return new NullArrayObject($return);
}
/**
* Return object with all found meta field things.
*
2022-12-29 12:42:26 -06:00
* @param int $journalId
* @param array $fields
2019-03-25 09:14:09 -05:00
*
* @return NullArrayObject
*/
public function getMetaFields(int $journalId, array $fields): NullArrayObject
{
2022-10-30 08:24:37 -05:00
$query = DB::table('journal_meta')
2022-12-29 12:42:26 -06:00
->where('transaction_journal_id', $journalId)
->whereIn('name', $fields)
->whereNull('deleted_at')
->get(['name', 'data']);
2019-03-25 09:14:09 -05:00
$return = [];
foreach ($query as $row) {
$return[$row->name] = json_decode($row->data);
}
return new NullArrayObject($return);
}
2019-04-16 09:20:46 -05:00
/**
* Return all piggy bank events for all journals in the group.
*
2022-12-29 12:42:26 -06:00
* @param TransactionGroup $group
2019-04-16 09:20:46 -05:00
*
* @return array
2021-05-24 01:50:17 -05:00
* @throws FireflyException
2022-12-29 12:42:26 -06:00
* @throws JsonException
2019-04-16 09:20:46 -05:00
*/
public function getPiggyEvents(TransactionGroup $group): array
{
2019-04-18 13:05:40 -05:00
$return = [];
$journals = $group->transactionJournals->pluck('id')->toArray();
2021-04-06 22:55:51 -05:00
$currency = app('amount')->getDefaultCurrencyByUser($this->user);
2022-10-30 08:24:37 -05:00
$data = PiggyBankEvent::whereIn('transaction_journal_id', $journals)
2022-12-29 12:42:26 -06:00
->with('piggyBank', 'piggyBank.account')
->get(['piggy_bank_events.*']);
2019-04-18 13:05:40 -05:00
/** @var PiggyBankEvent $row */
foreach ($data as $row) {
2021-03-11 23:20:01 -06:00
if (null === $row->piggyBank) {
2020-06-27 02:56:38 -05:00
continue;
}
2019-04-18 13:05:40 -05:00
// get currency preference.
2022-10-30 08:24:37 -05:00
$currencyPreference = AccountMeta::where('account_id', $row->piggyBank->account_id)
2022-12-29 12:42:26 -06:00
->where('name', 'currency_id')
->first();
2019-04-18 13:05:40 -05:00
if (null !== $currencyPreference) {
$currency = TransactionCurrency::where('id', $currencyPreference->data)->first();
}
if (null === $currencyPreference) {
$currencyCode = app('preferences')->getForUser($this->user, 'currencyPreference', 'EUR')->data;
$currency = TransactionCurrency::where('code', $currencyCode)->first();
}
2022-12-29 12:42:26 -06:00
$journalId = (int)$row->transaction_journal_id;
2019-04-18 13:05:40 -05:00
$return[$journalId] = $return[$journalId] ?? [];
$return[$journalId][] = [
2019-07-19 23:47:34 -05:00
'piggy' => $row->piggyBank->name,
2019-04-18 13:05:40 -05:00
'piggy_id' => $row->piggy_bank_id,
2019-07-19 23:47:34 -05:00
'amount' => app('amount')->formatAnything($currency, $row->amount),
2019-04-18 13:05:40 -05:00
];
}
return $return;
2019-04-16 09:20:46 -05:00
}
2021-03-11 23:20:01 -06:00
/**
* @inheritDoc
*/
public function getTagObjects(int $journalId): Collection
{
/** @var TransactionJournal $journal */
$journal = $this->user->transactionJournals()->find($journalId);
return $journal->tags()->get();
}
2019-03-25 09:14:09 -05:00
/**
* Get the tags for a journal (by ID).
*
2022-12-29 12:42:26 -06:00
* @param int $journalId
2019-03-25 09:14:09 -05:00
*
* @return array
*/
public function getTags(int $journalId): array
{
2022-10-30 08:24:37 -05:00
$result = DB::table('tag_transaction_journal')
2022-12-29 12:42:26 -06:00
->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id')
->where('tag_transaction_journal.transaction_journal_id', $journalId)
->orderBy('tags.tag', 'ASC')
->get(['tags.tag']);
2019-03-25 09:14:09 -05:00
return $result->pluck('tag')->toArray();
}
/**
2022-12-29 12:42:26 -06:00
* @param array $data
*
* @return TransactionGroup
* @throws DuplicateTransactionException
2020-03-11 23:06:42 -05:00
* @throws FireflyException
*/
public function store(array $data): TransactionGroup
{
/** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class);
$factory->setUser($this->user);
2020-02-22 04:05:16 -06:00
try {
return $factory->create($data);
} catch (DuplicateTransactionException $e) {
2022-10-30 08:44:49 -05:00
app('log')->warning('Group repository caught group factory with a duplicate exception!');
throw new DuplicateTransactionException($e->getMessage(), 0, $e);
2021-03-11 23:20:01 -06:00
} catch (FireflyException $e) {
2022-10-30 08:44:49 -05:00
app('log')->warning('Group repository caught group factory with an exception!');
2020-03-11 23:06:42 -05:00
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e);
2020-02-22 04:05:16 -06:00
}
}
/**
2022-12-29 12:42:26 -06:00
* @param TransactionGroup $transactionGroup
* @param array $data
*
* @return TransactionGroup
*
* @throws FireflyException
*/
public function update(TransactionGroup $transactionGroup, array $data): TransactionGroup
{
/** @var GroupUpdateService $service */
2019-08-27 00:26:32 -05:00
$service = app(GroupUpdateService::class);
2019-08-12 09:54:48 -05:00
return $service->update($transactionGroup, $data);
}
2019-08-17 05:09:03 -05:00
}