Cleanup various factories and libraries.

This commit is contained in:
James Cole 2015-01-17 08:58:49 +01:00
parent 33c830a432
commit 027b954b50
12 changed files with 227 additions and 228 deletions

View File

@ -88,51 +88,31 @@ class Account implements CUDInterface, CommonDatabaseCallsInterface, AccountInte
{ {
$opposingData = ['name' => $account->name . ' Initial Balance', 'active' => 0, 'what' => 'initial']; $opposingData = ['name' => $account->name . ' Initial Balance', 'active' => 0, 'what' => 'initial'];
$opposingAccount = $this->store($opposingData); $opposingAccount = $this->store($opposingData);
$balance = floatval($data['openingbalance']);
/* $date = new Carbon($data['openingbalancedate']);
* Create a journal from opposing to account or vice versa. /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $journals */
*/ $journals = \App::make('FireflyIII\Database\TransactionJournal\TransactionJournal');
$balance = floatval($data['openingbalance']); $fromAccount = $opposingAccount;
$date = new Carbon($data['openingbalancedate']); $toAccount = $account;
/** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $tj */
$tj = \App::make('FireflyIII\Database\TransactionJournal\TransactionJournal');
if ($balance < 0) { if ($balance < 0) {
// first transaction draws money from the new account to the opposing $fromAccount = $account;
$from = $account; $toAccount = $opposingAccount;
$to = $opposingAccount;
} else {
// first transaction puts money into account
$from = $opposingAccount;
$to = $account;
} }
// data for transaction journal: // data for transaction journal:
$balance = $balance < 0 ? $balance * -1 : $balance; $balance = $balance < 0 ? $balance * -1 : $balance;
// find the account type:
/** @var \FireflyIII\Database\TransactionType\TransactionType $typeRepository */ /** @var \FireflyIII\Database\TransactionType\TransactionType $typeRepository */
$typeRepository = \App::make('FireflyIII\Database\TransactionType\TransactionType'); $typeRepository = \App::make('FireflyIII\Database\TransactionType\TransactionType');
$type = $typeRepository->findByWhat('opening'); $type = $typeRepository->findByWhat('opening');
$currency = \Amount::getDefaultCurrency();
// find the currency. $opening = ['transaction_type_id' => $type->id, 'transaction_currency_id' => $currency->id, 'amount' => $balance, 'from' => $fromAccount,
$currency = \Amount::getDefaultCurrency(); 'completed' => 0, 'currency' => 'EUR', 'what' => 'opening', 'to' => $toAccount, 'date' => $date,
'description' => 'Opening balance for new account ' . $account->name,];
$opening = [ $validation = $journals->validate($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,];
$validation = $tj->validate($opening);
if ($validation['errors']->count() == 0) { if ($validation['errors']->count() == 0) {
$tj->store($opening); $journals->store($opening);
return true; return true;
} else { } else {
@ -141,6 +121,7 @@ class Account implements CUDInterface, CommonDatabaseCallsInterface, AccountInte
\App::abort(500); \App::abort(500);
} }
return false;
} }
/** /**

View File

@ -30,13 +30,10 @@ class PiggyBank extends PiggyBankShared implements CUDInterface, CommonDatabaseC
if ($reps->count() == 1) { if ($reps->count() == 1) {
return $reps->first(); return $reps->first();
} }
if ($reps->count() == 0) {
throw new FireflyException('Should always find a piggy bank repetition.');
}
// should filter the one we need: // should filter the one we need:
$repetitions = $reps->filter( $repetitions = $reps->filter(
function (\PiggyBankRepetition $rep) use ($date) { function (\PiggyBankRepetition $rep) use ($date) {
if ($date >= $rep->startdate && $date <= $rep->targetdate) { if ($date->between($rep->startdate, $rep->targetdate)) {
return $rep; return $rep;
} }

View File

@ -117,9 +117,6 @@ class TransactionJournal implements TransactionJournalInterface, CUDInterface, C
$this->storeBudget($data, $model); $this->storeBudget($data, $model);
$this->storeCategory($data, $model); $this->storeCategory($data, $model);
/*
* Now we can update the transactions related to this journal.
*/
$amount = floatval($data['amount']); $amount = floatval($data['amount']);
/** @var \Transaction $transaction */ /** @var \Transaction $transaction */
foreach ($model->transactions()->get() as $transaction) { foreach ($model->transactions()->get() as $transaction) {
@ -161,91 +158,37 @@ class TransactionJournal implements TransactionJournalInterface, CUDInterface, C
$journal->isValid(); $journal->isValid();
$errors = $journal->getErrors(); $errors = $journal->getErrors();
/*
* Is not in rules.
*/
if (!isset($model['what'])) { if (!isset($model['what'])) {
$errors->add('description', 'Internal error: need to know type of transaction!'); $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 = $errors->merge($this->_validateAmount($model));
$errors->add('amount', 'Amount must be > 0.01'); $errors = $errors->merge($this->_validateBudget($model));
} else { $errors = $errors->merge($this->_validateAccount($model));
if (!isset($model['amount'])) {
$errors->add('amount', 'Amount must be set!');
} else {
$successes->add('amount', 'OK');
}
}
/*
* Budget
*/
if (isset($model['budget_id']) && !ctype_digit($model['budget_id'])) {
$errors->add('budget_id', 'Invalid budget');
} else {
$successes->add('budget_id', 'OK');
}
$successes->add('category', 'OK');
/*
* Many checks to catch invalid or not-existing accounts.
*/
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" * Add "OK"
*/ */
if (!$errors->has('description')) {
$successes->add('description', 'OK'); /**
} * else {
if (!$errors->has('date')) { * $successes->add('account_from_id', 'OK');
$successes->add('date', 'OK'); * $successes->add('account_to_id', 'OK');
* }
* else {
*/
$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]; return ['errors' => $errors, 'warnings' => $warnings, 'successes' => $successes];
@ -377,6 +320,85 @@ class TransactionJournal implements TransactionJournalInterface, CUDInterface, C
return $typeRepository->findByWhat($type); return $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. * Returns an object with id $id.
* *

View File

@ -96,9 +96,10 @@ class TransactionType implements CUDInterface, CommonDatabaseCallsInterface
'withdrawal' => 'Withdrawal', 'withdrawal' => 'Withdrawal',
'deposit' => 'Deposit', 'deposit' => 'Deposit',
]; ];
if(!isset($translation[$what])) { if (!isset($translation[$what])) {
throw new FireflyException('Cannot find transaction type described as "' . e($what) . '".'); throw new FireflyException('Cannot find transaction type described as "' . e($what) . '".');
} }
return \TransactionType::whereType($translation[$what])->first(); return \TransactionType::whereType($translation[$what])->first();
} }

View File

@ -12,15 +12,6 @@ use Illuminate\Support\Collection;
class Helper implements HelperInterface 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. * 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 */ /** @var \FireflyIII\Database\Account\Account $accountRepository */
$accountRepository = \App::make('FireflyIII\Database\Account\Account'); $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)
{
}
} }

View File

@ -11,8 +11,9 @@ use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
/** /**
* Class Report * @SuppressWarnings("CamelCase") // I'm fine with this.
* *
* Class Report
* *
* @package FireflyIII\Report * @package FireflyIII\Report
*/ */

View File

@ -68,16 +68,13 @@ class ReportQuery implements ReportQueryInterface
} }
) )
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'otherJournals.id') ->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'otherJournals.id')
->before($end) ->before($end)->after($start)
->after($start)
->where('transaction_types.type', 'Withdrawal') ->where('transaction_types.type', 'Withdrawal')
->where('transaction_journals.user_id', \Auth::user()->id) ->where('transaction_journals.user_id', \Auth::user()->id)
->whereNull('budget_transaction_journal.budget_id') ->whereNull('budget_transaction_journal.budget_id')->whereNull('transaction_journals.deleted_at')
->whereNull('transaction_journals.deleted_at')
->whereNull('otherJournals.deleted_at') ->whereNull('otherJournals.deleted_at')
->where('transactions.account_id', $account->id) ->where('transactions.account_id', $account->id)
->whereNotNull('transaction_group_transaction_journal.transaction_group_id') ->whereNotNull('transaction_group_transaction_journal.transaction_group_id')->groupBy('transaction_journals.id')
->groupBy('transaction_journals.id')
->get( ->get(
[ [
'transaction_journals.id as transferId', 'transaction_journals.id as transferId',

View File

@ -13,7 +13,7 @@ use FireflyIII\Exception\FireflyException;
class Date class Date
{ {
/** /**
* @param Carbon $theDate * @param Carbon $theDate
* @param $repeatFreq * @param $repeatFreq
* @param $skip * @param $skip
* *
@ -25,41 +25,37 @@ class Date
$date = clone $theDate; $date = clone $theDate;
$add = ($skip + 1); $add = ($skip + 1);
switch ($repeatFreq) { $functionMap = [
default: 'daily' => 'addDays',
throw new FireflyException('Cannot do addPeriod for $repeat_freq "' . $repeatFreq . '"'); 'weekly' => 'addWeeks',
break; 'week' => 'addWeeks',
case 'daily': 'month' => 'addMonths',
$date->addDays($add); 'monthly' => 'addMonths',
break; 'quarter' => 'addMonths',
case 'week': 'quarterly' => 'addMonths',
case 'weekly': 'half-year' => 'addMonths',
$date->addWeeks($add); 'year' => 'addYears',
break; 'yearly' => 'addYears',
case 'month': ];
case 'monthly': $modifierMap = [
$date->addMonths($add); 'quarter' => 3,
break; 'quarterly' => 3,
case 'quarter': 'half-year' => 6,
case 'quarterly': ];
$months = $add * 3; if (!isset($functionMap[$repeatFreq])) {
$date->addMonths($months); throw new FireflyException('Cannot do addPeriod for $repeat_freq "' . $repeatFreq . '"');
break;
case 'half-year':
$months = $add * 6;
$date->addMonths($months);
break;
case 'year':
case 'yearly':
$date->addYears($add);
break;
} }
if (isset($modifierMap[$repeatFreq])) {
$add = $add * $modifierMap[$repeatFreq];
}
$function = $functionMap[$repeatFreq];
$date->$function($add);
return $date; return $date;
} }
/** /**
* @param Carbon $theCurrentEnd * @param Carbon $theCurrentEnd
* @param $repeatFreq * @param $repeatFreq
* *
* @return Carbon * @return Carbon
@ -68,41 +64,47 @@ class Date
public function endOfPeriod(Carbon $theCurrentEnd, $repeatFreq) public function endOfPeriod(Carbon $theCurrentEnd, $repeatFreq)
{ {
$currentEnd = clone $theCurrentEnd; $currentEnd = clone $theCurrentEnd;
switch ($repeatFreq) {
default: $functionMap = [
throw new FireflyException('Cannot do endOfPeriod for $repeat_freq ' . $repeatFreq); 'daily' => 'addDay',
break; 'week' => 'addWeek',
case 'daily': 'weekly' => 'addWeek',
$currentEnd->addDay(); 'month' => 'addMonth',
break; 'monthly' => 'addMonth',
case 'week': 'quarter' => 'addMonths',
case 'weekly': 'quarterly' => 'addMonths',
$currentEnd->addWeek()->subDay(); 'half-year' => 'addMonths',
break; 'year' => 'addYear',
case 'month': 'yearly' => 'addYear',
case 'monthly': ];
$currentEnd->addMonth()->subDay(); $modifierMap = [
break; 'quarter' => 3,
case 'quarter': 'quarterly' => 3,
case 'quarterly': 'half-year' => 6,
$currentEnd->addMonths(3)->subDay(); ];
break;
case 'half-year': $subDay = ['week', 'weekly', 'month', 'monthly', 'quarter', 'quarterly', 'half-year', 'year', 'yearly'];
$currentEnd->addMonths(6)->subDay();
break; if (!isset($functionMap[$repeatFreq])) {
case 'year': throw new FireflyException('Cannot do endOfPeriod for $repeat_freq ' . $repeatFreq);
case 'yearly': }
$currentEnd->addYear()->subDay(); $function = $functionMap[$repeatFreq];
break; if (isset($modifierMap[$repeatFreq])) {
$currentEnd->$function($modifierMap[$repeatFreq]);
} else {
$currentEnd->$function();
}
if (in_array($repeatFreq, $subDay)) {
$currentEnd->subDay();
} }
return $currentEnd; return $currentEnd;
} }
/** /**
* @param Carbon $theCurrentEnd * @param Carbon $theCurrentEnd
* @param $repeatFreq * @param $repeatFreq
* @param Carbon $maxDate * @param Carbon $maxDate
* *
* @return Carbon * @return Carbon
* @throws FireflyException * @throws FireflyException
@ -149,7 +151,7 @@ class Date
} }
/** /**
* @param Carbon $date * @param Carbon $date
* @param $repeatFrequency * @param $repeatFrequency
* *
* @return string * @return string
@ -183,7 +185,7 @@ class Date
} }
/** /**
* @param Carbon $theDate * @param Carbon $theDate
* @param $repeatFreq * @param $repeatFreq
* *
* @return Carbon * @return Carbon
@ -228,7 +230,7 @@ class Date
} }
/** /**
* @param Carbon $theDate * @param Carbon $theDate
* @param $repeatFreq * @param $repeatFreq
* @param int $subtract * @param int $subtract
* *

View File

@ -69,36 +69,29 @@ class Filter
*/ */
protected function updateStartDate($range, Carbon $start) protected function updateStartDate($range, Carbon $start)
{ {
switch ($range) { $functionMap = [
default: '1D' => 'startOfDay',
throw new FireflyException('updateStartDate cannot handle $range ' . $range); '1W' => 'startOfWeek',
break; '1M' => 'startOfMonth',
case '1D': '3M' => 'firstOfQuarter',
$start->startOfDay(); '1Y' => 'startOfYear',
break; ];
case '1W': if (isset($functionMap[$range])) {
$start->startOfWeek(); $function = $functionMap[$range];
break; $start->$function();
case '1M':
$start->startOfMonth(); return $start;
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;
} }
if ($range == '6M') {
if (intval($start->format('m')) >= 7) {
$start->startOfYear()->addMonths(6);
} else {
$start->startOfYear();
}
return $start; return $start;
}
throw new FireflyException('updateStartDate cannot handle $range ' . $range);
} }
/** /**

View File

@ -32,7 +32,7 @@ class Form
$title = null; $title = null;
foreach ($fields as $field) { foreach ($fields as $field) {
if (is_null($title) && isset($entry->$field)) { if (isset($entry->$field)) {
$title = $entry->$field; $title = $entry->$field;
} }
} }

View File

@ -15,8 +15,12 @@ League\FactoryMuffin\Facade::define(
return $set[rand(0, count($set) - 1)]; return $set[rand(0, count($set) - 1)];
}, },
'rep_every' => function() {return rand(0,3);}, 'rep_every' => function () {
'rep_times' => function() {return rand(0,3);}, return rand(0, 3);
},
'rep_times' => function () {
return rand(0, 3);
},
'reminder' => function () { 'reminder' => function () {
$set = ['day', 'week', 'quarter', 'month', 'year']; $set = ['day', 'week', 'quarter', 'month', 'year'];

View File

@ -5,8 +5,8 @@ League\FactoryMuffin\Facade::define(
'account_id' => 'factory|Account', 'account_id' => 'factory|Account',
'transaction_journal_id' => 'factory|TransactionJournal', 'transaction_journal_id' => 'factory|TransactionJournal',
'description' => 'sentence', 'description' => 'sentence',
'amount' => function() { 'amount' => function () {
return round(rand(100,10000) / 100,2); return round(rand(100, 10000) / 100, 2);
} }
] ]
); );