Files
firefly-iii/app/Services/Internal/Support/JournalServiceTrait.php

439 lines
15 KiB
PHP
Raw Normal View History

2018-02-23 15:12:47 +01:00
<?php
/**
* JournalServiceTrait.php
2020-02-16 13:56:35 +01:00
* Copyright (c) 2019 james@firefly-iii.org
2018-02-23 15:12:47 +01:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2018-02-23 15:12:47 +01: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.
2018-02-23 15:12:47 +01:00
*
* This program is distributed in the hope that it will be useful,
2018-02-23 15:12:47 +01: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.
2018-02-23 15:12:47 +01: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/>.
2018-02-23 15:12:47 +01:00
*/
declare(strict_types=1);
namespace FireflyIII\Services\Internal\Support;
2018-09-06 07:38:51 +02:00
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\AccountMetaFactory;
2018-02-23 15:12:47 +01:00
use FireflyIII\Factory\TagFactory;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
2018-02-23 15:12:47 +01:00
use FireflyIII\Models\Note;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Support\NullArrayObject;
2018-06-02 18:19:35 +02:00
use Log;
2018-02-23 15:12:47 +01:00
/**
* Trait JournalServiceTrait
*
*/
trait JournalServiceTrait
{
2020-07-26 07:57:48 +02:00
private AccountRepositoryInterface $accountRepository;
private BudgetRepositoryInterface $budgetRepository;
private CategoryRepositoryInterface $categoryRepository;
private TagFactory $tagFactory;
2019-03-05 17:26:49 +01:00
/**
* @param string $transactionType
* @param string $direction
* @param array $data
2019-03-05 17:26:49 +01:00
*
* @return Account
2019-07-31 16:53:09 +02:00
* @codeCoverageIgnore
2020-10-04 17:11:59 +02:00
* @throws FireflyException
2019-03-05 17:26:49 +01:00
*/
protected function getAccount(string $transactionType, string $direction, array $data): Account
2019-03-05 17:26:49 +01:00
{
// some debug logging:
Log::debug(sprintf('Now in getAccount(%s)', $direction), $data);
// final result:
$result = null;
2019-03-05 17:26:49 +01:00
// expected type of source account, in order of preference
/** @var array $array */
$array = config('firefly.expected_source_types');
$expectedTypes = $array[$direction];
unset($array);
// and now try to find it, based on the type of transaction.
2020-03-19 14:28:38 +01:00
$message = 'Based on the fact that the transaction is a %s, the %s account should be in: %s. Direction is %s.';
Log::debug(sprintf($message, $transactionType, $direction, implode(', ', $expectedTypes[$transactionType]), $direction));
2020-03-19 14:28:38 +01:00
$result = $this->findAccountById($data, $expectedTypes[$transactionType]);
$result = $this->findAccountByName($result, $data, $expectedTypes[$transactionType]);
$result = $this->findAccountByIban($result, $data, $expectedTypes[$transactionType]);
2021-04-22 06:18:46 +02:00
$result = $this->findAccountByNumber($result, $data, $expectedTypes[$transactionType]);
2020-03-19 14:28:38 +01:00
$result = $this->createAccount($result, $data, $expectedTypes[$transactionType][0]);
2021-03-13 14:33:48 +01:00
2020-10-23 19:11:25 +02:00
return $this->getCashAccount($result, $data, $expectedTypes[$transactionType]);
2019-03-05 17:26:49 +01:00
}
2020-03-19 14:28:38 +01:00
/**
* @param array $data
* @param array $types
*
* @return Account|null
*/
private function findAccountById(array $data, array $types): ?Account
{
$search = null;
// first attempt, find by ID.
if (null !== $data['id']) {
$search = $this->accountRepository->findNull($data['id']);
if (null !== $search && in_array($search->accountType->type, $types, true)) {
Log::debug(
sprintf('Found "account_id" object: #%d, "%s" of type %s', $search->id, $search->name, $search->accountType->type)
);
}
}
2020-03-19 14:28:38 +01:00
return $search;
}
/**
* @param Account|null $account
* @param array $data
* @param array $types
*
* @return Account|null
*/
private function findAccountByName(?Account $account, array $data, array $types): ?Account
{
// second attempt, find by name.
if (null === $account && null !== $data['name']) {
Log::debug('Found nothing by account ID.');
// find by preferred type.
$source = $this->accountRepository->findByName($data['name'], [$types[0]]);
// or any expected type.
$source = $source ?? $this->accountRepository->findByName($data['name'], $types);
if (null !== $source) {
Log::debug(sprintf('Found "account_name" object: #%d, %s', $source->id, $source->name));
$account = $source;
}
}
return $account;
}
/**
* @param Account|null $account
* @param array $data
* @param array $types
*
* @return Account|null
*/
private function findAccountByIban(?Account $account, array $data, array $types): ?Account
{
// third attempt, find by IBAN
if (null === $account && null !== $data['iban']) {
Log::debug(sprintf('Found nothing by account iban "%s".', $data['iban']));
2020-03-19 14:28:38 +01:00
// find by preferred type.
$source = $this->accountRepository->findByIbanNull($data['iban'], [$types[0]]);
// or any expected type.
$source = $source ?? $this->accountRepository->findByIbanNull($data['iban'], $types);
if (null !== $source) {
Log::debug(sprintf('Found "account_iban" object: #%d, %s', $source->id, $source->name));
$account = $source;
}
}
return $account;
}
/**
2021-04-22 06:18:46 +02:00
* @param Account|null $account
* @param array $data
* @param array $types
*
* @return Account|null
*/
private function findAccountByNumber(?Account $account, array $data, array $types): ?Account
{
// third attempt, find by account number
if (null === $account && null !== $data['number']) {
Log::debug(sprintf('Searching for account number "%s".', $data['number']));
// find by preferred type.
$source = $this->accountRepository->findByAccountNumber($data['number'], [$types[0]]);
// or any expected type.
$source = $source ?? $this->accountRepository->findByAccountNumber($data['iban'], $types);
if (null !== $source) {
Log::debug(sprintf('Found account: #%d, %s', $source->id, $source->name));
$account = $source;
}
}
return $account;
}
/**
2020-03-19 14:28:38 +01:00
* @param Account|null $account
* @param array $data
* @param string $preferredType
*
* @return Account
2020-10-04 17:11:59 +02:00
* @throws FireflyException
2020-03-19 14:28:38 +01:00
*/
2021-04-08 11:21:20 +02:00
private function createAccount(?Account $account, array $data, string $preferredType): ?Account
2020-03-19 14:28:38 +01:00
{
2020-04-14 17:23:58 +02:00
Log::debug('Now in createAccount()', $data);
2020-03-19 14:28:38 +01:00
// return new account.
if (null !== $account) {
Log::debug(
sprintf(
'Was also given %s account #%d ("%s") so will simply return that.',
$account->accountType->type, $account->id, $account->name
)
);
}
2020-03-19 14:28:38 +01:00
if (null === $account) {
// final attempt, create it.
if (AccountType::ASSET === $preferredType) {
2021-04-06 18:36:37 +02:00
throw new FireflyException(sprintf('TransactionFactory: Cannot create asset account with these values: %s',json_encode($data)));
2020-03-19 14:28:38 +01:00
}
// fix name of account if only IBAN is given:
2021-03-13 14:33:48 +01:00
if ('' === (string)$data['name'] && '' !== (string)$data['iban']) {
Log::debug(sprintf('Account name is now IBAN ("%s")', $data['iban']));
$data['name'] = $data['iban'];
}
2021-04-08 11:21:20 +02:00
// fix name of account if only number is given:
if ('' === (string)$data['name'] && '' !== (string)$data['number']) {
Log::debug(sprintf('Account name is now account number ("%s")', $data['number']));
$data['name'] = $data['number'];
}
// if name is still NULL, return NULL.
if(null === $data['name']) {
return null;
}
$data['name'] = $data['name'] ?? '(no name)';
2020-03-19 14:28:38 +01:00
2020-03-21 09:35:25 +01:00
$account = $this->accountRepository->store(
2020-03-19 14:28:38 +01:00
[
2021-04-05 21:52:55 +02:00
'account_type_id' => null,
'account_type_name' => $preferredType,
'name' => $data['name'],
'virtual_balance' => null,
'active' => true,
'iban' => $data['iban'],
'currency_id' => $data['currency_id'] ?? null,
'order' => $this->accountRepository->maxOrder($preferredType),
2020-03-19 14:28:38 +01:00
]
);
// store BIC
if (null !== $data['bic']) {
/** @var AccountMetaFactory $metaFactory */
$metaFactory = app(AccountMetaFactory::class);
2020-04-10 07:29:15 +02:00
$metaFactory->create(['account_id' => $account->id, 'name' => 'BIC', 'data' => $data['bic']]);
2020-03-19 14:28:38 +01:00
}
// store account number
if (null !== $data['number']) {
/** @var AccountMetaFactory $metaFactory */
$metaFactory = app(AccountMetaFactory::class);
2021-03-30 06:32:42 +02:00
$metaFactory->create(['account_id' => $account->id, 'name' => 'account_number', 'data' => $data['number']]);
2020-03-19 14:28:38 +01:00
}
2020-04-14 17:23:58 +02:00
2020-03-19 14:28:38 +01:00
}
return $account;
}
2021-03-15 10:31:11 +01:00
/**
* @param Account|null $account
* @param array $data
* @param array $types
*
* @return Account|null
*/
private function getCashAccount(?Account $account, array $data, array $types): ?Account
{
// return cash account.
if (null === $account && null === $data['name']
&& in_array(AccountType::CASH, $types, true)) {
$account = $this->accountRepository->getCashAccount();
}
return $account;
}
/**
* @param string $amount
*
* @return string
* @throws FireflyException
* @codeCoverageIgnore
*/
protected function getAmount(string $amount): string
{
if ('' === $amount) {
throw new FireflyException(sprintf('The amount cannot be an empty string: "%s"', $amount));
}
if (0 === bccomp('0', $amount)) {
throw new FireflyException(sprintf('The amount seems to be zero: "%s"', $amount));
}
return $amount;
}
/**
* @param string|null $amount
*
* @return string
* @codeCoverageIgnore
*/
protected function getForeignAmount(?string $amount): ?string
{
if (null === $amount) {
Log::debug('No foreign amount info in array. Return NULL');
return null;
}
if ('' === $amount) {
Log::debug('Foreign amount is empty string, return NULL.');
return null;
}
if (0 === bccomp('0', $amount)) {
Log::debug('Foreign amount is 0.0, return NULL.');
return null;
}
Log::debug(sprintf('Foreign amount is %s', $amount));
return $amount;
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $data
*
* @codeCoverageIgnore
*/
protected function storeBudget(TransactionJournal $journal, NullArrayObject $data): void
{
if (TransactionType::WITHDRAWAL !== $journal->transactionType->type) {
$journal->budgets()->sync([]);
return;
}
$budget = $this->budgetRepository->findBudget($data['budget_id'], $data['budget_name']);
if (null !== $budget) {
Log::debug(sprintf('Link budget #%d to journal #%d', $budget->id, $journal->id));
$journal->budgets()->sync([$budget->id]);
return;
}
// if the budget is NULL, sync empty.
$journal->budgets()->sync([]);
}
/**
* @param TransactionJournal $journal
* @param NullArrayObject $data
*
* @codeCoverageIgnore
*/
protected function storeCategory(TransactionJournal $journal, NullArrayObject $data): void
{
$category = $this->categoryRepository->findCategory($data['category_id'], $data['category_name']);
if (null !== $category) {
Log::debug(sprintf('Link category #%d to journal #%d', $category->id, $journal->id));
$journal->categories()->sync([$category->id]);
return;
}
// if the category is NULL, sync empty.
$journal->categories()->sync([]);
}
/**
* @param TransactionJournal $journal
* @param string $notes
*
* @codeCoverageIgnore
*/
protected function storeNotes(TransactionJournal $journal, ?string $notes): void
{
$notes = (string)$notes;
$note = $journal->notes()->first();
if ('' !== $notes) {
if (null === $note) {
$note = new Note;
$note->noteable()->associate($journal);
}
$note->text = $notes;
$note->save();
Log::debug(sprintf('Stored notes for journal #%d', $journal->id));
return;
}
if ('' === $notes && null !== $note) {
// try to delete existing notes.
try {
$note->delete();
2021-04-06 18:36:37 +02:00
} catch (Exception $e) { // @phpstan-ignore-line
// @ignoreException
2021-03-15 10:31:11 +01:00
}
}
}
/**
* Link tags to journal.
*
* @param TransactionJournal $journal
* @param array $tags
*
* @codeCoverageIgnore
*/
protected function storeTags(TransactionJournal $journal, ?array $tags): void
{
Log::debug('Now in storeTags()', $tags ?? []);
$this->tagFactory->setUser($journal->user);
$set = [];
if (!is_array($tags)) {
Log::debug('Tags is not an array, break.');
return;
}
Log::debug('Start of loop.');
foreach ($tags as $string) {
$string = (string)$string;
Log::debug(sprintf('Now at tag "%s"', $string));
if ('' !== $string) {
$tag = $this->tagFactory->findOrCreate($string);
if (null !== $tag) {
$set[] = $tag->id;
}
}
}
Log::debug('End of loop.');
Log::debug(sprintf('Total nr. of tags: %d', count($tags)), $tags);
$journal->tags()->sync($set);
Log::debug('Done!');
}
2018-03-05 19:35:58 +01:00
}