Skip to content

Firefly III: a personal finances manager

Clean up repository.

James Cole65b8882ed475
diff --git a/app/Crud/Account/AccountCrud.php b/app/Crud/Account/AccountCrud.php
new file mode 100644
index 0000000000..cd40e0ca17
--- /dev/null
+++ b/app/Crud/Account/AccountCrud.php
@@ -0,0 +1,342 @@
+<?php
+declare(strict_types = 1);
+
+/**
+ * AccountCrud.php
+ * Copyright (C) 2016 [email protected]
+ *
+ * This software may be modified and distributed under the terms
+ * of the MIT license. See the LICENSE file for details.
+ */
+
+namespace FireflyIII\Crud\Account;
+
+use DB;
+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;
+use Log;
+
+
+/**
+ * Class AccountCrud
+ *
+ * @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;
+ }
+
+ /**
+ * @param Account $account
+ * @param Account $moveTo
+ *
+ * @return bool
+ */
+ public function destroy(Account $account, Account $moveTo = null): bool
+ {
+ if (!is_null($moveTo)) {
+ // update all transactions:
+ DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]);
+ }
+
+ $account->delete();
+
+ return true;
+ }
+
+ /**
+ * @param Account $account
+ *
+ * @return TransactionJournal|null
+ */
+ public 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)) {
+ return new TransactionJournal;
+ }
+
+ return $journal;
+ }
+
+ /**
+ * @param array $data
+ *
+ * @return Account
+ */
+ public function store(array $data): Account
+ {
+ $newAccount = $this->storeAccount($data);
+ if (!is_null($newAccount)) {
+ $this->storeMetadata($newAccount, $data);
+ }
+
+
+ // continue with the opposing account:
+ if ($data['openingBalance'] != 0) {
+ $opposingData = [
+ 'user' => $data['user'],
+ 'accountType' => 'initial',
+ 'virtualBalance' => 0,
+ 'name' => $data['name'] . ' initial balance',
+ 'active' => false,
+ 'iban' => '',
+ ];
+ $opposing = $this->storeAccount($opposingData);
+ if (!is_null($opposing) && !is_null($newAccount)) {
+ $this->storeInitialBalance($newAccount, $opposing, $data);
+ }
+
+ }
+
+ return $newAccount;
+
+ }
+
+ /**
+ * @param $account
+ * @param $name
+ * @param $value
+ *
+ * @return AccountMeta
+ */
+ public function storeMeta(Account $account, string $name, $value): AccountMeta
+ {
+ return AccountMeta::create(['name' => $name, 'data' => $value, 'account_id' => $account->id,]);
+ }
+
+ /**
+ * @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);
+ $openingBalance = $this->openingBalanceTransaction($account);
+ if ($data['openingBalance'] != 0) {
+ if (!is_null($openingBalance->id)) {
+ $this->updateInitialBalance($account, $openingBalance, $data);
+ } else {
+ $type = $data['openingBalance'] < 0 ? 'expense' : 'revenue';
+ $opposingData = [
+ 'user' => $data['user'],
+ 'accountType' => $type,
+ 'name' => $data['name'] . ' initial balance',
+ 'active' => false,
+ 'iban' => '',
+ 'virtualBalance' => 0,
+ ];
+ $opposing = $this->storeAccount($opposingData);
+ if (!is_null($opposing)) {
+ $this->storeInitialBalance($account, $opposing, $data);
+ }
+ }
+
+ } else {
+ if ($openingBalance) { // opening balance is zero, should we delete it?
+ $openingBalance->delete(); // delete existing opening balance.
+ }
+ }
+
+ return $account;
+ }
+
+ /**
+ * @param array $data
+ *
+ * @return Account
+ */
+ protected function storeAccount(array $data): Account
+ {
+ $type = config('firefly.accountTypeByIdentifier.' . $data['accountType']);
+ $accountType = AccountType::whereType($type)->first();
+ $newAccount = new Account(
+ [
+ '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'],
+ ]
+ );
+
+ if (!$newAccount->isValid()) {
+ // does the account already exist?
+ $searchData = [
+ 'user_id' => $data['user'],
+ 'account_type_id' => $accountType->id,
+ 'virtual_balance' => $data['virtualBalance'],
+ 'name' => $data['name'],
+ 'iban' => $data['iban'],
+ ];
+ $existingAccount = Account::firstOrNullEncrypted($searchData);
+ if (!$existingAccount) {
+ Log::error('Account create error: ' . $newAccount->getErrors()->toJson());
+ abort(500);
+ }
+ $newAccount = $existingAccount;
+
+ }
+ $newAccount->save();
+
+ return $newAccount;
+ }
+
+ /**
+ * @param Account $account
+ * @param Account $opposing
+ * @param array $data
+ *
+ * @return TransactionJournal
+ */
+ protected function storeInitialBalance(Account $account, Account $opposing, array $data): TransactionJournal
+ {
+ $transactionType = TransactionType::whereType(TransactionType::OPENING_BALANCE)->first();
+ $journal = TransactionJournal::create(
+ [
+ 'user_id' => $data['user'],
+ 'transaction_type_id' => $transactionType->id,
+ 'bill_id' => null,
+ 'transaction_currency_id' => $data['openingBalanceCurrency'],
+ 'description' => 'Initial balance for "' . $account->name . '"',
+ 'completed' => true,
+ 'date' => $data['openingBalanceDate'],
+ 'encrypted' => true,
+ ]
+ );
+
+ if ($data['openingBalance'] < 0) {
+ $firstAccount = $opposing;
+ $secondAccount = $account;
+ $firstAmount = $data['openingBalance'] * -1;
+ $secondAmount = $data['openingBalance'];
+ } else {
+ $firstAccount = $account;
+ $secondAccount = $opposing;
+ $firstAmount = $data['openingBalance'];
+ $secondAmount = $data['openingBalance'] * -1;
+ }
+
+ $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
+
+ return $journal;
+
+ }
+
+ /**
+ * @param Account $account
+ * @param array $data
+ */
+ protected function storeMetadata(Account $account, array $data)
+ {
+ foreach ($this->validFields as $field) {
+ if (isset($data[$field])) {
+ $metaData = new AccountMeta(
+ [
+ 'account_id' => $account->id,
+ 'name' => $field,
+ 'data' => $data[$field],
+ ]
+ );
+ $metaData->save();
+ }
+
+
+ }
+ }
+
+ /**
+ * @param Account $account
+ * @param TransactionJournal $journal
+ * @param array $data
+ *
+ * @return TransactionJournal
+ */
+ protected function updateInitialBalance(Account $account, TransactionJournal $journal, array $data): TransactionJournal
+ {
+ $journal->date = $data['openingBalanceDate'];
+ $journal->save();
+
+ /** @var Transaction $transaction */
+ foreach ($journal->transactions()->get() as $transaction) {
+ if ($account->id == $transaction->account_id) {
+ $transaction->amount = $data['openingBalance'];
+ $transaction->save();
+ }
+ if ($account->id != $transaction->account_id) {
+ $transaction->amount = $data['openingBalance'] * -1;
+ $transaction->save();
+ }
+ }
+
+ return $journal;
+ }
+
+ /**
+ * @param Account $account
+ * @param array $data
+ *
+ */
+ protected function updateMetadata(Account $account, array $data)
+ {
+ foreach ($this->validFields as $field) {
+ $entry = $account->accountMeta()->where('name', $field)->first();
+
+ if (isset($data[$field])) {
+ // update if new data is present:
+ if (!is_null($entry)) {
+ $entry->data = $data[$field];
+ $entry->save();
+ } else {
+ $metaData = new AccountMeta(
+ [
+ 'account_id' => $account->id,
+ 'name' => $field,
+ 'data' => $data[$field],
+ ]
+ );
+ $metaData->save();
+ }
+ }
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/app/Crud/Account/AccountCrudInterface.php b/app/Crud/Account/AccountCrudInterface.php
new file mode 100644
index 0000000000..a00d494a6b
--- /dev/null
+++ b/app/Crud/Account/AccountCrudInterface.php
@@ -0,0 +1,65 @@
+<?php
+declare(strict_types = 1);
+
+/**
+ * AccountCrudInterface.php
+ * Copyright (C) 2016 [email protected]
+ *
+ * This software may be modified and distributed under the terms
+ * of the MIT license. See the LICENSE file for details.
+ */
+
+namespace FireflyIII\Crud\Account;
+
+use FireflyIII\Models\Account;
+use FireflyIII\Models\AccountMeta;
+use FireflyIII\Models\TransactionJournal;
+
+/**
+ * Interface AccountCrudInterface
+ *
+ * @package FireflyIII\Crud\Account
+ */
+interface AccountCrudInterface
+{
+ /**
+ * @param Account $account
+ * @param Account $moveTo
+ *
+ * @return bool
+ */
+ public function destroy(Account $account, Account $moveTo): bool;
+
+ /**
+ *
+ * @param Account $account
+ *
+ * @return TransactionJournal
+ */
+ public function openingBalanceTransaction(Account $account) : TransactionJournal;
+
+ /**
+ * @param array $data
+ *
+ * @return Account
+ */
+ public function store(array $data) : Account;
+
+ /**
+ * @param $account
+ * @param $name
+ * @param $value
+ *
+ * @return AccountMeta
+ */
+ public function storeMeta(Account $account, string $name, $value): AccountMeta;
+
+
+ /**
+ * @param Account $account
+ * @param array $data
+ *
+ * @return Account
+ */
+ public function update(Account $account, array $data): Account;
+}
\ No newline at end of file
diff --git a/app/Helpers/Csv/Converter/AssetAccountIban.php b/app/Helpers/Csv/Converter/AssetAccountIban.php
index 88f9c88217..2df18d4f08 100644
--- a/app/Helpers/Csv/Converter/AssetAccountIban.php
+++ b/app/Helpers/Csv/Converter/AssetAccountIban.php
@@ -4,6 +4,7 @@ namespace FireflyIII\Helpers\Csv\Converter;
use Auth;
use Carbon\Carbon;
+use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
@@ -42,10 +43,11 @@ class AssetAccountIban extends BasicConverter implements ConverterInterface
/**
* @param AccountRepositoryInterface $repository
+ * @param AccountCrudInterface $crud
*
* @return Account
*/
- private function searchOrCreate(AccountRepositoryInterface $repository)
+ private function searchOrCreate(AccountRepositoryInterface $repository, AccountCrudInterface $crud)
{
// find or create new account:
$set = $repository->getAccountsByType(['Default account', 'Asset account']);
@@ -74,7 +76,7 @@ class AssetAccountIban extends BasicConverter implements ConverterInterface
'openingBalanceCurrency' => 1, // hard coded.
];
- $account = $repository->store($accountData);
+ $account = $crud->store($accountData);
return $account;
}
diff --git a/app/Helpers/Csv/Converter/AssetAccountName.php b/app/Helpers/Csv/Converter/AssetAccountName.php
index 017866ed06..c60ad87aa2 100644
--- a/app/Helpers/Csv/Converter/AssetAccountName.php
+++ b/app/Helpers/Csv/Converter/AssetAccountName.php
@@ -4,6 +4,7 @@ namespace FireflyIII\Helpers\Csv\Converter;
use Auth;
use Carbon\Carbon;
+use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
@@ -22,6 +23,10 @@ class AssetAccountName extends BasicConverter implements ConverterInterface
{
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
+
+ /** @var AccountCrudInterface $crud */
+ $crud = app(AccountCrudInterface::class);
+
if (isset($this->mapped[$this->index][$this->value])) {
$account = $repository->find(intval($this->mapped[$this->index][$this->value]));
@@ -50,7 +55,7 @@ class AssetAccountName extends BasicConverter implements ConverterInterface
'openingBalanceCurrency' => 1, // hard coded.
];
- $account = $repository->store($accountData);
+ $account = $crud->store($accountData);
return $account;
}
diff --git a/app/Helpers/Csv/Converter/AssetAccountNumber.php b/app/Helpers/Csv/Converter/AssetAccountNumber.php
index e15cf4c900..ad742b3904 100644
--- a/app/Helpers/Csv/Converter/AssetAccountNumber.php
+++ b/app/Helpers/Csv/Converter/AssetAccountNumber.php
@@ -13,6 +13,7 @@ namespace FireflyIII\Helpers\Csv\Converter;
use Auth;
use Carbon\Carbon;
+use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
@@ -32,6 +33,9 @@ class AssetAccountNumber extends BasicConverter implements ConverterInterface
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
+ /** @var AccountCrudInterface $crud */
+ $crud = app(AccountCrudInterface::class);
+
// is mapped? Then it's easy!
if (isset($this->mapped[$this->index][$this->value])) {
$account = $repository->find(intval($this->mapped[$this->index][$this->value]));
@@ -68,7 +72,7 @@ class AssetAccountNumber extends BasicConverter implements ConverterInterface
];
- $account = $repository->store($accountData);
+ $account = $crud->store($accountData);
return $account;
}
diff --git a/app/Helpers/Csv/PostProcessing/AssetAccount.php b/app/Helpers/Csv/PostProcessing/AssetAccount.php
index bc028e721e..4a4b4a3525 100644
--- a/app/Helpers/Csv/PostProcessing/AssetAccount.php
+++ b/app/Helpers/Csv/PostProcessing/AssetAccount.php
@@ -4,6 +4,7 @@ namespace FireflyIII\Helpers\Csv\PostProcessing;
use Auth;
use Carbon\Carbon;
+use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
@@ -230,6 +231,9 @@ class AssetAccount implements PostProcessorInterface
*/
private function parseAccountNumberString()
{
+ /** @var AccountCrudInterface $crud */
+ $crud = app(AccountCrudInterface::class);
+
$accountNumber = $this->data['asset-account-number'] ?? '';
$accountType = $this->getAccountType();
$accounts = Auth::user()->accounts()->with(['accountmeta'])->where('account_type_id', $accountType->id)->get();
@@ -258,7 +262,7 @@ class AssetAccount implements PostProcessorInterface
'openingBalanceDate' => new Carbon,
'openingBalanceCurrency' => 1, // hard coded.
];
- $account = $repository->store($accountData);
+ $account = $crud->store($accountData);
return $account;
}
diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php
index 03665021f2..62a29fa8cf 100644
--- a/app/Http/Controllers/AccountController.php
+++ b/app/Http/Controllers/AccountController.php
@@ -6,6 +6,7 @@ namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon;
use ExpandedForm;
+use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Http\Requests\AccountFormRequest;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
@@ -83,19 +84,20 @@ class AccountController extends Controller
}
/**
- * @param ARI $repository
- * @param Account $account
+ * @param ARI $repository
+ * @param AccountCrudInterface $crud
+ * @param Account $account
*
- * @return \Illuminate\Http\RedirectResponse
+ * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
- public function destroy(ARI $repository, Account $account)
+ public function destroy(ARI $repository, AccountCrudInterface $crud, Account $account)
{
$type = $account->accountType->type;
$typeName = config('firefly.shortNamesByFullName.' . $type);
$name = $account->name;
$moveTo = $repository->find(intval(Input::get('move_account_before_delete')));
- $repository->destroy($account, $moveTo);
+ $crud->destroy($account, $moveTo);
Session::flash('success', strval(trans('firefly.' . $typeName . '_deleted', ['name' => $name])));
Preferences::mark();
@@ -273,12 +275,12 @@ class AccountController extends Controller
}
/**
- * @param AccountFormRequest $request
- * @param ARI $repository
+ * @param AccountFormRequest $request
+ * @param AccountCrudInterface $crud
*
- * @return \Illuminate\Http\RedirectResponse
+ * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
- public function store(AccountFormRequest $request, ARI $repository)
+ public function store(AccountFormRequest $request, AccountCrudInterface $crud)
{
$accountData = [
'name' => $request->input('name'),
@@ -296,7 +298,7 @@ class AccountController extends Controller
];
- $account = $repository->store($accountData);
+ $account = $crud->store($accountData);
Session::flash('success', strval(trans('firefly.stored_new_account', ['name' => $account->name])));
Preferences::mark();
@@ -320,13 +322,13 @@ class AccountController extends Controller
}
/**
- * @param AccountFormRequest $request
- * @param ARI $repository
- * @param Account $account
+ * @param AccountFormRequest $request
+ * @param AccountCrudInterface $crud
+ * @param Account $account
*
- * @return \Illuminate\Http\RedirectResponse
+ * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
- public function update(AccountFormRequest $request, ARI $repository, Account $account)
+ public function update(AccountFormRequest $request, AccountCrudInterface $crud, Account $account)
{
$accountData = [
@@ -343,7 +345,7 @@ class AccountController extends Controller
'ccType' => $request->input('ccType'),
'ccMonthlyPaymentDate' => $request->input('ccMonthlyPaymentDate'),
];
- $repository->update($account, $accountData);
+ $crud->update($account, $accountData);
Session::flash('success', strval(trans('firefly.updated_account', ['name' => $account->name])));
Preferences::mark();
diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php
index 6962540179..f3a4f06653 100644
--- a/app/Http/Controllers/HomeController.php
+++ b/app/Http/Controllers/HomeController.php
@@ -126,7 +126,7 @@ class HomeController extends Controller
$piggyBankAccounts = $repository->getPiggyBankAccounts($start, $end);
- $savingsTotal = 0;
+ $savingsTotal = '0';
foreach ($savings as $savingAccount) {
$savingsTotal = bcadd($savingsTotal, Steam::balance($savingAccount, $end));
}
diff --git a/app/Http/Controllers/NewUserController.php b/app/Http/Controllers/NewUserController.php
index 26115ab5a3..d33e7d760d 100644
--- a/app/Http/Controllers/NewUserController.php
+++ b/app/Http/Controllers/NewUserController.php
@@ -4,6 +4,7 @@ namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon;
+use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Http\Requests\NewUserFormRequest;
use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI;
use Preferences;
@@ -49,12 +50,12 @@ class NewUserController extends Controller
}
/**
- * @param NewUserFormRequest $request
- * @param ARI $repository
+ * @param NewUserFormRequest $request
+ * @param AccountCrudInterface $crud
*
* @return \Illuminate\Http\RedirectResponse
*/
- public function submit(NewUserFormRequest $request, ARI $repository)
+ public function submit(NewUserFormRequest $request, AccountCrudInterface $crud)
{
$count = 1;
// create normal asset account:
@@ -71,7 +72,7 @@ class NewUserController extends Controller
'openingBalanceCurrency' => intval($request->input('amount_currency_id_bank_balance')),
];
- $repository->store($assetAccount);
+ $crud->store($assetAccount);
// create savings account
if (strlen($request->get('savings_balance') > 0)) {
@@ -87,7 +88,7 @@ class NewUserController extends Controller
'openingBalanceDate' => new Carbon,
'openingBalanceCurrency' => intval($request->input('amount_currency_id_savings_balance')),
];
- $repository->store($savingsAccount);
+ $crud->store($savingsAccount);
$count++;
}
@@ -106,11 +107,11 @@ class NewUserController extends Controller
'openingBalanceDate' => null,
'openingBalanceCurrency' => intval($request->input('amount_currency_id_credit_card_limit')),
];
- $creditCard = $repository->store($creditAccount);
+ $creditCard = $crud->store($creditAccount);
// store meta for CC:
- $repository->storeMeta($creditCard, 'ccType', 'monthlyFull');
- $repository->storeMeta($creditCard, 'ccMonthlyPaymentDate', Carbon::now()->year . '-01-01');
+ $crud->storeMeta($creditCard, 'ccType', 'monthlyFull');
+ $crud->storeMeta($creditCard, 'ccMonthlyPaymentDate', Carbon::now()->year . '-01-01');
$count++;
}
$message = strval(trans('firefly.stored_new_accounts_new_user'));
diff --git a/app/Providers/CrudServiceProvider.php b/app/Providers/CrudServiceProvider.php
index 249ce49100..9ea942796e 100644
--- a/app/Providers/CrudServiceProvider.php
+++ b/app/Providers/CrudServiceProvider.php
@@ -53,5 +53,19 @@ class CrudServiceProvider extends ServiceProvider
return app('FireflyIII\Crud\Split\Journal', $arguments);
}
);
+
+ $this->app->bind(
+ 'FireflyIII\Crud\Account\AccountCrudInterface',
+ function (Application $app, array $arguments) {
+ if (!isset($arguments[0]) && $app->auth->check()) {
+ return app('FireflyIII\Crud\Account\AccountCrud', [$app->auth->user()]);
+ }
+ if (!isset($arguments[0]) && !$app->auth->check()) {
+ throw new FireflyException('There is no user present.');
+ }
+
+ return app('FireflyIII\Crud\Account\AccountCrud', $arguments);
+ }
+ );
}
}
diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php
index 94d44de835..ae9e7c4a81 100644
--- a/app/Repositories/Account/AccountRepository.php
+++ b/app/Repositories/Account/AccountRepository.php
@@ -2,14 +2,11 @@
declare(strict_types = 1);
-
namespace FireflyIII\Repositories\Account;
use Carbon\Carbon;
use DB;
use FireflyIII\Models\Account;
-use FireflyIII\Models\AccountMeta;
-use FireflyIII\Models\AccountType;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
@@ -18,7 +15,6 @@ use FireflyIII\User;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
-use Log;
use Steam;
@@ -58,24 +54,6 @@ class AccountRepository implements AccountRepositoryInterface
return $count;
}
- /**
- * @param Account $account
- * @param Account $moveTo
- *
- * @return bool
- */
- public function destroy(Account $account, Account $moveTo = null): bool
- {
- if (!is_null($moveTo)) {
- // update all transactions:
- DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]);
- }
-
- $account->delete();
-
- return true;
- }
-
/**
* This method is almost the same as ::earnedInPeriod, but only works for revenue accounts
* instead of the implied asset accounts for ::earnedInPeriod. ::earnedInPeriod will tell you
@@ -337,10 +315,10 @@ class AccountRepository implements AccountRepositoryInterface
function (Account $account) use ($start, $end) {
$account->startBalance = Steam::balanceIgnoreVirtual($account, $start);
$account->endBalance = Steam::balanceIgnoreVirtual($account, $end);
- $account->piggyBalance = 0;
+ $account->piggyBalance = '0';
/** @var PiggyBank $piggyBank */
foreach ($account->piggyBanks as $piggyBank) {
- $account->piggyBalance += $piggyBank->currentRelevantRep()->currentamount;
+ $account->piggyBalance = bcadd($account->piggyBalance, $piggyBank->currentRelevantRep()->currentamount);
}
// sum of piggy bank amounts on this account:
// diff between endBalance and piggyBalance.
@@ -650,260 +628,4 @@ class AccountRepository implements AccountRepositoryInterface
return $sum;
}
- /**
- * @param array $data
- *
- * @return Account
- */
- public function store(array $data): Account
- {
- $newAccount = $this->storeAccount($data);
- if (!is_null($newAccount)) {
- $this->storeMetadata($newAccount, $data);
- }
-
-
- // continue with the opposing account:
- if ($data['openingBalance'] != 0) {
- $opposingData = [
- 'user' => $data['user'],
- 'accountType' => 'initial',
- 'virtualBalance' => 0,
- 'name' => $data['name'] . ' initial balance',
- 'active' => false,
- 'iban' => '',
- ];
- $opposing = $this->storeAccount($opposingData);
- if (!is_null($opposing) && !is_null($newAccount)) {
- $this->storeInitialBalance($newAccount, $opposing, $data);
- }
-
- }
-
- return $newAccount;
-
- }
-
- /**
- * @param $account
- * @param $name
- * @param $value
- *
- * @return AccountMeta
- */
- public function storeMeta(Account $account, string $name, $value): AccountMeta
- {
- return AccountMeta::create(['name' => $name, 'data' => $value, 'account_id' => $account->id,]);
- }
-
- /**
- * @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);
- $openingBalance = $this->openingBalanceTransaction($account);
- if ($data['openingBalance'] != 0) {
- if (!is_null($openingBalance->id)) {
- $this->updateInitialBalance($account, $openingBalance, $data);
- } else {
- $type = $data['openingBalance'] < 0 ? 'expense' : 'revenue';
- $opposingData = [
- 'user' => $data['user'],
- 'accountType' => $type,
- 'name' => $data['name'] . ' initial balance',
- 'active' => false,
- 'iban' => '',
- 'virtualBalance' => 0,
- ];
- $opposing = $this->storeAccount($opposingData);
- if (!is_null($opposing)) {
- $this->storeInitialBalance($account, $opposing, $data);
- }
- }
-
- } else {
- if ($openingBalance) { // opening balance is zero, should we delete it?
- $openingBalance->delete(); // delete existing opening balance.
- }
- }
-
- return $account;
- }
-
- /**
- * @param array $data
- *
- * @return Account
- */
- protected function storeAccount(array $data): Account
- {
- $type = config('firefly.accountTypeByIdentifier.' . $data['accountType']);
- $accountType = AccountType::whereType($type)->first();
- $newAccount = new Account(
- [
- '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'],
- ]
- );
-
- if (!$newAccount->isValid()) {
- // does the account already exist?
- $searchData = [
- 'user_id' => $data['user'],
- 'account_type_id' => $accountType->id,
- 'virtual_balance' => $data['virtualBalance'],
- 'name' => $data['name'],
- 'iban' => $data['iban'],
- ];
- $existingAccount = Account::firstOrNullEncrypted($searchData);
- if (!$existingAccount) {
- Log::error('Account create error: ' . $newAccount->getErrors()->toJson());
- abort(500);
- }
- $newAccount = $existingAccount;
-
- }
- $newAccount->save();
-
- return $newAccount;
- }
-
- /**
- * @param Account $account
- * @param Account $opposing
- * @param array $data
- *
- * @return TransactionJournal
- */
- protected function storeInitialBalance(Account $account, Account $opposing, array $data): TransactionJournal
- {
- $transactionType = TransactionType::whereType(TransactionType::OPENING_BALANCE)->first();
- $journal = TransactionJournal::create(
- [
- 'user_id' => $data['user'],
- 'transaction_type_id' => $transactionType->id,
- 'bill_id' => null,
- 'transaction_currency_id' => $data['openingBalanceCurrency'],
- 'description' => 'Initial balance for "' . $account->name . '"',
- 'completed' => true,
- 'date' => $data['openingBalanceDate'],
- 'encrypted' => true,
- ]
- );
-
- if ($data['openingBalance'] < 0) {
- $firstAccount = $opposing;
- $secondAccount = $account;
- $firstAmount = $data['openingBalance'] * -1;
- $secondAmount = $data['openingBalance'];
- } else {
- $firstAccount = $account;
- $secondAccount = $opposing;
- $firstAmount = $data['openingBalance'];
- $secondAmount = $data['openingBalance'] * -1;
- }
-
- $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
-
- return $journal;
-
- }
-
- /**
- * @param Account $account
- * @param array $data
- */
- protected function storeMetadata(Account $account, array $data)
- {
- foreach ($this->validFields as $field) {
- if (isset($data[$field])) {
- $metaData = new AccountMeta(
- [
- 'account_id' => $account->id,
- 'name' => $field,
- 'data' => $data[$field],
- ]
- );
- $metaData->save();
- }
-
-
- }
- }
-
- /**
- * @param Account $account
- * @param TransactionJournal $journal
- * @param array $data
- *
- * @return TransactionJournal
- */
- protected function updateInitialBalance(Account $account, TransactionJournal $journal, array $data): TransactionJournal
- {
- $journal->date = $data['openingBalanceDate'];
- $journal->save();
-
- /** @var Transaction $transaction */
- foreach ($journal->transactions()->get() as $transaction) {
- if ($account->id == $transaction->account_id) {
- $transaction->amount = $data['openingBalance'];
- $transaction->save();
- }
- if ($account->id != $transaction->account_id) {
- $transaction->amount = $data['openingBalance'] * -1;
- $transaction->save();
- }
- }
-
- return $journal;
- }
-
- /**
- * @param Account $account
- * @param array $data
- *
- */
- protected function updateMetadata(Account $account, array $data)
- {
- foreach ($this->validFields as $field) {
- $entry = $account->accountMeta()->where('name', $field)->first();
-
- if (isset($data[$field])) {
- // update if new data is present:
- if (!is_null($entry)) {
- $entry->data = $data[$field];
- $entry->save();
- } else {
- $metaData = new AccountMeta(
- [
- 'account_id' => $account->id,
- 'name' => $field,
- 'data' => $data[$field],
- ]
- );
- $metaData->save();
- }
- }
- }
-
- }
}
diff --git a/app/Repositories/Account/AccountRepositoryInterface.php b/app/Repositories/Account/AccountRepositoryInterface.php
index 45fe15a939..074b2588e8 100644
--- a/app/Repositories/Account/AccountRepositoryInterface.php
+++ b/app/Repositories/Account/AccountRepositoryInterface.php
@@ -25,14 +25,6 @@ interface AccountRepositoryInterface
*/
public function countAccounts(array $types): int;
- /**
- * @param Account $account
- * @param Account $moveTo
- *
- * @return bool
- */
- public function destroy(Account $account, Account $moveTo): bool;
-
/**
* This method is almost the same as ::earnedInPeriod, but only works for revenue accounts
* instead of the implied asset accounts for ::earnedInPeriod. ::earnedInPeriod will tell you
@@ -218,28 +210,5 @@ interface AccountRepositoryInterface
* @return string
*/
public function spentInPeriod(Collection $accounts, Carbon $start, Carbon $end): string;
-
- /**
- * @param array $data
- *
- * @return Account
- */
- public function store(array $data) : Account;
-
- /**
- * @param $account
- * @param $name
- * @param $value
- *
- * @return AccountMeta
- */
- public function storeMeta(Account $account, string $name, $value): AccountMeta;
-
- /**
- * @param Account $account
- * @param array $data
- *
- * @return Account
- */
- public function update(Account $account, array $data): Account;
+
}