Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Cleanup various factories and libraries.
James Cole027b954b50a1
diff --git a/app/lib/FireflyIII/Database/Account/Account.php b/app/lib/FireflyIII/Database/Account/Account.phpindex 257ae7b79a..1faa84c220 100644--- a/app/lib/FireflyIII/Database/Account/Account.php+++ b/app/lib/FireflyIII/Database/Account/Account.php@@ -88,51 +88,31 @@ class Account implements CUDInterface, CommonDatabaseCallsInterface, AccountInte{$opposingData = ['name' => $account->name . ' Initial Balance', 'active' => 0, 'what' => 'initial'];$opposingAccount = $this->store($opposingData);-- /*- * Create a journal from opposing to account or vice versa.- */- $balance = floatval($data['openingbalance']);- $date = new Carbon($data['openingbalancedate']);- /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $tj */- $tj = \App::make('FireflyIII\Database\TransactionJournal\TransactionJournal');+ $balance = floatval($data['openingbalance']);+ $date = new Carbon($data['openingbalancedate']);+ /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $journals */+ $journals = \App::make('FireflyIII\Database\TransactionJournal\TransactionJournal');+ $fromAccount = $opposingAccount;+ $toAccount = $account;if ($balance < 0) {- // first transaction draws money from the new account to the opposing- $from = $account;- $to = $opposingAccount;- } else {- // first transaction puts money into account- $from = $opposingAccount;- $to = $account;+ $fromAccount = $account;+ $toAccount = $opposingAccount;}-// data for transaction journal:$balance = $balance < 0 ? $balance * -1 : $balance;- // find the account type:/** @var \FireflyIII\Database\TransactionType\TransactionType $typeRepository */$typeRepository = \App::make('FireflyIII\Database\TransactionType\TransactionType');$type = $typeRepository->findByWhat('opening');+ $currency = \Amount::getDefaultCurrency();- // find the currency.- $currency = \Amount::getDefaultCurrency();-- $opening = [- 'transaction_type_id' => $type->id,- 'transaction_currency_id' => $currency->id,- 'amount' => $balance,- 'from' => $from,- 'completed' => 0,- 'currency' => 'EUR',- 'what' => 'opening',- 'to' => $to,- 'date' => $date,- 'description' => 'Opening balance for new account ' . $account->name,];-+ $opening = ['transaction_type_id' => $type->id, 'transaction_currency_id' => $currency->id, 'amount' => $balance, 'from' => $fromAccount,+ 'completed' => 0, 'currency' => 'EUR', 'what' => 'opening', 'to' => $toAccount, 'date' => $date,+ 'description' => 'Opening balance for new account ' . $account->name,];- $validation = $tj->validate($opening);+ $validation = $journals->validate($opening);if ($validation['errors']->count() == 0) {- $tj->store($opening);+ $journals->store($opening);return true;} else {@@ -141,6 +121,7 @@ class Account implements CUDInterface, CommonDatabaseCallsInterface, AccountInte\App::abort(500);}+ return false;}/**diff --git a/app/lib/FireflyIII/Database/PiggyBank/PiggyBank.php b/app/lib/FireflyIII/Database/PiggyBank/PiggyBank.phpindex b77f9246bb..5de40005e9 100644--- a/app/lib/FireflyIII/Database/PiggyBank/PiggyBank.php+++ b/app/lib/FireflyIII/Database/PiggyBank/PiggyBank.php@@ -30,13 +30,10 @@ class PiggyBank extends PiggyBankShared implements CUDInterface, CommonDatabaseCif ($reps->count() == 1) {return $reps->first();}- if ($reps->count() == 0) {- throw new FireflyException('Should always find a piggy bank repetition.');- }// should filter the one we need:$repetitions = $reps->filter(function (\PiggyBankRepetition $rep) use ($date) {- if ($date >= $rep->startdate && $date <= $rep->targetdate) {+ if ($date->between($rep->startdate, $rep->targetdate)) {return $rep;}diff --git a/app/lib/FireflyIII/Database/TransactionJournal/TransactionJournal.php b/app/lib/FireflyIII/Database/TransactionJournal/TransactionJournal.phpindex beb7b13df2..60f74c1415 100644--- a/app/lib/FireflyIII/Database/TransactionJournal/TransactionJournal.php+++ b/app/lib/FireflyIII/Database/TransactionJournal/TransactionJournal.php@@ -117,9 +117,6 @@ class TransactionJournal implements TransactionJournalInterface, CUDInterface, C$this->storeBudget($data, $model);$this->storeCategory($data, $model);- /*- * Now we can update the transactions related to this journal.- */$amount = floatval($data['amount']);/** @var \Transaction $transaction */foreach ($model->transactions()->get() as $transaction) {@@ -161,91 +158,37 @@ class TransactionJournal implements TransactionJournalInterface, CUDInterface, C$journal->isValid();$errors = $journal->getErrors();- if (!isset($model['what'])) {- $errors->add('description', 'Internal error: need to know type of transaction!');- }/*- * Amount+ * Is not in rules.*/- if (isset($model['amount']) && floatval($model['amount']) < 0.01) {- $errors->add('amount', 'Amount must be > 0.01');- } else {- if (!isset($model['amount'])) {- $errors->add('amount', 'Amount must be set!');- } else {- $successes->add('amount', 'OK');- }+ if (!isset($model['what'])) {+ $errors->add('description', 'Internal error: need to know type of transaction!');}-/*- * Budget+ * Is not in rules.*/- if (isset($model['budget_id']) && !ctype_digit($model['budget_id'])) {- $errors->add('budget_id', 'Invalid budget');- } else {- $successes->add('budget_id', 'OK');- }+ $errors = $errors->merge($this->_validateAmount($model));+ $errors = $errors->merge($this->_validateBudget($model));+ $errors = $errors->merge($this->_validateAccount($model));- $successes->add('category', 'OK');/*- * Many checks to catch invalid or not-existing accounts.+ * Add "OK"*/- switch (true) {- // this combination is often seen in withdrawals.- case (isset($model['account_id']) && isset($model['expense_account'])):- if (intval($model['account_id']) < 1) {- $errors->add('account_id', 'Invalid account.');- } else {- $successes->add('account_id', 'OK');- }- $successes->add('expense_account', 'OK');- break;- case (isset($model['account_id']) && isset($model['revenue_account'])):- if (intval($model['account_id']) < 1) {- $errors->add('account_id', 'Invalid account.');- } else {- $successes->add('account_id', 'OK');- }- $successes->add('revenue_account', 'OK');- break;- case (isset($model['account_from_id']) && isset($model['account_to_id'])):- if (intval($model['account_from_id']) < 1 || intval($model['account_from_id']) < 1) {- $errors->add('account_from_id', 'Invalid account selected.');- $errors->add('account_to_id', 'Invalid account selected.');-- } else {- if (intval($model['account_from_id']) == intval($model['account_to_id'])) {- $errors->add('account_to_id', 'Cannot be the same as "from" account.');- $errors->add('account_from_id', 'Cannot be the same as "to" account.');- } else {- $successes->add('account_from_id', 'OK');- $successes->add('account_to_id', 'OK');- }- }- break;- case (isset($model['to']) && isset($model['from'])):- if (is_object($model['to']) && is_object($model['from'])) {- $successes->add('from', 'OK');- $successes->add('to', 'OK');- }- break;-- default:- throw new FireflyException('Cannot validate accounts for transaction journal.');- break;- }--- /*- * Add "OK"+ /**+ * else {+ * $successes->add('account_from_id', 'OK');+ * $successes->add('account_to_id', 'OK');+ * }+ * else {*/- if (!$errors->has('description')) {- $successes->add('description', 'OK');- }- if (!$errors->has('date')) {- $successes->add('date', 'OK');+ $list = ['date', 'description', 'amount', 'budget_id', 'from', 'to', 'account_from_id', 'account_to_id', 'category', 'account_id', 'expense_account',+ 'revenue_account'];+ foreach ($list as $entry) {+ if (!$errors->has($entry)) {+ $successes->add($entry, 'OK');+ }}return ['errors' => $errors, 'warnings' => $warnings, 'successes' => $successes];@@ -377,6 +320,85 @@ class TransactionJournal implements TransactionJournalInterface, CUDInterface, Creturn $typeRepository->findByWhat($type);}+ /**+ * @param array $model+ *+ * @return MessageBag+ */+ protected function _validateAmount(array $model)+ {+ $errors = new MessageBag;+ if (isset($model['amount']) && floatval($model['amount']) < 0.01) {+ $errors->add('amount', 'Amount must be > 0.01');+ } else {+ if (!isset($model['amount'])) {+ $errors->add('amount', 'Amount must be set!');+ }+ }++ return $errors;+ }++ /**+ * @param array $model+ *+ * @return MessageBag+ */+ protected function _validateBudget(array $model)+ {+ /*+ * Budget (is not in rules)+ */+ $errors = new MessageBag;+ if (isset($model['budget_id']) && !ctype_digit($model['budget_id'])) {+ $errors->add('budget_id', 'Invalid budget');+ }++ return $errors;+ }++ /**+ * @param array $model+ *+ * @return MessageBag+ * @throws FireflyException+ */+ protected function _validateAccount(array $model)+ {+ $errors = new MessageBag;+ switch (true) {+ // this combination is often seen in withdrawals.+ case (isset($model['account_id']) && isset($model['expense_account'])):+ if (intval($model['account_id']) < 1) {+ $errors->add('account_id', 'Invalid account.');+ }+ break;+ case (isset($model['account_id']) && isset($model['revenue_account'])):+ if (intval($model['account_id']) < 1) {+ $errors->add('account_id', 'Invalid account.');+ }+ break;+ case (isset($model['account_from_id']) && isset($model['account_to_id'])):+ if (intval($model['account_from_id']) < 1 || intval($model['account_from_id']) < 1) {+ $errors->add('account_from_id', 'Invalid account selected.');+ $errors->add('account_to_id', 'Invalid account selected.');++ } else {+ if (intval($model['account_from_id']) == intval($model['account_to_id'])) {+ $errors->add('account_to_id', 'Cannot be the same as "from" account.');+ $errors->add('account_from_id', 'Cannot be the same as "to" account.');+ }+ }+ break;++ default:+ throw new FireflyException('Cannot validate accounts for transaction journal.');+ break;+ }++ return $errors;+ }+/*** Returns an object with id $id.*diff --git a/app/lib/FireflyIII/Database/TransactionType/TransactionType.php b/app/lib/FireflyIII/Database/TransactionType/TransactionType.phpindex b3b5191de4..2159e5d62a 100644--- a/app/lib/FireflyIII/Database/TransactionType/TransactionType.php+++ b/app/lib/FireflyIII/Database/TransactionType/TransactionType.php@@ -96,9 +96,10 @@ class TransactionType implements CUDInterface, CommonDatabaseCallsInterface'withdrawal' => 'Withdrawal','deposit' => 'Deposit',];- if(!isset($translation[$what])) {+ if (!isset($translation[$what])) {throw new FireflyException('Cannot find transaction type described as "' . e($what) . '".');}+return \TransactionType::whereType($translation[$what])->first();}diff --git a/app/lib/FireflyIII/Helper/TransactionJournal/Helper.php b/app/lib/FireflyIII/Helper/TransactionJournal/Helper.phpindex 304cef0c5d..f2f9b0f313 100644--- a/app/lib/FireflyIII/Helper/TransactionJournal/Helper.php+++ b/app/lib/FireflyIII/Helper/TransactionJournal/Helper.php@@ -12,15 +12,6 @@ use Illuminate\Support\Collection;class Helper implements HelperInterface{- /**- * @param $what- *- * @return int- */- public function getTransactionTypeIdByWhat($what) {-- }-/**** Get the account_id, which is the asset account that paid for the transaction.@@ -49,7 +40,7 @@ class Helper implements HelperInterface/** @var \FireflyIII\Database\Account\Account $accountRepository */$accountRepository = \App::make('FireflyIII\Database\Account\Account');- return $accountRepository->getAssetAccounts();+ return $accountRepository->getAccountsByType(['Default account', 'Asset account']);}/**@@ -90,4 +81,14 @@ class Helper implements HelperInterface}+ /**+ * @param $what+ *+ * @return int+ */+ public function getTransactionTypeIdByWhat($what)+ {++ }+}diff --git a/app/lib/FireflyIII/Report/Report.php b/app/lib/FireflyIII/Report/Report.phpindex f3040fe30f..748b2f5f49 100644--- a/app/lib/FireflyIII/Report/Report.php+++ b/app/lib/FireflyIII/Report/Report.php@@ -11,8 +11,9 @@ use Illuminate\Database\Query\JoinClause;use Illuminate\Support\Collection;/**- * Class Report+ * @SuppressWarnings("CamelCase") // I'm fine with this.*+ * Class Report** @package FireflyIII\Report*/diff --git a/app/lib/FireflyIII/Report/ReportQuery.php b/app/lib/FireflyIII/Report/ReportQuery.phpindex 1a143cbb44..a53618adcd 100644--- a/app/lib/FireflyIII/Report/ReportQuery.php+++ b/app/lib/FireflyIII/Report/ReportQuery.php@@ -68,16 +68,13 @@ class ReportQuery implements ReportQueryInterface})->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'otherJournals.id')- ->before($end)- ->after($start)+ ->before($end)->after($start)->where('transaction_types.type', 'Withdrawal')->where('transaction_journals.user_id', \Auth::user()->id)- ->whereNull('budget_transaction_journal.budget_id')- ->whereNull('transaction_journals.deleted_at')+ ->whereNull('budget_transaction_journal.budget_id')->whereNull('transaction_journals.deleted_at')->whereNull('otherJournals.deleted_at')->where('transactions.account_id', $account->id)- ->whereNotNull('transaction_group_transaction_journal.transaction_group_id')- ->groupBy('transaction_journals.id')+ ->whereNotNull('transaction_group_transaction_journal.transaction_group_id')->groupBy('transaction_journals.id')->get(['transaction_journals.id as transferId',diff --git a/app/lib/FireflyIII/Shared/Toolkit/Date.php b/app/lib/FireflyIII/Shared/Toolkit/Date.phpindex 3f7b321216..7b41d9d273 100644--- a/app/lib/FireflyIII/Shared/Toolkit/Date.php+++ b/app/lib/FireflyIII/Shared/Toolkit/Date.php@@ -13,7 +13,7 @@ use FireflyIII\Exception\FireflyException;class Date{/**- * @param Carbon $theDate+ * @param Carbon $theDate* @param $repeatFreq* @param $skip*@@ -25,41 +25,37 @@ class Date$date = clone $theDate;$add = ($skip + 1);- switch ($repeatFreq) {- default:- throw new FireflyException('Cannot do addPeriod for $repeat_freq "' . $repeatFreq . '"');- break;- case 'daily':- $date->addDays($add);- break;- case 'week':- case 'weekly':- $date->addWeeks($add);- break;- case 'month':- case 'monthly':- $date->addMonths($add);- break;- case 'quarter':- case 'quarterly':- $months = $add * 3;- $date->addMonths($months);- break;- case 'half-year':- $months = $add * 6;- $date->addMonths($months);- break;- case 'year':- case 'yearly':- $date->addYears($add);- break;+ $functionMap = [+ 'daily' => 'addDays',+ 'weekly' => 'addWeeks',+ 'week' => 'addWeeks',+ 'month' => 'addMonths',+ 'monthly' => 'addMonths',+ 'quarter' => 'addMonths',+ 'quarterly' => 'addMonths',+ 'half-year' => 'addMonths',+ 'year' => 'addYears',+ 'yearly' => 'addYears',+ ];+ $modifierMap = [+ 'quarter' => 3,+ 'quarterly' => 3,+ 'half-year' => 6,+ ];+ if (!isset($functionMap[$repeatFreq])) {+ throw new FireflyException('Cannot do addPeriod for $repeat_freq "' . $repeatFreq . '"');+ }+ if (isset($modifierMap[$repeatFreq])) {+ $add = $add * $modifierMap[$repeatFreq];}+ $function = $functionMap[$repeatFreq];+ $date->$function($add);return $date;}/**- * @param Carbon $theCurrentEnd+ * @param Carbon $theCurrentEnd* @param $repeatFreq** @return Carbon@@ -68,41 +64,47 @@ class Datepublic function endOfPeriod(Carbon $theCurrentEnd, $repeatFreq){$currentEnd = clone $theCurrentEnd;- switch ($repeatFreq) {- default:- throw new FireflyException('Cannot do endOfPeriod for $repeat_freq ' . $repeatFreq);- break;- case 'daily':- $currentEnd->addDay();- break;- case 'week':- case 'weekly':- $currentEnd->addWeek()->subDay();- break;- case 'month':- case 'monthly':- $currentEnd->addMonth()->subDay();- break;- case 'quarter':- case 'quarterly':- $currentEnd->addMonths(3)->subDay();- break;- case 'half-year':- $currentEnd->addMonths(6)->subDay();- break;- case 'year':- case 'yearly':- $currentEnd->addYear()->subDay();- break;++ $functionMap = [+ 'daily' => 'addDay',+ 'week' => 'addWeek',+ 'weekly' => 'addWeek',+ 'month' => 'addMonth',+ 'monthly' => 'addMonth',+ 'quarter' => 'addMonths',+ 'quarterly' => 'addMonths',+ 'half-year' => 'addMonths',+ 'year' => 'addYear',+ 'yearly' => 'addYear',+ ];+ $modifierMap = [+ 'quarter' => 3,+ 'quarterly' => 3,+ 'half-year' => 6,+ ];++ $subDay = ['week', 'weekly', 'month', 'monthly', 'quarter', 'quarterly', 'half-year', 'year', 'yearly'];++ if (!isset($functionMap[$repeatFreq])) {+ throw new FireflyException('Cannot do endOfPeriod for $repeat_freq ' . $repeatFreq);+ }+ $function = $functionMap[$repeatFreq];+ if (isset($modifierMap[$repeatFreq])) {+ $currentEnd->$function($modifierMap[$repeatFreq]);+ } else {+ $currentEnd->$function();+ }+ if (in_array($repeatFreq, $subDay)) {+ $currentEnd->subDay();}return $currentEnd;}/**- * @param Carbon $theCurrentEnd+ * @param Carbon $theCurrentEnd* @param $repeatFreq- * @param Carbon $maxDate+ * @param Carbon $maxDate** @return Carbon* @throws FireflyException@@ -149,7 +151,7 @@ class Date}/**- * @param Carbon $date+ * @param Carbon $date* @param $repeatFrequency** @return string@@ -183,7 +185,7 @@ class Date}/**- * @param Carbon $theDate+ * @param Carbon $theDate* @param $repeatFreq** @return Carbon@@ -228,7 +230,7 @@ class Date}/**- * @param Carbon $theDate+ * @param Carbon $theDate* @param $repeatFreq* @param int $subtract*diff --git a/app/lib/FireflyIII/Shared/Toolkit/Filter.php b/app/lib/FireflyIII/Shared/Toolkit/Filter.phpindex 9be82e313a..f8fdf42037 100644--- a/app/lib/FireflyIII/Shared/Toolkit/Filter.php+++ b/app/lib/FireflyIII/Shared/Toolkit/Filter.php@@ -69,36 +69,29 @@ class Filter*/protected function updateStartDate($range, Carbon $start){- switch ($range) {- default:- throw new FireflyException('updateStartDate cannot handle $range ' . $range);- break;- case '1D':- $start->startOfDay();- break;- case '1W':- $start->startOfWeek();- break;- case '1M':- $start->startOfMonth();- break;- case '3M':- $start->firstOfQuarter();- break;- case '6M':- if (intval($start->format('m')) >= 7) {- $start->startOfYear()->addMonths(6);- } else {- $start->startOfYear();- }- break;- case '1Y':- $start->startOfYear();- break;- }+ $functionMap = [+ '1D' => 'startOfDay',+ '1W' => 'startOfWeek',+ '1M' => 'startOfMonth',+ '3M' => 'firstOfQuarter',+ '1Y' => 'startOfYear',+ ];+ if (isset($functionMap[$range])) {+ $function = $functionMap[$range];+ $start->$function();- return $start;+ return $start;+ }+ if ($range == '6M') {+ if (intval($start->format('m')) >= 7) {+ $start->startOfYear()->addMonths(6);+ } else {+ $start->startOfYear();+ }+ return $start;+ }+ throw new FireflyException('updateStartDate cannot handle $range ' . $range);}/**diff --git a/app/lib/FireflyIII/Shared/Toolkit/Form.php b/app/lib/FireflyIII/Shared/Toolkit/Form.phpindex 55457dc7d5..a5475a0456 100644--- a/app/lib/FireflyIII/Shared/Toolkit/Form.php+++ b/app/lib/FireflyIII/Shared/Toolkit/Form.php@@ -32,7 +32,7 @@ class Form$title = null;foreach ($fields as $field) {- if (is_null($title) && isset($entry->$field)) {+ if (isset($entry->$field)) {$title = $entry->$field;}}diff --git a/app/tests/factories/PiggyBank.php b/app/tests/factories/PiggyBank.phpindex 36f89debf8..aaab88cd71 100644--- a/app/tests/factories/PiggyBank.php+++ b/app/tests/factories/PiggyBank.php@@ -15,8 +15,12 @@ League\FactoryMuffin\Facade::define(return $set[rand(0, count($set) - 1)];},- 'rep_every' => function() {return rand(0,3);},- 'rep_times' => function() {return rand(0,3);},+ 'rep_every' => function () {+ return rand(0, 3);+ },+ 'rep_times' => function () {+ return rand(0, 3);+ },'reminder' => function () {$set = ['day', 'week', 'quarter', 'month', 'year'];diff --git a/app/tests/factories/Transaction.php b/app/tests/factories/Transaction.phpindex 9f812b8ce0..39f50f7ca5 100644--- a/app/tests/factories/Transaction.php+++ b/app/tests/factories/Transaction.php@@ -5,8 +5,8 @@ League\FactoryMuffin\Facade::define('account_id' => 'factory|Account','transaction_journal_id' => 'factory|TransactionJournal','description' => 'sentence',- 'amount' => function() {- return round(rand(100,10000) / 100,2);+ 'amount' => function () {+ return round(rand(100, 10000) / 100, 2);}]);