Files
firefly-iii/app/Crud/Account/AccountCrud.php

408 lines
13 KiB
PHP
Raw Normal View History

2016-05-20 09:25:17 +02:00
<?php
/**
* AccountCrud.php
* Copyright (C) 2016 thegrumpydictator@gmail.com
*
* This software may be modified and distributed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International License.
*
* See the LICENSE file for details.
2016-05-20 09:25:17 +02:00
*/
declare(strict_types = 1);
2016-05-20 09:25:17 +02:00
namespace FireflyIII\Crud\Account;
2016-07-30 16:29:04 +02:00
use Carbon\Carbon;
2016-10-08 10:02:33 +02:00
use FireflyIII\Exceptions\FireflyException;
2016-05-20 09:25:17 +02:00
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountMeta;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\User;
2016-05-20 11:02:07 +02:00
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
2016-05-20 09:25:17 +02:00
use Log;
/**
* Class AccountCrud
*
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*
2016-05-20 09:25:17 +02:00
* @package FireflyIII\Crud\Account
*/
class AccountCrud implements AccountCrudInterface
{
/** @var User */
private $user;
/** @var array */
private $validFields = ['accountRole', 'ccMonthlyPaymentDate', 'ccType', 'accountNumber'];
/**
* AccountCrud constructor.
*
* @param User $user
*/
public function __construct(User $user)
{
$this->user = $user;
}
2016-07-16 07:58:25 +02:00
/**
2016-10-10 07:20:49 +02:00
* WILL BE REMOVED.
*
2016-07-16 07:58:25 +02:00
* @param string $name
* @param array $types
*
* @return Account
*/
public function findByName(string $name, array $types): Account
{
$query = $this->user->accounts();
2016-07-16 07:58:25 +02:00
if (count($types) > 0) {
$query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id');
$query->whereIn('account_types.type', $types);
2016-07-16 07:58:25 +02:00
}
Log::debug(sprintf('Searching for account named %s of the following type(s)', $name), ['types' => $types]);
2016-07-16 07:58:25 +02:00
$accounts = $query->get(['accounts.*']);
2016-07-16 07:58:25 +02:00
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name) {
Log::debug(sprintf('Found #%d (%s) with type id %d', $account->id, $account->name, $account->account_type_id));
2016-08-11 18:44:11 +02:00
return $account;
2016-07-16 07:58:25 +02:00
}
}
Log::debug('Found nothing.');
2016-07-16 07:58:25 +02:00
return new Account;
}
2016-05-20 09:25:17 +02:00
/**
* @param array $data
*
* @return Account
*/
public function store(array $data): Account
{
$newAccount = $this->storeAccount($data);
2016-10-08 10:02:33 +02:00
$this->updateMetadata($newAccount, $data);
2016-05-20 09:25:17 +02:00
2016-10-08 10:02:33 +02:00
if ($this->validOpeningBalanceData($data)) {
$this->updateInitialBalance($newAccount, $data);
return $newAccount;
2016-05-20 09:25:17 +02:00
}
2016-10-08 10:02:33 +02:00
$this->deleteInitialBalance($newAccount);
2016-05-20 09:25:17 +02:00
return $newAccount;
}
/**
* @param Account $account
* @param array $data
*
* @return Account
*/
public function update(Account $account, array $data): Account
{
// update the account:
$account->name = $data['name'];
$account->active = $data['active'] == '1' ? true : false;
$account->virtual_balance = $data['virtualBalance'];
$account->iban = $data['iban'];
$account->save();
$this->updateMetadata($account, $data);
2016-07-30 16:29:04 +02:00
$this->updateInitialBalance($account, $data);
2016-05-20 09:25:17 +02:00
return $account;
}
2016-10-08 10:02:33 +02:00
/**
* @param Account $account
*/
protected function deleteInitialBalance(Account $account)
{
$journal = $this->openingBalanceTransaction($account);
if (!is_null($journal->id)) {
$journal->delete();
}
}
/**
* @param Account $account
*
* @return TransactionJournal|null
*/
protected function openingBalanceTransaction(Account $account): TransactionJournal
{
$journal = TransactionJournal
::sortCorrectly()
->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::OPENING_BALANCE])
->first(['transaction_journals.*']);
if (is_null($journal)) {
Log::debug('Could not find a opening balance journal, return empty one.');
return new TransactionJournal;
}
Log::debug(sprintf('Found opening balance: journal #%d.', $journal->id));
return $journal;
}
2016-05-20 09:25:17 +02:00
/**
* @param array $data
*
* @return Account
2016-10-08 10:02:33 +02:00
* @throws FireflyException
2016-05-20 09:25:17 +02:00
*/
protected function storeAccount(array $data): Account
{
2016-10-08 10:02:33 +02:00
$data['accountType'] = $data['accountType'] ?? 'invalid';
$type = config('firefly.accountTypeByIdentifier.' . $data['accountType']);
$accountType = AccountType::whereType($type)->first();
// verify account type
if (is_null($accountType)) {
throw new FireflyException(sprintf('Account type "%s" is invalid. Cannot create account.', $data['accountType']));
}
// account may exist already:
$existingAccount = $this->findByName($data['name'], [$data['accountType']]);
if (!is_null($existingAccount->id)) {
throw new FireflyException(sprintf('There already is an account named "%s" of type "%s".', $data['name'], $data['accountType']));
}
// create it:
$newAccount = new Account(
2016-05-20 09:25:17 +02:00
[
'user_id' => $data['user'],
'account_type_id' => $accountType->id,
'name' => $data['name'],
'virtual_balance' => $data['virtualBalance'],
'active' => $data['active'] === true ? true : false,
'iban' => $data['iban'],
]
);
$newAccount->save();
2016-10-08 10:02:33 +02:00
// verify its creation:
if (is_null($newAccount->id)) {
Log::error(
sprintf('Could not create account "%s" (%d error(s))', $data['name'], $newAccount->getErrors()->count()), $newAccount->getErrors()->toArray()
);
throw new FireflyException(sprintf('Tried to create account named "%s" but failed. The logs have more details.', $data['name']));
}
2016-05-20 09:25:17 +02:00
return $newAccount;
}
/**
* @param Account $account
* @param array $data
*
* @return TransactionJournal
*/
2016-07-30 16:29:04 +02:00
protected function storeInitialBalance(Account $account, array $data): TransactionJournal
2016-05-20 09:25:17 +02:00
{
2016-07-30 16:29:04 +02:00
$amount = $data['openingBalance'];
$user = $data['user'];
$name = $data['name'];
$opposing = $this->storeOpposingAccount($amount, $user, $name);
2016-05-20 09:25:17 +02:00
$transactionType = TransactionType::whereType(TransactionType::OPENING_BALANCE)->first();
$journal = TransactionJournal::create(
[
'user_id' => $data['user'],
'transaction_type_id' => $transactionType->id,
'transaction_currency_id' => $data['openingBalanceCurrency'],
'description' => 'Initial balance for "' . $account->name . '"',
'completed' => true,
'date' => $data['openingBalanceDate'],
'encrypted' => true,
]
);
2016-10-08 10:02:33 +02:00
Log::debug(sprintf('Created new opening balance journal: #%d', $journal->id));
2016-05-20 09:25:17 +02:00
$firstAccount = $account;
$secondAccount = $opposing;
2016-07-30 16:29:04 +02:00
$firstAmount = $amount;
$secondAmount = $amount * -1;
2016-05-20 09:25:17 +02:00
if ($data['openingBalance'] < 0) {
$firstAccount = $opposing;
$secondAccount = $account;
2016-07-30 16:29:04 +02:00
$firstAmount = $amount * -1;
$secondAmount = $amount;
2016-05-20 09:25:17 +02:00
}
$one = new Transaction(['account_id' => $firstAccount->id, 'transaction_journal_id' => $journal->id, 'amount' => $firstAmount]);
$one->save();// first transaction: from
$two = new Transaction(['account_id' => $secondAccount->id, 'transaction_journal_id' => $journal->id, 'amount' => $secondAmount]);
$two->save(); // second transaction: to
2016-10-08 10:02:33 +02:00
Log::debug(sprintf('Stored two transactions, #%d and #%d', $one->id, $two->id));
2016-05-20 09:25:17 +02:00
return $journal;
}
/**
2016-10-08 10:02:33 +02:00
* @param float $amount
* @param int $user
* @param string $name
*
* @return Account
2016-05-20 09:25:17 +02:00
*/
2016-10-08 10:02:33 +02:00
protected function storeOpposingAccount(float $amount, int $user, string $name):Account
2016-05-20 09:25:17 +02:00
{
2016-10-08 10:02:33 +02:00
$type = $amount < 0 ? 'expense' : 'revenue';
$opposingData = [
'user' => $user,
'accountType' => $type,
'name' => $name . ' initial balance',
'active' => false,
'iban' => '',
'virtualBalance' => 0,
];
Log::debug('Going to create an opening balance opposing account');
return $this->storeAccount($opposingData);
2016-05-20 09:25:17 +02:00
}
/**
2016-07-30 16:29:04 +02:00
* @param Account $account
* @param array $data
2016-05-20 09:25:17 +02:00
*
2016-07-30 16:29:04 +02:00
* @return bool
2016-05-20 09:25:17 +02:00
*/
2016-07-30 16:29:04 +02:00
protected function updateInitialBalance(Account $account, array $data): bool
2016-05-20 09:25:17 +02:00
{
2016-07-30 16:29:04 +02:00
$openingBalance = $this->openingBalanceTransaction($account);
2016-10-08 10:02:33 +02:00
// no opening balance journal? create it:
if (is_null($openingBalance->id)) {
Log::debug('No opening balance journal yet, create journal.');
2016-07-30 16:29:04 +02:00
$this->storeInitialBalance($account, $data);
return true;
}
2016-10-08 10:02:33 +02:00
// opening balance data? update it!
if (!is_null($openingBalance->id)) {
$date = $data['openingBalanceDate'];
$amount = $data['openingBalance'];
Log::debug('Opening balance journal found, update journal.');
$this->updateOpeningBalanceJournal($account, $openingBalance, $date, $amount);
return true;
2016-05-20 09:25:17 +02:00
}
2016-07-30 16:29:04 +02:00
return true;
2016-05-20 09:25:17 +02:00
}
/**
* @param Account $account
* @param array $data
*
*/
protected function updateMetadata(Account $account, array $data)
{
foreach ($this->validFields as $field) {
2016-10-08 10:02:33 +02:00
/** @var AccountMeta $entry */
2016-05-20 09:25:17 +02:00
$entry = $account->accountMeta()->where('name', $field)->first();
2016-10-08 10:02:33 +02:00
// if $data has field and $entry is null, create new one:
if (isset($data[$field]) && is_null($entry)) {
Log::debug(
sprintf(
'Created meta-field "%s":"%s" for account #%d ("%s") ',
$field, $data[$field], $account->id, $account->name
)
);
AccountMeta::create(
[
'account_id' => $account->id,
'name' => $field,
'data' => $data[$field],
]
);
2016-05-20 09:25:17 +02:00
}
2016-05-20 09:45:24 +02:00
2016-10-08 10:02:33 +02:00
// if $data has field and $entry is not null, update $entry:
if (isset($data[$field]) && !is_null($entry)) {
$entry->data = $data[$field];
$entry->save();
Log::debug(
sprintf(
'Updated meta-field "%s":"%s" for account #%d ("%s") ',
$field, $data[$field], $account->id, $account->name
)
);
}
2016-05-20 09:45:24 +02:00
}
2016-07-30 16:29:04 +02:00
}
/**
* @param Account $account
* @param TransactionJournal $journal
* @param Carbon $date
* @param float $amount
*
* @return bool
*/
2016-10-08 10:02:33 +02:00
protected function updateOpeningBalanceJournal(Account $account, TransactionJournal $journal, Carbon $date, float $amount): bool
2016-07-30 16:29:04 +02:00
{
// update date:
$journal->date = $date;
$journal->save();
// update transactions:
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
if ($account->id == $transaction->account_id) {
$transaction->amount = $amount;
$transaction->save();
}
if ($account->id != $transaction->account_id) {
$transaction->amount = $amount * -1;
$transaction->save();
}
}
2016-10-08 10:02:33 +02:00
Log::debug('Updated opening balance journal.');
2016-07-30 16:29:04 +02:00
return true;
}
2016-10-08 10:02:33 +02:00
/**
* @param array $data
*
* @return bool
*/
protected function validOpeningBalanceData(array $data): bool
{
if (isset($data['openingBalance'])
&& isset($data['openingBalanceDate'])
&& isset($data['openingBalanceCurrency'])
&& bccomp(strval($data['openingBalance']), '0') !== 0
) {
Log::debug('Array has valid opening balance data.');
return true;
}
Log::debug('Array does not have valid opening balance data.');
return false;
}
2016-08-12 15:10:03 +02:00
}