Code cleanup.

This commit is contained in:
James Cole 2015-05-17 10:30:18 +02:00
parent beedf7d780
commit 63050907b9
14 changed files with 91 additions and 138 deletions

View File

@ -44,6 +44,7 @@ class Handler extends ExceptionHandler
* Report or log an exception. * Report or log an exception.
* *
* This is a great spot to send exceptions to Sentry, Bugsnag, etc. * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
* @SuppressWarnings(PHPMD.ShortVariable)
* *
* @param \Exception $e * @param \Exception $e
* *

View File

@ -6,7 +6,6 @@ use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankEvent; use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use Log;
/** /**
* Class ConnectJournalToPiggyBank * Class ConnectJournalToPiggyBank
@ -28,6 +27,8 @@ class ConnectJournalToPiggyBank
/** /**
* Handle the event when journal is saved. * Handle the event when journal is saved.
* *
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*
* @param JournalCreated $event * @param JournalCreated $event
* *
* @return boolean * @return boolean
@ -37,45 +38,25 @@ class ConnectJournalToPiggyBank
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
$journal = $event->journal; $journal = $event->journal;
$piggyBankId = $event->piggyBankId; $piggyBankId = $event->piggyBankId;
if (intval($piggyBankId) < 1) {
return false;
}
Log::debug('JournalCreated event: ' . $journal->id . ', ' . $piggyBankId);
/** @var PiggyBank $piggyBank */ /** @var PiggyBank $piggyBank */
$piggyBank = Auth::user()->piggybanks()->where('piggy_banks.id', $piggyBankId)->first(['piggy_banks.*']); $piggyBank = Auth::user()->piggybanks()->where('piggy_banks.id', $piggyBankId)->first(['piggy_banks.*']);
if (is_null($piggyBank) || $journal->transactionType->type != 'Transfer') { if (is_null($piggyBank)) {
return false;
}
Log::debug('Found a piggy bank');
$amount = $journal->amount;
Log::debug('Amount: ' . $amount);
if ($amount == 0) {
return false; return false;
} }
// update piggy bank rep for date of transaction journal. // update piggy bank rep for date of transaction journal.
$repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first(); $repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first();
if (is_null($repetition)) { if (is_null($repetition)) {
Log::debug('Found no repetition for piggy bank for date ' . $journal->date->format('Y M d'));
return false; return false;
} }
Log::debug('Found rep! ' . $repetition->id); $amount = $journal->amount;
/*
* Add amount when
*/
/** @var Transaction $transaction */ /** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) { foreach ($journal->transactions()->get() as $transaction) {
if ($transaction->account_id == $piggyBank->account_id) { if ($transaction->account_id == $piggyBank->account_id) {
if ($transaction->amount < 0) { if ($transaction->amount < 0) {
$amount = $amount * -1; $amount = $transaction->amount * -1;
Log::debug('Transaction is away from piggy, so amount becomes ' . $amount);
} else {
Log::debug('Transaction is to from piggy, so amount stays ' . $amount);
} }
} }
} }
@ -83,14 +64,7 @@ class ConnectJournalToPiggyBank
$repetition->currentamount += $amount; $repetition->currentamount += $amount;
$repetition->save(); $repetition->save();
PiggyBankEvent::create( PiggyBankEvent::create(['piggy_bank_id' => $piggyBank->id, 'transaction_journal_id' => $journal->id, 'date' => $journal->date, 'amount' => $amount]);
[
'piggy_bank_id' => $piggyBank->id,
'transaction_journal_id' => $journal->id,
'date' => $journal->date,
'amount' => $amount
]
);
return true; return true;

View File

@ -34,19 +34,19 @@ class Expense
public function addOrCreateExpense(TransactionJournal $entry) public function addOrCreateExpense(TransactionJournal $entry)
{ {
$id = $entry->account_id; $accountId = $entry->account_id;
if (!$this->expenses->has($id)) { if (!$this->expenses->has($accountId)) {
$newObject = new stdClass; $newObject = new stdClass;
$newObject->amount = floatval($entry->queryAmount); $newObject->amount = floatval($entry->queryAmount);
$newObject->name = $entry->name; $newObject->name = $entry->name;
$newObject->count = 1; $newObject->count = 1;
$newObject->id = $id; $newObject->id = $accountId;
$this->expenses->put($id, $newObject); $this->expenses->put($accountId, $newObject);
} else { } else {
$existing = $this->expenses->get($id); $existing = $this->expenses->get($accountId);
$existing->amount += floatval($entry->queryAmount); $existing->amount += floatval($entry->queryAmount);
$existing->count++; $existing->count++;
$this->expenses->put($id, $existing); $this->expenses->put($accountId, $existing);
} }
} }

View File

@ -35,19 +35,19 @@ class Income
public function addOrCreateIncome(TransactionJournal $entry) public function addOrCreateIncome(TransactionJournal $entry)
{ {
$id = $entry->account_id; $accountId = $entry->account_id;
if (!$this->incomes->has($id)) { if (!$this->incomes->has($accountId)) {
$newObject = new stdClass; $newObject = new stdClass;
$newObject->amount = floatval($entry->queryAmount); $newObject->amount = floatval($entry->queryAmount);
$newObject->name = $entry->name; $newObject->name = $entry->name;
$newObject->count = 1; $newObject->count = 1;
$newObject->id = $id; $newObject->id = $accountId;
$this->incomes->put($id, $newObject); $this->incomes->put($accountId, $newObject);
} else { } else {
$existing = $this->incomes->get($id); $existing = $this->incomes->get($accountId);
$existing->amount += floatval($entry->queryAmount); $existing->amount += floatval($entry->queryAmount);
$existing->count++; $existing->count++;
$this->incomes->put($id, $existing); $this->incomes->put($accountId, $existing);
} }
} }

View File

@ -40,18 +40,16 @@ class ReportQuery implements ReportQueryInterface
{ {
$query = $this->queryJournalsWithTransactions($start, $end); $query = $this->queryJournalsWithTransactions($start, $end);
if ($includeShared === false) { if ($includeShared === false) {
// only get withdrawals not from a shared account
// and transfers from a shared account.
$query->where( $query->where(
function (Builder $query) { function (Builder $query) {
$query->where( $query->where(
function (Builder $q) { function (Builder $q) { // only get withdrawals not from a shared account
$q->where('transaction_types.type', 'Withdrawal'); $q->where('transaction_types.type', 'Withdrawal');
$q->where('acm_from.data', '!=', '"sharedAsset"'); $q->where('acm_from.data', '!=', '"sharedAsset"');
} }
); );
$query->orWhere( $query->orWhere(
function (Builder $q) { function (Builder $q) { // and transfers from a shared account.
$q->where('transaction_types.type', 'Transfer'); $q->where('transaction_types.type', 'Transfer');
$q->where('acm_to.data', '=', '"sharedAsset"'); $q->where('acm_to.data', '=', '"sharedAsset"');
} }
@ -59,24 +57,14 @@ class ReportQuery implements ReportQueryInterface
} }
); );
} else { } else {
// any withdrawal is fine. $query->where('transaction_types.type', 'Withdrawal'); // any withdrawal is fine.
$query->where('transaction_types.type', 'Withdrawal');
} }
$query->groupBy('transaction_journals.id')->orderBy('transaction_journals.date'); $query->groupBy('transaction_journals.id')->orderBy('transaction_journals.date');
// get everything, decrypt and return // get everything, decrypt and return
$data = $query->get( $data = $query->get(['transaction_journals.id', 'transaction_journals.description', 'transaction_journals.encrypted', 'transaction_types.type',
['transaction_journals.id',
'transaction_journals.description',
'transaction_journals.encrypted',
'transaction_types.type',
DB::Raw('SUM(`t_from`.`amount`) as `queryAmount`'), DB::Raw('SUM(`t_from`.`amount`) as `queryAmount`'),
'transaction_journals.date', 'transaction_journals.date', 't_to.account_id as account_id', 'ac_to.name as name', 'ac_to.encrypted as account_encrypted']);
't_to.account_id as account_id',
'ac_to.name as name',
'ac_to.encrypted as account_encrypted'
]
);
$data->each( $data->each(
function (Model $object) { function (Model $object) {

View File

@ -52,9 +52,7 @@ class TransactionController extends Controller
$subTitle = trans('form.add_new_' . $what); $subTitle = trans('form.add_new_' . $what);
foreach ($respondTo as $r) { foreach ($respondTo as $r) {
if (!is_null(Input::get($r))) { $preFilled[$r] = Input::get($r);
$preFilled[$r] = Input::get($r);
}
} }
Session::put('preFilled', $preFilled); Session::put('preFilled', $preFilled);
@ -269,7 +267,9 @@ class TransactionController extends Controller
// rescan journal, UpdateJournalConnection // rescan journal, UpdateJournalConnection
event(new JournalSaved($journal)); event(new JournalSaved($journal));
// ConnectJournalToPiggyBank // ConnectJournalToPiggyBank
event(new JournalCreated($journal, intval($request->get('piggy_bank_id')))); if ($journal->transactionType->type == 'Transfer' && intval($request->get('piggy_bank_id')) > 0) {
event(new JournalCreated($journal, intval($request->get('piggy_bank_id'))));
}
$repository->deactivateReminder($request->get('reminder_id')); $repository->deactivateReminder($request->get('reminder_id'));

View File

@ -43,6 +43,7 @@ class Range
* *
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @param \Closure $theNext * @param \Closure $theNext
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* *
* @return mixed * @return mixed
*/ */
@ -63,9 +64,6 @@ class Range
Session::put('end', $end); Session::put('end', $end);
} }
if (!Session::has('first')) { if (!Session::has('first')) {
/**
* Get helper thing.
*/
/** @var \FireflyIII\Repositories\Journal\JournalRepositoryInterface $repository */ /** @var \FireflyIII\Repositories\Journal\JournalRepositoryInterface $repository */
$repository = App::make('FireflyIII\Repositories\Journal\JournalRepositoryInterface'); $repository = App::make('FireflyIII\Repositories\Journal\JournalRepositoryInterface');
$journal = $repository->first(); $journal = $repository->first();
@ -75,16 +73,12 @@ class Range
Session::put('first', Carbon::now()->startOfYear()); Session::put('first', Carbon::now()->startOfYear());
} }
} }
// set current / next / prev month.
$current = Carbon::now()->format('F Y'); $current = Carbon::now()->format('F Y');
$next = Carbon::now()->endOfMonth()->addDay()->format('F Y'); $next = Carbon::now()->endOfMonth()->addDay()->format('F Y');
$prev = Carbon::now()->startOfMonth()->subDay()->format('F Y'); $prev = Carbon::now()->startOfMonth()->subDay()->format('F Y');
View::share('currentMonthName', $current); View::share('currentMonthName', $current);
View::share('previousMonthName', $prev); View::share('previousMonthName', $prev);
View::share('nextMonthName', $next); View::share('nextMonthName', $next);
} }
return $theNext($request); return $theNext($request);

View File

@ -50,12 +50,11 @@ class JournalFormRequest extends Request
/** /**
* @return array * @return array
* @throws Exception * @throws Exception
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function rules() public function rules()
{ {
// can we switch on the "what"? $what = Input::get('what');
$what = Input::get('what');
$rules = [ $rules = [
'description' => 'required|min:1,max:255', 'description' => 'required|min:1,max:255',
'what' => 'required|in:withdrawal,deposit,transfer', 'what' => 'required|in:withdrawal,deposit,transfer',
@ -74,8 +73,6 @@ class JournalFormRequest extends Request
if (intval(Input::get('budget_id')) != 0) { if (intval(Input::get('budget_id')) != 0) {
$rules['budget_id'] = 'exists:budgets,id|belongsToUser:budgets'; $rules['budget_id'] = 'exists:budgets,id|belongsToUser:budgets';
} }
break; break;
case 'deposit': case 'deposit':
$rules['category'] = 'between:1,255'; $rules['category'] = 'between:1,255';
@ -93,7 +90,5 @@ class JournalFormRequest extends Request
} }
return $rules; return $rules;
} }
} }

View File

@ -28,7 +28,7 @@ class Account extends Model
/** /**
* @param array $fields * @param array $fields
* * @SuppressWarnings(PHPMD.CyclomaticComplexity)
* *
* @return Account|null * @return Account|null
*/ */

View File

@ -37,6 +37,7 @@ class Category extends Model
/** /**
* @param array $fields * @param array $fields
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* *
* @return Account|null * @return Account|null
*/ */

View File

@ -29,6 +29,8 @@ class Tag extends Model
/** /**
* @param array $fields * @param array $fields
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* *
* @return Tag|null * @return Tag|null
*/ */

View File

@ -49,7 +49,47 @@ class EventServiceProvider extends ServiceProvider
public function boot(DispatcherContract $events) public function boot(DispatcherContract $events)
{ {
parent::boot($events); parent::boot($events);
$this->registerDeleteEvents();
$this->registerCreateEvents();
BudgetLimit::saved(
function (BudgetLimit $budgetLimit) {
$end = Navigation::addPeriod(clone $budgetLimit->startdate, $budgetLimit->repeat_freq, 0);
$end->subDay();
$set = $budgetLimit->limitrepetitions()->where('startdate', $budgetLimit->startdate->format('Y-m-d'))->where('enddate', $end->format('Y-m-d'))
->get();
if ($set->count() == 0) {
$repetition = new LimitRepetition;
$repetition->startdate = $budgetLimit->startdate;
$repetition->enddate = $end;
$repetition->amount = $budgetLimit->amount;
$repetition->budgetLimit()->associate($budgetLimit);
try {
$repetition->save();
} catch (QueryException $e) {
Log::error('Trying to save new LimitRepetition failed!');
Log::error($e->getMessage());
}
} else {
if ($set->count() == 1) {
$repetition = $set->first();
$repetition->amount = $budgetLimit->amount;
$repetition->save();
}
}
}
);
}
/**
*
*/
protected function registerDeleteEvents()
{
TransactionJournal::deleted( TransactionJournal::deleted(
function (TransactionJournal $journal) { function (TransactionJournal $journal) {
@ -59,8 +99,6 @@ class EventServiceProvider extends ServiceProvider
} }
} }
); );
PiggyBank::deleting( PiggyBank::deleting(
function (PiggyBank $piggyBank) { function (PiggyBank $piggyBank) {
$reminders = $piggyBank->reminders()->get(); $reminders = $piggyBank->reminders()->get();
@ -82,6 +120,14 @@ class EventServiceProvider extends ServiceProvider
} }
); );
}
/**
*
*/
protected function registerCreateEvents()
{
// move this routine to a filter // move this routine to a filter
// in case of repeated piggy banks and/or other problems. // in case of repeated piggy banks and/or other problems.
PiggyBank::created( PiggyBank::created(
@ -94,47 +140,6 @@ class EventServiceProvider extends ServiceProvider
$repetition->save(); $repetition->save();
} }
); );
BudgetLimit::saved(
function (BudgetLimit $budgetLimit) {
$end = Navigation::addPeriod(clone $budgetLimit->startdate, $budgetLimit->repeat_freq, 0);
$end->subDay();
$set = $budgetLimit->limitrepetitions()->where('startdate', $budgetLimit->startdate->format('Y-m-d'))->where('enddate', $end->format('Y-m-d'))
->get();
/*
* Create new LimitRepetition:
*/
if ($set->count() == 0) {
$repetition = new LimitRepetition;
$repetition->startdate = $budgetLimit->startdate;
$repetition->enddate = $end;
$repetition->amount = $budgetLimit->amount;
$repetition->budgetLimit()->associate($budgetLimit);
try {
$repetition->save();
} catch (QueryException $e) {
Log::error('Trying to save new LimitRepetition failed!');
Log::error($e->getMessage());
}
} else {
if ($set->count() == 1) {
/*
* Update existing one.
*/
$repetition = $set->first();
$repetition->amount = $budgetLimit->amount;
$repetition->save();
}
}
}
);
} }
} }

View File

@ -46,6 +46,9 @@ class FireflyServiceProvider extends ServiceProvider
Twig::addExtension(new Translation); Twig::addExtension(new Translation);
} }
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function register() public function register()
{ {

View File

@ -65,21 +65,11 @@ class Navigation
$currentEnd = clone $theCurrentEnd; $currentEnd = clone $theCurrentEnd;
$functionMap = [ $functionMap = [
'1D' => 'addDay', '1D' => 'addDay', 'daily' => 'addDay',
'daily' => 'addDay', '1W' => 'addWeek', 'week' => 'addWeek', 'weekly' => 'addWeek',
'1W' => 'addWeek', '1M' => 'addMonth', 'month' => 'addMonth', 'monthly' => 'addMonth',
'week' => 'addWeek', '3M' => 'addMonths', 'quarter' => 'addMonths', 'quarterly' => 'addMonths', '6M' => 'addMonths', 'half-year' => 'addMonths',
'weekly' => 'addWeek', 'year' => 'addYear', 'yearly' => 'addYear',
'1M' => 'addMonth',
'month' => 'addMonth',
'monthly' => 'addMonth',
'3M' => 'addMonths',
'quarter' => 'addMonths',
'quarterly' => 'addMonths',
'6M' => 'addMonths',
'half-year' => 'addMonths',
'year' => 'addYear',
'yearly' => 'addYear',
]; ];
$modifierMap = [ $modifierMap = [
'quarter' => 3, 'quarter' => 3,