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

349 lines
12 KiB
PHP
Raw Normal View History

2018-02-21 20:34:24 +01:00
<?php
/**
* AccountServiceTrait.php
* Copyright (c) 2018 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Services\Internal\Support;
2019-02-16 08:05:48 +01:00
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\AccountMetaFactory;
2019-06-22 10:25:34 +02:00
use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Factory\TransactionGroupFactory;
2018-02-21 20:34:24 +01:00
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Note;
2019-06-22 10:25:34 +02:00
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionGroup;
2019-06-22 10:25:34 +02:00
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Services\Internal\Destroy\TransactionGroupDestroyService;
2018-02-21 20:34:24 +01:00
use Log;
use Validator;
/**
* Trait AccountServiceTrait
*
*/
trait AccountServiceTrait
{
/** @var AccountRepositoryInterface */
protected $accountRepository;
/** @var array */
protected $validAssetFields = ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth'];
/** @var array */
protected $validCCFields = ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth'];
/** @var array */
protected $validFields = ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth'];
2018-02-21 20:34:24 +01:00
/**
* @param null|string $iban
*
* @return null|string
*/
2018-07-26 06:27:52 +02:00
public function filterIban(?string $iban): ?string
2018-02-21 20:34:24 +01:00
{
if (null === $iban) {
return null;
}
$data = ['iban' => $iban];
$rules = ['iban' => 'required|iban'];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
2018-04-24 19:26:31 +02:00
Log::info(sprintf('Detected invalid IBAN ("%s"). Return NULL instead.', $iban));
2018-02-21 20:34:24 +01:00
return null;
}
return $iban;
}
2019-06-22 10:25:34 +02:00
/**
* Update meta data for account. Depends on type which fields are valid.
*
* TODO this method treats expense accounts and liabilities the same way (tries to save interest)
*
* @param Account $account
* @param array $data
2019-08-17 10:47:29 +02:00
*
2019-06-22 10:25:34 +02:00
*/
public function updateMetaData(Account $account, array $data): void
{
$fields = $this->validFields;
if ($account->accountType->type === AccountType::ASSET) {
$fields = $this->validAssetFields;
}
if ($account->accountType->type === AccountType::ASSET && isset($data['account_role']) && 'ccAsset' === $data['account_role']) {
2019-06-22 10:25:34 +02:00
$fields = $this->validCCFields;
}
/** @var AccountMetaFactory $factory */
$factory = app(AccountMetaFactory::class);
foreach ($fields as $field) {
2019-06-22 10:25:34 +02:00
$factory->crud($account, $field, (string)($data[$field] ?? ''));
}
}
/**
* @param Account $account
2019-06-22 10:25:34 +02:00
* @param string $note
*
2019-07-31 16:53:09 +02:00
* @codeCoverageIgnore
2019-06-22 10:25:34 +02:00
* @return bool
*/
2019-06-22 10:25:34 +02:00
public function updateNote(Account $account, string $note): bool
{
2019-06-22 10:25:34 +02:00
if ('' === $note) {
$dbNote = $account->notes()->first();
if (null !== $dbNote) {
try {
$dbNote->delete();
} catch (Exception $e) {
Log::debug($e->getMessage());
}
}
2019-06-22 10:25:34 +02:00
return true;
}
2019-06-22 10:25:34 +02:00
$dbNote = $account->notes()->first();
if (null === $dbNote) {
$dbNote = new Note;
$dbNote->noteable()->associate($account);
}
2019-06-22 10:25:34 +02:00
$dbNote->text = trim($note);
$dbNote->save();
return true;
}
/**
* Verify if array contains valid data to possibly store or update the opening balance.
*
* @param array $data
*
* @return bool
*/
public function validOBData(array $data): bool
{
$data['opening_balance'] = (string)($data['opening_balance'] ?? '');
if ('' !== $data['opening_balance'] && isset($data['opening_balance'], $data['opening_balance_date'])) {
Log::debug('Array has valid opening balance data.');
return true;
}
Log::debug('Array does not have valid opening balance data.');
return false;
}
2019-06-22 10:25:34 +02:00
/**
* @param int $currencyId
* @param string $currencyCode
* @return TransactionCurrency
*/
protected function getCurrency(int $currencyId, string $currencyCode): TransactionCurrency
{
// find currency, or use default currency instead.
/** @var TransactionCurrencyFactory $factory */
$factory = app(TransactionCurrencyFactory::class);
/** @var TransactionCurrency $currency */
$currency = $factory->find($currencyId, $currencyCode);
if (null === $currency) {
// use default currency:
$currency = app('amount')->getDefaultCurrencyByUser($this->user);
}
$currency->enabled = true;
$currency->save();
return $currency;
}
/**
* Delete TransactionGroup with opening balance in it.
*
* @param Account $account
*/
protected function deleteOBGroup(Account $account): void
{
Log::debug(sprintf('deleteOB() for account #%d', $account->id));
$openingBalanceGroup = $this->getOBGroup($account);
// opening balance data? update it!
if (null !== $openingBalanceGroup) {
Log::debug('Opening balance journal found, delete journal.');
/** @var TransactionGroupDestroyService $service */
$service = app(TransactionGroupDestroyService::class);
$service->destroy($openingBalanceGroup);
}
}
/**
* @param Account $account
* @param array $data
* @return TransactionGroup|null
*/
protected function createOBGroup(Account $account, array $data): ?TransactionGroup
{
Log::debug('Now going to create an OB group.');
$language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data;
$sourceId = null;
$sourceName = null;
$destId = null;
$destName = null;
$amount = $data['opening_balance'];
if (1 === bccomp($amount, '0')) {
Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id));
// amount is positive.
$sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);
$destId = $account->id;
}
if (-1 === bccomp($amount, '0')) {
Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id));
// amount is not positive
$destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);
$sourceId = $account->id;
}
2019-08-10 11:17:23 +02:00
if (0 === bccomp($amount, '0')) {
Log::debug('Amount is zero, so will not make an OB group.');
return null;
}
$amount = app('steam')->positive($amount);
$submission = [
'group_title' => null,
'user' => $account->user_id,
'transactions' => [
[
'type' => 'Opening balance',
'date' => $data['opening_balance_date'],
'source_id' => $sourceId,
'source_name' => $sourceName,
'destination_id' => $destId,
'destination_name' => $destName,
'user' => $account->user_id,
'currency_id' => $data['currency_id'],
'order' => 0,
'amount' => $amount,
'foreign_amount' => null,
'description' => trans('firefly.initial_balance_description', ['account' => $account->name]),
'budget_id' => null,
'budget_name' => null,
'category_id' => null,
'category_name' => null,
'piggy_bank_id' => null,
'piggy_bank_name' => null,
'reconciled' => false,
'notes' => null,
'tags' => [],
],
],
];
Log::debug('Going for submission', $submission);
$group = null;
/** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class);
$factory->setUser($account->user);
try {
$group = $factory->create($submission);
// @codeCoverageIgnoreStart
} catch (FireflyException $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
}
2019-06-22 10:25:34 +02:00
// @codeCoverageIgnoreEnd
return $group;
}
/**
* Update or create the opening balance group. Assumes valid data in $data.
*
* Returns null if this fails.
*
* @param Account $account
* @param array $data
2019-07-31 16:53:09 +02:00
*
* @return TransactionGroup|null
2019-07-31 16:53:09 +02:00
* @codeCoverageIgnore
*/
protected function updateOBGroup(Account $account, array $data): ?TransactionGroup
{
2019-06-22 10:25:34 +02:00
$obGroup = $this->getOBGroup($account);
if (null === $obGroup) {
return $this->createOBGroup($account, $data);
}
2019-06-22 10:25:34 +02:00
/** @var TransactionJournal $journal */
$journal = $obGroup->transactionJournals()->first();
$journal->date = $data['opening_balance_date'] ?? $journal->date;
$journal->transaction_currency_id = $data['currency_id'];
/** @var Transaction $obTransaction */
$obTransaction = $journal->transactions()->where('account_id', '!=', $account->id)->first();
/** @var Transaction $accountTransaction */
$accountTransaction = $journal->transactions()->where('account_id', $account->id)->first();
// if amount is negative:
if (1 === bccomp('0', $data['opening_balance'])) {
// account transaction loses money:
$accountTransaction->amount = app('steam')->negative($data['opening_balance']);
$accountTransaction->transaction_currency_id = $data['currency_id'];
// OB account transaction gains money
$obTransaction->amount = app('steam')->positive($data['opening_balance']);
$obTransaction->transaction_currency_id = $data['currency_id'];
}
if (-1 === bccomp('0', $data['opening_balance'])) {
// account gains money:
$accountTransaction->amount = app('steam')->positive($data['opening_balance']);
$accountTransaction->transaction_currency_id = $data['currency_id'];
// OB account loses money:
$obTransaction->amount = app('steam')->negative($data['opening_balance']);
$obTransaction->transaction_currency_id = $data['currency_id'];
}
// save both
$accountTransaction->save();
$obTransaction->save();
$journal->save();
$obGroup->refresh();
2019-06-22 10:25:34 +02:00
return $obGroup;
}
/**
* Returns the opening balance group, or NULL if it does not exist.
*
* @param Account $account
* @return TransactionGroup|null
*/
protected function getOBGroup(Account $account): ?TransactionGroup
{
return $this->accountRepository->getOpeningBalanceGroup($account);
}
2018-03-05 19:35:58 +01:00
}