Cleaned up the budget controller.

This commit is contained in:
James Cole
2014-12-12 07:13:40 +01:00
parent d054f9b92f
commit cb2863eaf3
5 changed files with 153 additions and 179 deletions

View File

@@ -236,7 +236,7 @@ class AccountController extends BaseController
} }
// go back to update screen. // go back to update screen.
if ($data['post_submit_action'] == 'return_to_edit') { if ($data['post_submit_action'] == 'return_to_edit') {
return Redirect::route('accounts.edit', $account->id); return Redirect::route('accounts.edit', $account->id)->withInput(['post_submit_action' => 'return_to_edit']);
} }
return Redirect::route('accounts.index', $data['what']); return Redirect::route('accounts.index', $data['what']);

View File

@@ -1,24 +1,31 @@
<?php <?php
use FireflyIII\Database\Budget as BudgetRepository; use FireflyIII\Database\Budget as BudgetRepository;
use FireflyIII\Exception\FireflyException; use FireflyIII\Shared\Preferences\PreferencesInterface as Pref;
use Illuminate\Support\MessageBag;
/** /**
* Class BudgetController * Class BudgetController
*
* @SuppressWarnings("CamelCase")
* @SuppressWarnings("TooManyMethods")
* @SuppressWarnings("CouplingBetweenObjects")
*/ */
class BudgetController extends BaseController class BudgetController extends BaseController
{ {
/** @var Pref */
protected $_preferences;
/** @var BudgetRepository */ /** @var BudgetRepository */
protected $_repository; protected $_repository;
/** /**
* @param BudgetRepository $repository * @param BudgetRepository $repository
* @param Pref $preferences
*/ */
public function __construct(BudgetRepository $repository) public function __construct(BudgetRepository $repository, Pref $preferences)
{ {
$this->_repository = $repository; $this->_repository = $repository;
$this->_preferences = $preferences;
View::share('title', 'Budgets'); View::share('title', 'Budgets');
View::share('mainTitleIcon', 'fa-tasks'); View::share('mainTitleIcon', 'fa-tasks');
} }
@@ -31,17 +38,11 @@ class BudgetController extends BaseController
*/ */
public function amount(Budget $budget) public function amount(Budget $budget)
{ {
$amount = intval(Input::get('amount')); $amount = intval(Input::get('amount'));
$date = Session::get('start'); $date = Session::get('start');
$limit = $this->_repository->updateLimitAmount($budget, $date, $amount); $limitRepetition = $this->_repository->updateLimitAmount($budget, $date, $amount);
// try to find the limit repetition for this limit: return Response::json(['name' => $budget->name, 'repetition' => $limitRepetition->id]);
$repetition = $limit->limitrepetitions()->first();
if ($repetition) {
return Response::json(['name' => $budget->name, 'repetition' => $repetition->id]);
} else {
return Response::json(['name' => $budget->name, 'repetition' => null]);
}
} }
@@ -72,8 +73,9 @@ class BudgetController extends BaseController
*/ */
public function destroy(Budget $budget) public function destroy(Budget $budget)
{ {
Session::flash('success', 'Budget "' . e($budget->name) . '" was deleted.');
$this->_repository->destroy($budget); $this->_repository->destroy($budget);
Session::flash('success', 'The budget was deleted.');
return Redirect::route('budgets.index'); return Redirect::route('budgets.index');
@@ -86,67 +88,39 @@ class BudgetController extends BaseController
*/ */
public function edit(Budget $budget) public function edit(Budget $budget)
{ {
$subTitle = 'Edit budget "' . $budget->name . '"'; $subTitle = 'Edit budget "' . e($budget->name) . '"';
return View::make('budgets.edit', compact('budget', 'subTitle')); return View::make('budgets.edit', compact('budget', 'subTitle'));
} }
/** /**
* The index of the budget controller contains all budgets and the current relevant limit repetition.
*
* @return $this * @return $this
*/ */
public function index() public function index()
{ {
$budgets = $this->_repository->get();
/** @var \FireflyIII\Shared\Preferences\PreferencesInterface $preferences */ // loop the budgets:
$preferences = App::make('FireflyIII\Shared\Preferences\PreferencesInterface'); $budgets->each(
function (Budget $budget) {
/** @var \FireflyIII\Database\Budget $repos */ /** @noinspection PhpUndefinedFieldInspection */
$repos = App::make('FireflyIII\Database\Budget'); $budget->spent = $this->_repository->spentInMonth($budget, \Session::get('start'));
$budgets = $repos->get(); /** @noinspection PhpUndefinedFieldInspection */
$budget->currentRep = $budget->limitrepetitions()->where('limit_repetitions.startdate', \Session::get('start')->format('Y-m-d'))->first(
// get the limits for the current month. ['limit_repetitions.*']
$date = \Session::get('start'); );
$spent = 0;
/** @var \Budget $budget */
foreach ($budgets as $budget) {
$budget->spent = $repos->spentInMonth($budget, $date);
$spent += $budget->spent;
$budget->pct = 0;
$budget->limit = 0;
/** @var \Limit $limit */
foreach ($budget->limits as $limit) {
/** @var \LimitRepetition $repetition */
foreach ($limit->limitrepetitions as $repetition) {
if ($repetition->startdate == $date) {
$budget->currentRep = $repetition;
$budget->limit = floatval($repetition->amount);
if ($budget->limit > $budget->spent) {
// not overspent:
$budget->pct = 30;
} else {
$budget->pct = 50;
}
}
}
} }
} );
$budgetAmount = $preferences->get('budgetIncomeTotal' . $date->format('FY'), 1000); $spent = $budgets->sum('spent');
$amount = floatval($budgetAmount->data); $amount = $this->_preferences->get('budgetIncomeTotal' . \Session::get('start')->format('FY'), 1000)->data;
$overspent = $spent > $amount; $overspent = $spent > $amount;
if ($overspent) { $spentPCT = $overspent ? ceil($amount / $spent * 100) : ceil($spent / $amount * 100);
// overspent on total amount
$spentPCT = ceil($amount / $spent * 100);
} else {
// not overspent on total amount.
$spentPCT = ceil($spent / $amount * 100);
}
return View::make('budgets.index', compact('budgets', 'spent', 'spentPCT', 'overspent'))->with('budgetAmount', $budgetAmount); return View::make('budgets.index', compact('budgets', 'spent', 'spentPCT', 'overspent', 'amount'));
} }
/** /**
@@ -154,12 +128,7 @@ class BudgetController extends BaseController
*/ */
public function postUpdateIncome() public function postUpdateIncome()
{ {
/** @var \FireflyIII\Shared\Preferences\PreferencesInterface $preferences */ $this->_preferences->set('budgetIncomeTotal' . Session::get('start')->format('FY'), intval(Input::get('amount')));
$preferences = App::make('FireflyIII\Shared\Preferences\PreferencesInterface');
$date = Session::get('start');
$value = intval(Input::get('amount'));
$preferences->set('budgetIncomeTotal' . $date->format('FY'), $value);
return Redirect::route('budgets.index'); return Redirect::route('budgets.index');
} }
@@ -175,121 +144,93 @@ class BudgetController extends BaseController
if (!is_null($repetition) && $repetition->limit->budget->id != $budget->id) { if (!is_null($repetition) && $repetition->limit->budget->id != $budget->id) {
App::abort(500); App::abort(500);
} }
/** @var \FireflyIII\Database\Budget $repos */
$repos = App::make('FireflyIII\Database\Budget');
if (is_null($repetition)) { $journals = $this->_repository->getJournals($budget, $repetition);
// get all other repetitions: $limits = $repetition ? $budget->limits()->orderBy('startdate', 'DESC')->get() : [$repetition->limit];
$limits = $budget->limits()->orderBy('startdate', 'DESC')->get(); $subTitle = $repetition ? e($budget->name) . ' in ' . $repetition->startdate->format('F Y') : e($budget->name);
// get all transaction journals for this budget.
$journals = $repos->getTransactionJournals($budget, 50);
$subTitle = $budget->name; return View::make('budgets.show', compact('limits', 'budget', 'repetition', 'journals', 'subTitle'));
} else {
// get nothing? i dunno
$limits = [$repetition->limit];
// get all transaction journals for this budget and limit repetition.
$subTitle = $budget->name . ' in ' . $repetition->startdate->format('F Y');
$journals = $repos->getTransactionJournalsInRepetition($budget, $repetition, 50);
}
$hideBudget = true;
return View::make('budgets.show', compact('limits', 'budget', 'repetition', 'journals', 'subTitle', 'hideBudget'));
} }
/** /**
* @return $this * @return $this|\Illuminate\Http\RedirectResponse
* @throws FireflyException
*/ */
public function store() public function store()
{ {
/** @var \FireflyIII\Database\Budget $repos */ $data = Input::except('_token');
$repos = App::make('FireflyIII\Database\Budget');
$data = Input::except('_token');
switch ($data['post_submit_action']) { // always validate:
default: $messages = $this->_repository->validate($data);
throw new FireflyException('Cannot handle post_submit_action "' . e($data['post_submit_action']) . '"');
break;
case 'create_another':
case 'store':
$messages = $repos->validate($data);
/** @var MessageBag $messages ['errors'] */
if ($messages['errors']->count() > 0) {
Session::flash('warnings', $messages['warnings']);
Session::flash('successes', $messages['successes']);
Session::flash('error', 'Could not save budget: ' . $messages['errors']->first());
return Redirect::route('budgets.create')->withInput()->withErrors($messages['errors']); // flash messages:
} Session::flash('warnings', $messages['warnings']);
// store! Session::flash('successes', $messages['successes']);
$repos->store($data); Session::flash('errors', $messages['errors']);
Session::flash('success', 'New budget stored!'); if ($messages['errors']->count() > 0) {
Session::flash('error', 'Could not store budget: ' . $messages['errors']->first());
if ($data['post_submit_action'] == 'create_another') {
return Redirect::route('budgets.create');
} else {
return Redirect::route('budgets.index');
}
break;
case 'validate_only':
$messageBags = $repos->validate($data);
Session::flash('warnings', $messageBags['warnings']);
Session::flash('successes', $messageBags['successes']);
Session::flash('errors', $messageBags['errors']);
return Redirect::route('budgets.create')->withInput();
break;
} }
// return to create screen:
if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) {
return Redirect::route('budgets.create')->withInput();
}
// store:
$this->_repository->store($data);
Session::flash('success', 'Budget "' . e($data['name']) . '" stored.');
if ($data['post_submit_action'] == 'store') {
return Redirect::route('budgets.index');
}
// create another.
if ($data['post_submit_action'] == 'create_another') {
return Redirect::route('budgets.create')->withInput();
}
return Redirect::route('budgets.index');
} }
/** /**
* @param Budget $budget * @param Budget $budget
* *
* @return $this * @return $this|\Illuminate\Http\RedirectResponse
* @throws FireflyException
*/ */
public function update(Budget $budget) public function update(Budget $budget)
{ {
/** @var \FireflyIII\Database\Budget $repos */ $data = Input::except('_token');
$repos = App::make('FireflyIII\Database\Budget');
$data = Input::except('_token');
switch (Input::get('post_submit_action')) { // always validate:
default: $messages = $this->_repository->validate($data);
throw new FireflyException('Cannot handle post_submit_action "' . e(Input::get('post_submit_action')) . '"');
break;
case 'return_to_edit':
case 'update':
$messages = $repos->validate($data);
/** @var MessageBag $messages ['errors'] */
if ($messages['errors']->count() > 0) {
Session::flash('warnings', $messages['warnings']);
Session::flash('successes', $messages['successes']);
Session::flash('error', 'Could not save budget: ' . $messages['errors']->first());
return Redirect::route('budgets.edit', $budget->id)->withInput()->withErrors($messages['errors']); // flash messages:
} Session::flash('warnings', $messages['warnings']);
// store! Session::flash('successes', $messages['successes']);
$repos->update($budget, $data); Session::flash('errors', $messages['errors']);
Session::flash('success', 'Budget updated!'); if ($messages['errors']->count() > 0) {
Session::flash('error', 'Could not update budget: ' . $messages['errors']->first());
if ($data['post_submit_action'] == 'return_to_edit') {
return Redirect::route('budgets.edit', $budget->id);
} else {
return Redirect::route('budgets.index');
}
case 'validate_only':
$messageBags = $repos->validate($data);
Session::flash('warnings', $messageBags['warnings']);
Session::flash('successes', $messageBags['successes']);
Session::flash('errors', $messageBags['errors']);
return Redirect::route('budgets.edit', $budget->id)->withInput();
break;
} }
// return to update screen:
if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) {
return Redirect::route('budgets.edit', $budget->id)->withInput();
}
// update
$this->_repository->update($budget, $data);
Session::flash('success', 'Budget "' . e($data['name']) . '" updated.');
// go back to list
if ($data['post_submit_action'] == 'update') {
return Redirect::route('budgets.index');
}
// go back to update screen.
if ($data['post_submit_action'] == 'return_to_edit') {
return Redirect::route('budgets.edit', $budget->id)->withInput(['post_submit_action' => 'return_to_edit']);
}
return Redirect::route('budgets.index');
} }
/** /**
@@ -297,11 +238,7 @@ class BudgetController extends BaseController
*/ */
public function updateIncome() public function updateIncome()
{ {
$date = Session::get('start'); $budgetAmount = $this->_preferences->get('budgetIncomeTotal' . Session::get('start')->format('FY'), 1000);
/** @var \FireflyIII\Shared\Preferences\PreferencesInterface $preferences */ return View::make('budgets.income')->with('amount', $budgetAmount);
$preferences = App::make('FireflyIII\Shared\Preferences\PreferencesInterface');
$budgetAmount = $preferences->get('budgetIncomeTotal' . $date->format('FY'), 1000);
return View::make('budgets.income')->with('amount', $budgetAmount)->with('date', $date);
} }
} }

View File

@@ -166,6 +166,40 @@ class Budget implements CUD, CommonDatabaseCalls, BudgetInterface
throw new NotImplementedException; throw new NotImplementedException;
} }
/**
* Returns all the transaction journals for a limit, possibly limited by a limit repetition.
*
* @param \Budget $budget
* @param \LimitRepetition $repetition
* @param int $take
*
* @return \Illuminate\Pagination\Paginator
*/
public function getJournals(\Budget $budget, \LimitRepetition $repetition = null, $take = 50)
{
$offset = intval(\Input::get('page')) > 0 ? intval(\Input::get('page')) * $take : 0;
$setQuery = $budget->transactionJournals()->withRelevantData()->take($take)->offset($offset)->orderBy('date', 'DESC');
$countQuery = $budget->transactionJournals();
if (!is_null($repetition)) {
$setQuery->before($repetition->startdate)->after($repetition->enddate);
$countQuery->before($repetition->startdate)->after($repetition->enddate);
}
$set = $setQuery->get(['transaction_journals.*']);
$count = $countQuery->count();
$items = [];
foreach ($set as $entry) {
$items[] = $entry;
}
return \Paginator::make($items, $count, $take);
}
public function getTransactionJournals(\Budget $budget, $limit = 50) public function getTransactionJournals(\Budget $budget, $limit = 50)
{ {
$offset = intval(\Input::get('page')) > 0 ? intval(\Input::get('page')) * $limit : 0; $offset = intval(\Input::get('page')) > 0 ? intval(\Input::get('page')) * $limit : 0;
@@ -265,11 +299,14 @@ class Budget implements CUD, CommonDatabaseCalls, BudgetInterface
} }
/** /**
* This method updates the amount (envelope) for the given date and budget. This results in a (new) limit (aka an envelope)
* for that budget. Returned to the user is the new limit repetition.
*
* @param \Budget $budget * @param \Budget $budget
* @param Carbon $date * @param Carbon $date
* @param $amount * @param $amount
* *
* @return \Limit * @return \LimitRepetition
* @throws \Exception * @throws \Exception
*/ */
public function updateLimitAmount(\Budget $budget, Carbon $date, $amount) public function updateLimitAmount(\Budget $budget, Carbon $date, $amount)
@@ -280,10 +317,10 @@ class Budget implements CUD, CommonDatabaseCalls, BudgetInterface
// create one! // create one!
$limit = new \Limit; $limit = new \Limit;
$limit->budget()->associate($budget); $limit->budget()->associate($budget);
$limit->startdate = $date; $limit->startdate = $date;
$limit->amount = $amount; $limit->amount = $amount;
$limit->repeat_freq = 'monthly'; $limit->repeat_freq = 'monthly';
$limit->repeats = 0; $limit->repeats = 0;
$limit->save(); $limit->save();
/* /*
* A newly stored limit also created a limit repetition. * A newly stored limit also created a limit repetition.
@@ -302,7 +339,7 @@ class Budget implements CUD, CommonDatabaseCalls, BudgetInterface
} }
} }
return $limit; return $limit->limitrepetitions()->first();
} }

View File

@@ -4,7 +4,7 @@
<div class="modal-content"> <div class="modal-content">
<div class="modal-header"> <div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Update (expected) income for {{$date->format('F Y')}}</h4> <h4 class="modal-title" id="myModalLabel">Update (expected) income for {{Session::get('start')->format('F Y')}}</h4>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<div class="input-group"> <div class="input-group">

View File

@@ -14,7 +14,7 @@
</div> </div>
<div class="col-lg-6 col-md-4 col-sm-3" style="text-align:right;"> <div class="col-lg-6 col-md-4 col-sm-3" style="text-align:right;">
<small>Income {{\Session::get('start')->format('F Y')}}: <small>Income {{\Session::get('start')->format('F Y')}}:
<a href="#" class="updateIncome"><span id="totalAmount" data-value="{{$budgetAmount->data}}">{{mf($budgetAmount->data)}}</span></a></small> <a href="#" class="updateIncome"><span id="totalAmount" data-value="{{$amount}}">{{mf($amount)}}</span></a></small>
</div> </div>
</div> </div>
@@ -59,7 +59,7 @@
<div class="col-lg-3 col-sm-4 col-md-6" style="height:180px;"> <div class="col-lg-3 col-sm-4 col-md-6" style="height:180px;">
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-heading"> <div class="panel-heading">
@if($budget->currentRep) @if(isset($budget->currentRep))
<a href="{{route('budgets.show',[$budget->id,$budget->currentRep->id])}}" id="budget-link-{{$budget->id}}">{{{$budget->name}}}</a> <a href="{{route('budgets.show',[$budget->id,$budget->currentRep->id])}}" id="budget-link-{{$budget->id}}">{{{$budget->name}}}</a>
@else @else
<a href="{{route('budgets.show',$budget->id)}}" id="budget-link-{{$budget->id}}">{{{$budget->name}}}</a> <a href="{{route('budgets.show',$budget->id)}}" id="budget-link-{{$budget->id}}">{{{$budget->name}}}</a>
@@ -99,10 +99,10 @@
<span id="budget-description-{{$budget->id}}">Budgeted: </span> <span id="budget-description-{{$budget->id}}">Budgeted: </span>
<!-- budget-info-X holds the input and the euro-sign: --> <!-- budget-info-X holds the input and the euro-sign: -->
<span id="budget-info-{{$budget->id}}"> <span id="budget-info-{{$budget->id}}">
@if($budget->limit > $budget->spent) @if($budget->currentRep->amount > $budget->spent)
<span class="text-success">&euro;</span> <input type="number" min="0" max="900" data-id="{{$budget->id}}" step="1" value="{{$budget->limit}}" style="width:50px;color:#3c763d;" /> <span class="text-success">&euro;</span> <input type="number" min="0" max="900" data-id="{{$budget->id}}" step="1" value="{{$budget->currentRep->amount}}" style="width:90px;color:#3c763d;" />
@else @else
<span class="text-danger">&euro;</span> <input type="number" min="0" max="900" data-id="{{$budget->id}}" step="1" value="{{$budget->limit}}" style="width:50px;color:#a94442;" /> <span class="text-danger">&euro;</span> <input type="number" min="0" max="900" data-id="{{$budget->id}}" step="1" value="{{$budget->currentRep->amount}}" style="width:90px;color:#a94442;" />
@endif @endif
</span> </span>
@else @else