diff --git a/.coveralls.yml b/.coveralls.yml
index 482521d6ec..68c3d23770 100644
--- a/.coveralls.yml
+++ b/.coveralls.yml
@@ -1,2 +1,3 @@
src_dir: .
-coverage_clover: tests/_output/coverage.xml
\ No newline at end of file
+coverage_clover: tests/_output/coverage.xml
+json_path: tests/_output/coveralls-upload.json
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index d0be83396b..71d8f61ce0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,6 @@
/bootstrap/compiled.php
/vendor
composer.phar
-composer.lock
.env.*.php
.env.php
.DS_Store
@@ -14,8 +13,13 @@ index.html*
app/storage/firefly-export*
.vagrant
firefly-iii-import-*.json
-
tests/_output/*
testing.sqlite
-c3.php
_ide_helper_models.php
+clean.sqlite
+tests/acceptance/AcceptanceTester.php
+tests/functional/FunctionalTester.php
+tests/unit/UnitTester.php
+pi.php
+tests/_data/db.sqlite
+tests/_data/dump.sql
diff --git a/.travis.yml b/.travis.yml
index 835ec484b9..7638995c02 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -3,13 +3,14 @@ language: php
php:
- 5.5
- 5.6
- - hhvm
install:
- composer install
script:
- - php vendor/bin/codecept run
+ - ./tests/_data/db.sh
+ - php vendor/bin/codecept build
+ - php vendor/bin/codecept run --coverage --coverage-xml
after_script:
- php vendor/bin/coveralls
\ No newline at end of file
diff --git a/README.md b/README.md
index 6d44b33cf8..25c2f0d92b 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,9 @@
Firefly III
===========
-[![Build Status](https://travis-ci.org/JC5/firefly-iii.svg?branch=master)](https://travis-ci.org/JC5/firefly-iii)
-![Still maintained?](http://stillmaintained.com/JC5/firefly-iii.png)
+[![Build Status](https://travis-ci.org/JC5/firefly-iii.svg?branch=develop)](https://travis-ci.org/JC5/firefly-iii)
+[![Project Status](http://stillmaintained.com/JC5/firefly-iii.png?a=b)](http://stillmaintained.com/JC5/firefly-iii)
+[![Coverage Status](https://coveralls.io/repos/JC5/firefly-iii/badge.png?branch=master)](https://coveralls.io/r/JC5/firefly-iii?branch=master)
[![Latest Stable Version](https://poser.pugx.org/grumpydictator/firefly-iii/v/stable.svg)](https://packagist.org/packages/grumpydictator/firefly-iii)
[![Total Downloads](https://poser.pugx.org/grumpydictator/firefly-iii/downloads.svg)](https://packagist.org/packages/grumpydictator/firefly-iii)
@@ -17,13 +18,15 @@ laptop and [Firefly II](https://github.com/JC5/Firefly) is live.
## Current features
-- [A double-entry bookkeeping system](http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system).
+- [A double-entry bookkeeping system](http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system);
- You can store, edit and remove withdrawals, deposits and transfers. This allows you full financial management;
- It's possible to create, change and manage money using _budgets_;
- Organize transactions using categories;
- Save towards a goal using piggy banks;
- Predict and anticipate large expenses using "repeated expenses" (ie. yearly taxes);
-- Predict and anticipate bills using "recurring transactions" (rent for example).
+- Predict and anticipate bills using "recurring transactions" (rent for example);
+- View basic income / expense reports.
+- Lots of help text in case you don't get it;
Everything is organised:
@@ -37,15 +40,13 @@ Everything is organised:
Firefly III will feature, but does not feature yet:
- Financial reporting showing you how well you are doing;
-- Lots of help text in case you don't get it;
- More control over other resources outside of personal finance
- Accounts shared with a partner (household accounts)
- Debts
- Credit cards
-- More test-coverage (aka: actual test coverage);
+- More test-coverage;
- Firefly will be able to split transactions; a single purchase can be split in multiple entries, for more fine-grained control.
- Firefly will be able to join transactions.
-- Transfers and transactions are combined into one internal datatype which is more consistent with what you're actually doing: moving money from A to B. The fact that A or B or both are yours should not matter.
- Any other features I might not have thought of.
Some stuff has been removed:
@@ -64,13 +65,9 @@ Some stuff has been removed:
![Reports](http://i.imgur.com/EnEIyQI.png)
## Current state
-I have the basics up and running. Test coverage is currently non-existent.
+I have the basics up and running. Test coverage is currently coming, slowly.
Although I have not checked extensively, some forms and views have CSRF vulnerabilities. This is because not all
views escape all characters by default. Will be fixed.
-The current layout / look & feel is a pretty basic Bootstrap3 template. I am currently working on a more consistent,
-expanded layout which will feature shiny AJAX things and data tables and all the Web 3.0 goodies you've come to expect
-from social media sites.
-
Questions, ideas or other things to contribute? [Let me know](https://github.com/JC5/firefly-iii/issues/new)!
\ No newline at end of file
diff --git a/app/breadcrumbs.php b/app/breadcrumbs.php
index 9772319edf..3269c6e773 100644
--- a/app/breadcrumbs.php
+++ b/app/breadcrumbs.php
@@ -90,7 +90,7 @@ Breadcrumbs::register(
$breadcrumbs->push($budget->name, route('budgets.show', $budget->id));
if (!is_null($repetition)) {
$breadcrumbs->push(
- DateKit::periodShow($repetition->startdate, $repetition->limit->repeat_freq), route('budgets.show', $budget->id, $repetition->id)
+ DateKit::periodShow($repetition->startdate, $repetition->budgetlimit->repeat_freq), route('budgets.show', $budget->id, $repetition->id)
);
}
}
diff --git a/app/commands/Cleanup.php b/app/commands/Cleanup.php
index 2e5c889068..76b734fe53 100644
--- a/app/commands/Cleanup.php
+++ b/app/commands/Cleanup.php
@@ -1,9 +1,12 @@
info('Cleared compiled...');
Artisan::call('ide-helper:generate');
$this->info('IDE helper, done...');
- Artisan::call('ide-helper:models', ['write']);
+ Artisan::call('ide-helper:models', ['nowrite']);
$this->info('IDE models, done...');
Artisan::call('optimize');
$this->info('Optimized...');
diff --git a/app/config/homestead/database.php b/app/config/homestead/database.php
index de7f714bdf..29737579f8 100644
--- a/app/config/homestead/database.php
+++ b/app/config/homestead/database.php
@@ -2,22 +2,7 @@
return [
- /*
- |--------------------------------------------------------------------------
- | Database Connections
- |--------------------------------------------------------------------------
- |
- | Here are each of the database connections setup for your application.
- | Of course, examples of configuring each database platform that is
- | supported by Laravel is shown below to make development simple.
- |
- |
- | All database work in Laravel is done through the PHP PDO facilities
- | so make sure you have the driver for your particular database of
- | choice installed on your machine before you begin development.
- |
- */
-
+ 'default' => 'mysql',
'connections' => [
'mysql' => [
@@ -30,6 +15,11 @@ return [
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
+ 'sqlite' => [
+ 'driver' => 'sqlite',
+ 'database' => realpath(__DIR__.'/../../../tests/_data/testing.sqlite'),
+ 'prefix' => ''
+ ],
'pgsql' => [
'driver' => 'pgsql',
diff --git a/app/config/packages/rcrowe/twigbridge/extensions.php b/app/config/packages/rcrowe/twigbridge/extensions.php
deleted file mode 100644
index 8f99eb097e..0000000000
--- a/app/config/packages/rcrowe/twigbridge/extensions.php
+++ /dev/null
@@ -1,134 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-/**
- * Configuration options for the built-in extensions.
- */
-return [
-
- /*
- |--------------------------------------------------------------------------
- | Extensions
- |--------------------------------------------------------------------------
- |
- | Enabled extensions.
- |
- | `Twig_Extension_Debug` is enabled automatically if twig.debug is TRUE.
- |
- */
- 'enabled' => [
- 'TwigBridge\Extension\Loader\Facades',
- 'TwigBridge\Extension\Loader\Filters',
- 'TwigBridge\Extension\Loader\Functions',
-
- 'TwigBridge\Extension\Laravel\Auth',
- 'TwigBridge\Extension\Laravel\Config',
- 'TwigBridge\Extension\Laravel\Form',
- 'TwigBridge\Extension\Laravel\Html',
- 'TwigBridge\Extension\Laravel\Input',
- 'TwigBridge\Extension\Laravel\Session',
- 'TwigBridge\Extension\Laravel\String',
- 'TwigBridge\Extension\Laravel\Translator',
- 'TwigBridge\Extension\Laravel\Url',
-
- // 'TwigBridge\Extension\Laravel\Legacy\Facades',
- ],
-
- /*
- |--------------------------------------------------------------------------
- | Facades
- |--------------------------------------------------------------------------
- |
- | Available facades. Access like `{{ Config.get('foo.bar') }}`.
- |
- | Each facade can take an optional array of options. To mark the whole facade
- | as safe you can set the option `'is_safe' => true`. Setting the facade as
- | safe means that any HTML returned will not be escaped.
- |
- | It is advisable to not set the whole facade as safe and instead mark the
- | each appropriate method as safe for security reasons. You can do that with
- | the following syntax:
- |
- |
- | 'Form' => [
- | 'is_safe' => [
- | 'open'
- | ]
- | ]
- |
- |
- | The values of the `is_safe` array must match the called method on the facade
- | in order to be marked as safe.
- |
- */
- 'facades' => [],
-
- /*
- |--------------------------------------------------------------------------
- | Functions
- |--------------------------------------------------------------------------
- |
- | Available functions. Access like `{{ secure_url(...) }}`.
- |
- | Each function can take an optional array of options. These options are
- | passed directly to `Twig_SimpleFunction`.
- |
- | So for example, to mark a function as safe you can do the following:
- |
- |
- | 'link_to' => [
- | 'is_safe' => ['html']
- | ]
- |
- |
- | The options array also takes a `callback` that allows you to name the
- | function differently in your Twig templates than what it's actually called.
- |
- |
- | 'link' => [
- | 'callback' => 'link_to'
- | ]
- |
- |
- */
- 'functions' => [],
-
- /*
- |--------------------------------------------------------------------------
- | Filters
- |--------------------------------------------------------------------------
- |
- | Available filters. Access like `{{ variable|filter }}`.
- |
- | Each filter can take an optional array of options. These options are
- | passed directly to `Twig_SimpleFilter`.
- |
- | So for example, to mark a filter as safe you can do the following:
- |
- |
- | 'studly_case' => [
- | 'is_safe' => ['html']
- | ]
- |
- |
- | The options array also takes a `callback` that allows you to name the
- | filter differently in your Twig templates than what is actually called.
- |
- |
- | 'snake' => [
- | 'callback' => 'snake_case'
- | ]
- |
- |
- */
- 'filters' => [],
-
-];
diff --git a/app/config/packages/rcrowe/twigbridge/twig.php b/app/config/packages/rcrowe/twigbridge/twig.php
deleted file mode 100644
index 343e9e1e14..0000000000
--- a/app/config/packages/rcrowe/twigbridge/twig.php
+++ /dev/null
@@ -1,88 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-use Illuminate\Support\Facades\Config;
-
-/**
- * Configuration options for Twig.
- */
-return [
-
- /*
- |--------------------------------------------------------------------------
- | Extension
- |--------------------------------------------------------------------------
- |
- | File extension for Twig view files.
- |
- */
- 'extension' => 'twig',
-
- /*
- |--------------------------------------------------------------------------
- | Accepts all Twig environment configuration options
- |--------------------------------------------------------------------------
- |
- | http://twig.sensiolabs.org/doc/api.html#environment-options
- |
- */
- 'environment' => [
-
- // When set to true, the generated templates have a __toString() method
- // that you can use to display the generated nodes.
- // default: false
- 'debug' => Config::get('app.debug', false),
-
- // The charset used by the templates.
- // default: utf-8
- 'charset' => 'utf-8',
-
- // The base template class to use for generated templates.
- // default: TwigBridge\Twig\Template
- 'base_template_class' => 'TwigBridge\Twig\Template',
-
- // An absolute path where to store the compiled templates, or false to disable caching. If null
- // then the cache file path is used.
- // default: cache file storage path
- 'cache' => null,
-
- // When developing with Twig, it's useful to recompile the template
- // whenever the source code changes. If you don't provide a value
- // for the auto_reload option, it will be determined automatically based on the debug value.
- 'auto_reload' => true,
-
- // If set to false, Twig will silently ignore invalid variables
- // (variables and or attributes/methods that do not exist) and
- // replace them with a null value. When set to true, Twig throws an exception instead.
- // default: false
- 'strict_variables' => false,
-
- // If set to true, auto-escaping will be enabled by default for all templates.
- // default: true
- 'autoescape' => true,
-
- // A flag that indicates which optimizations to apply
- // (default to -1 -- all optimizations are enabled; set it to 0 to disable)
- 'optimizations' => -1,
- ],
-
- /*
- |--------------------------------------------------------------------------
- | Global variables
- |--------------------------------------------------------------------------
- |
- | These will always be passed in and can be accessed as Twig variables.
- | NOTE: these will be overwritten if you pass data into the view with the same key.
- |
- */
- 'globals' => [],
-
-];
diff --git a/app/config/testing/cache.php b/app/config/testing/cache.php
index 729ae3a825..fef1e78b52 100644
--- a/app/config/testing/cache.php
+++ b/app/config/testing/cache.php
@@ -1,20 +1,3 @@
'array',
-
-];
+return ['driver' => 'array',];
diff --git a/app/config/testing/database.php b/app/config/testing/database.php
index dce7200371..3517df8d20 100644
--- a/app/config/testing/database.php
+++ b/app/config/testing/database.php
@@ -4,7 +4,7 @@ return [
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
- 'database' => 'tests/_data/testing.sqlite',
+ 'database' => realpath(__DIR__.'/../../../tests/_data/db.sqlite'),
'prefix' => ''
]
diff --git a/app/config/testing/session.php b/app/config/testing/session.php
index 46bf726a27..fef1e78b52 100644
--- a/app/config/testing/session.php
+++ b/app/config/testing/session.php
@@ -1,21 +1,3 @@
'array',
-
-];
+return ['driver' => 'array',];
diff --git a/app/controllers/AccountController.php b/app/controllers/AccountController.php
index b4fe3cd03d..190df02a5d 100644
--- a/app/controllers/AccountController.php
+++ b/app/controllers/AccountController.php
@@ -1,6 +1,6 @@
withInput();
- }
- return Redirect::route('accounts.index', $data['what']);
+ return Redirect::route('accounts.create', $data['what'])->withInput();
}
/**
@@ -210,6 +206,7 @@ class AccountController extends BaseController
$data = Input::except('_token');
$data['what'] = $this->_shortNamesByFullName[$account->accountType->type];
+
// always validate:
$messages = $this->_repository->validate($data);
@@ -234,11 +231,8 @@ class AccountController extends BaseController
if ($data['post_submit_action'] == 'update') {
return Redirect::route('accounts.index', $data['what']);
}
- // go back to update screen.
- if ($data['post_submit_action'] == 'return_to_edit') {
- return Redirect::route('accounts.edit', $account->id);
- }
- return Redirect::route('accounts.index', $data['what']);
+ // go back to update screen.
+ return Redirect::route('accounts.edit', $account->id)->withInput(['post_submit_action' => 'return_to_edit']);
}
}
\ No newline at end of file
diff --git a/app/controllers/BudgetController.php b/app/controllers/BudgetController.php
index 3d2f95d75a..a3fa3bd014 100644
--- a/app/controllers/BudgetController.php
+++ b/app/controllers/BudgetController.php
@@ -1,24 +1,34 @@
_repository = $repository;
+ $this->_repository = $repository;
+ $this->_preferences = $preferences;
View::share('title', 'Budgets');
View::share('mainTitleIcon', 'fa-tasks');
}
@@ -31,17 +41,11 @@ class BudgetController extends BaseController
*/
public function amount(Budget $budget)
{
- $amount = intval(Input::get('amount'));
- $date = Session::get('start');
- $limit = $this->_repository->updateLimitAmount($budget, $date, $amount);
+ $amount = intval(Input::get('amount'));
+ $date = Session::get('start', Carbon::now()->startOfMonth());
+ $limitRepetition = $this->_repository->updateLimitAmount($budget, $date, $amount);
- // try to find the limit repetition for this limit:
- $repetition = $limit->limitrepetitions()->first();
- if ($repetition) {
- return Response::json(['name' => $budget->name, 'repetition' => $repetition->id]);
- } else {
- return Response::json(['name' => $budget->name, 'repetition' => null]);
- }
+ return Response::json(['name' => $budget->name, 'repetition' => $limitRepetition->id]);
}
@@ -72,8 +76,9 @@ class BudgetController extends BaseController
*/
public function destroy(Budget $budget)
{
+ Session::flash('success', 'Budget "' . e($budget->name) . '" was deleted.');
$this->_repository->destroy($budget);
- Session::flash('success', 'The budget was deleted.');
+
return Redirect::route('budgets.index');
@@ -86,67 +91,38 @@ class BudgetController extends BaseController
*/
public function edit(Budget $budget)
{
- $subTitle = 'Edit budget "' . $budget->name . '"';
+ $subTitle = 'Edit budget "' . e($budget->name) . '"';
return View::make('budgets.edit', compact('budget', 'subTitle'));
}
/**
+ * The index of the budget controller contains all budgets and the current relevant limit repetition.
+ * TODO move currentRep to the repository.
+ *
* @return $this
*/
public function index()
{
+ $budgets = $this->_repository->get();
- /** @var \FireflyIII\Shared\Preferences\PreferencesInterface $preferences */
- $preferences = App::make('FireflyIII\Shared\Preferences\PreferencesInterface');
-
- /** @var \FireflyIII\Database\Budget $repos */
- $repos = App::make('FireflyIII\Database\Budget');
- $budgets = $repos->get();
-
- // get the limits for the current month.
- $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;
- }
-
- }
- }
+ // loop the budgets:
+ $budgets->each(
+ function (Budget $budget) {
+ $budget->spent = $this->_repository->spentInMonth($budget, \Session::get('start', Carbon::now()->startOfMonth()));
+ $budget->currentRep = $this->_repository->getRepetitionByDate($budget, \Session::get('start', Carbon::now()->startOfMonth()));
}
- }
+ );
- $budgetAmount = $preferences->get('budgetIncomeTotal' . $date->format('FY'), 1000);
- $amount = floatval($budgetAmount->data);
- $overspent = $spent > $amount;
- if ($overspent) {
- // overspent on total amount
- $spentPCT = ceil($amount / $spent * 100);
- } else {
- // not overspent on total amount.
- $spentPCT = ceil($spent / $amount * 100);
- }
+ $spent = $budgets->sum('spent');
+ $amount = $this->_preferences->get('budgetIncomeTotal' . \Session::get('start', Carbon::now()->startOfMonth())->format('FY'), 1000)->data;
+ $overspent = $spent > $amount;
+ $spentPCT = $overspent ? ceil($amount / $spent * 100) : ceil($spent / $amount * 100);
+ $budgetMax = $this->_preferences->get('budgetMaximum', 1000);
+ $budgetMaximum = $budgetMax->data;
- return View::make('budgets.index', compact('budgets', 'spent', 'spentPCT', 'overspent'))->with('budgetAmount', $budgetAmount);
+ return View::make('budgets.index', compact('budgetMaximum', 'budgets', 'spent', 'spentPCT', 'overspent', 'amount'));
}
/**
@@ -154,12 +130,7 @@ class BudgetController extends BaseController
*/
public function postUpdateIncome()
{
- /** @var \FireflyIII\Shared\Preferences\PreferencesInterface $preferences */
- $preferences = App::make('FireflyIII\Shared\Preferences\PreferencesInterface');
- $date = Session::get('start');
-
- $value = intval(Input::get('amount'));
- $preferences->set('budgetIncomeTotal' . $date->format('FY'), $value);
+ $this->_preferences->set('budgetIncomeTotal' . Session::get('start', Carbon::now()->startOfMonth())->format('FY'), intval(Input::get('amount')));
return Redirect::route('budgets.index');
}
@@ -172,124 +143,91 @@ class BudgetController extends BaseController
*/
public function show(Budget $budget, LimitRepetition $repetition = null)
{
- if (!is_null($repetition) && $repetition->limit->budget->id != $budget->id) {
- App::abort(500);
+ if (!is_null($repetition) && $repetition->budgetLimit->budget->id != $budget->id) {
+ return View::make('error')->with('message', 'Invalid selection.');
}
- /** @var \FireflyIII\Database\Budget $repos */
- $repos = App::make('FireflyIII\Database\Budget');
-
- if (is_null($repetition)) {
- // get all other repetitions:
- $limits = $budget->limits()->orderBy('startdate', 'DESC')->get();
- // get all transaction journals for this budget.
- $journals = $repos->getTransactionJournals($budget, 50);
-
- $subTitle = $budget->name;
- } 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;
+ $hideBudget = true; // used in transaction list.
+ $journals = $this->_repository->getJournals($budget, $repetition);
+ $limits = $repetition ? [$repetition->budgetLimit] : $budget->budgetLimits()->orderBy('startdate', 'DESC')->get();
+ $subTitle = $repetition ? e($budget->name) . ' in ' . $repetition->startdate->format('F Y') : e($budget->name);
return View::make('budgets.show', compact('limits', 'budget', 'repetition', 'journals', 'subTitle', 'hideBudget'));
}
/**
- * @return $this
- * @throws FireflyException
+ * @return $this|\Illuminate\Http\RedirectResponse
*/
public function store()
{
- /** @var \FireflyIII\Database\Budget $repos */
- $repos = App::make('FireflyIII\Database\Budget');
- $data = Input::except('_token');
+ $data = Input::except('_token');
+ $data['user_id'] = Auth::user()->id;
- switch ($data['post_submit_action']) {
- default:
- 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());
+ // always validate:
+ $messages = $this->_repository->validate($data);
- return Redirect::route('budgets.create')->withInput()->withErrors($messages['errors']);
- }
- // store!
- $repos->store($data);
- Session::flash('success', 'New budget stored!');
-
- 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;
+ // flash messages:
+ Session::flash('warnings', $messages['warnings']);
+ Session::flash('successes', $messages['successes']);
+ Session::flash('errors', $messages['errors']);
+ if ($messages['errors']->count() > 0) {
+ Session::flash('error', 'Could not validate budget: ' . $messages['errors']->first());
}
+
+ // 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.
+ return Redirect::route('budgets.create')->withInput();
}
+
/**
* @param Budget $budget
*
- * @return $this
- * @throws FireflyException
+ * @return $this|\Illuminate\Http\RedirectResponse
*/
public function update(Budget $budget)
{
- /** @var \FireflyIII\Database\Budget $repos */
- $repos = App::make('FireflyIII\Database\Budget');
- $data = Input::except('_token');
+ $data = Input::except('_token');
+ $data['user_id'] = Auth::user()->id;
- switch (Input::get('post_submit_action')) {
- default:
- 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());
+ // always validate:
+ $messages = $this->_repository->validate($data);
- return Redirect::route('budgets.edit', $budget->id)->withInput()->withErrors($messages['errors']);
- }
- // store!
- $repos->update($budget, $data);
- Session::flash('success', 'Budget updated!');
-
- 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;
+ // flash messages:
+ Session::flash('warnings', $messages['warnings']);
+ Session::flash('successes', $messages['successes']);
+ Session::flash('errors', $messages['errors']);
+ if ($messages['errors']->count() > 0) {
+ Session::flash('error', 'Could not update budget: ' . $messages['errors']->first());
}
+
+ // 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');
+ }
+
+ return Redirect::route('budgets.edit', $budget->id)->withInput(['post_submit_action' => 'return_to_edit']);
}
/**
@@ -297,11 +235,8 @@ class BudgetController extends BaseController
*/
public function updateIncome()
{
- $date = Session::get('start');
- /** @var \FireflyIII\Shared\Preferences\PreferencesInterface $preferences */
- $preferences = App::make('FireflyIII\Shared\Preferences\PreferencesInterface');
- $budgetAmount = $preferences->get('budgetIncomeTotal' . $date->format('FY'), 1000);
+ $budgetAmount = $this->_preferences->get('budgetIncomeTotal' . Session::get('start', Carbon::now()->startOfMonth())->format('FY'), 1000);
- return View::make('budgets.income')->with('amount', $budgetAmount)->with('date', $date);
+ return View::make('budgets.income')->with('amount', $budgetAmount);
}
-}
\ No newline at end of file
+}
diff --git a/app/controllers/CategoryController.php b/app/controllers/CategoryController.php
index 2093aa54e0..b6d6da5df8 100644
--- a/app/controllers/CategoryController.php
+++ b/app/controllers/CategoryController.php
@@ -1,19 +1,29 @@
_repository = $repository;
}
/**
@@ -41,11 +51,9 @@ class CategoryController extends BaseController
*/
public function destroy(Category $category)
{
- /** @var \FireflyIII\Database\Category $repos */
- $repos = App::make('FireflyIII\Database\Category');
+ Session::flash('success', 'Category "' . e($category->name) . '" was deleted.');
+ $this->_repository->destroy($category);
- $repos->destroy($category);
- Session::flash('success', 'The category was deleted.');
return Redirect::route('categories.index');
}
@@ -65,9 +73,7 @@ class CategoryController extends BaseController
*/
public function index()
{
- /** @var \FireflyIII\Database\Category $repos */
- $repos = App::make('FireflyIII\Database\Category');
- $categories = $repos->get();
+ $categories = $this->_repository->get();
return View::make('categories.index', compact('categories'));
}
@@ -79,12 +85,8 @@ class CategoryController extends BaseController
*/
public function show(Category $category)
{
- $hideCategory = true;
-
- /** @var \FireflyIII\Database\Category $repos */
- $repos = App::make('FireflyIII\Database\Category');
-
- $journals = $repos->getTransactionJournals($category, 50);
+ $hideCategory = true; // used in list.
+ $journals = $this->_repository->getTransactionJournals($category, 50);
return View::make('categories.show', compact('category', 'journals', 'hideCategory'));
}
@@ -95,44 +97,33 @@ class CategoryController extends BaseController
*/
public function store()
{
- $data = Input::all();
- /** @var \FireflyIII\Database\Category $repos */
- $repos = App::make('FireflyIII\Database\Category');
+ $data = Input::except('_token');
+ $data['user_id'] = Auth::user()->id;
- switch ($data['post_submit_action']) {
- default:
- 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 category: ' . $messages['errors']->first());
+ // always validate:
+ $messages = $this->_repository->validate($data);
- return Redirect::route('categories.create')->withInput()->withErrors($messages['errors']);
- }
- // store!
- $repos->store($data);
- Session::flash('success', 'New category stored!');
-
- if ($data['post_submit_action'] == 'create_another') {
- return Redirect::route('categories.create')->withInput();
- } else {
- return Redirect::route('categories.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('categories.create')->withInput();
- break;
+ // flash messages:
+ Session::flash('warnings', $messages['warnings']);
+ Session::flash('successes', $messages['successes']);
+ Session::flash('errors', $messages['errors']);
+ if ($messages['errors']->count() > 0) {
+ Session::flash('error', 'Could not store category: ' . $messages['errors']->first());
}
+
+ // return to create screen:
+ if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) {
+ return Redirect::route('categories.create')->withInput();
+ }
+
+ // store:
+ $this->_repository->store($data);
+ Session::flash('success', 'Category "' . e($data['name']) . '" stored.');
+ if ($data['post_submit_action'] == 'store') {
+ return Redirect::route('categories.index');
+ }
+
+ return Redirect::route('categories.create')->withInput();
}
/**
@@ -143,44 +134,37 @@ class CategoryController extends BaseController
*/
public function update(Category $category)
{
- /** @var \FireflyIII\Database\Category $repos */
- $repos = App::make('FireflyIII\Database\Category');
- $data = Input::except('_token');
+ $data = Input::except('_token');
+ $data['user_id'] = Auth::user()->id;
- switch (Input::get('post_submit_action')) {
- default:
- 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 category: ' . $messages['errors']->first());
+ // always validate:
+ $messages = $this->_repository->validate($data);
- return Redirect::route('categories.edit', $category->id)->withInput()->withErrors($messages['errors']);
- }
- // store!
- $repos->update($category, $data);
- Session::flash('success', 'Category updated!');
-
- if ($data['post_submit_action'] == 'return_to_edit') {
- return Redirect::route('categories.edit', $category->id);
- } else {
- return Redirect::route('categories.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('categories.edit', $category->id)->withInput();
- break;
+ // flash messages:
+ Session::flash('warnings', $messages['warnings']);
+ Session::flash('successes', $messages['successes']);
+ Session::flash('errors', $messages['errors']);
+ if ($messages['errors']->count() > 0) {
+ Session::flash('error', 'Could not update category: ' . $messages['errors']->first());
}
+ // return to update screen:
+ if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) {
+ return Redirect::route('categories.edit', $category->id)->withInput();
+ }
+
+ // update
+ $this->_repository->update($category, $data);
+ Session::flash('success', 'Category "' . e($data['name']) . '" updated.');
+
+ // go back to list
+ if ($data['post_submit_action'] == 'update') {
+ return Redirect::route('categories.index');
+ }
+
+ // go back to update screen.
+ return Redirect::route('categories.edit', $category->id)->withInput(['post_submit_action' => 'return_to_edit']);
+
}
diff --git a/app/controllers/CurrencyController.php b/app/controllers/CurrencyController.php
new file mode 100644
index 0000000000..bc2ae575ea
--- /dev/null
+++ b/app/controllers/CurrencyController.php
@@ -0,0 +1,179 @@
+_repository = $repository;
+
+
+ View::share('title', 'Currencies');
+ View::share('mainTitleIcon', 'fa-usd');
+ }
+
+ /**
+ * @return \Illuminate\View\View
+ */
+ public function create()
+ {
+ $subTitleIcon = 'fa-plus';
+ $subTitle = 'Create a new currency';
+
+ return View::make('currency.create', compact('subTitleIcon', 'subTitle'));
+ }
+
+ /**
+ * @param TransactionCurrency $currency
+ *
+ * @return \Illuminate\Http\RedirectResponse
+ */
+ public function defaultCurrency(TransactionCurrency $currency)
+ {
+ /** @var \FireflyIII\Shared\Preferences\Preferences $preferences */
+ $preferences = App::make('FireflyIII\Shared\Preferences\Preferences');
+
+ $currencyPreference = $preferences->get('currencyPreference', 'EUR');
+ $currencyPreference->data = $currency->code;
+ $currencyPreference->save();
+
+ Session::flash('success', $currency->name.' is now the default currency.');
+ Cache::forget('FFCURRENCYSYMBOL');
+ Cache::forget('FFCURRENCYCODE');
+
+ return Redirect::route('currency.index');
+
+ }
+
+ /**
+ * @param TransactionCurrency $currency
+ */
+ public function delete(TransactionCurrency $currency)
+ {
+ if ($currency->transactionJournals()->count() > 0) {
+ Session::flash('error', 'Cannot delete ' . e($currency->name) . ' because there are still transactions attached to it.');
+
+ return Redirect::route('currency.index');
+ }
+
+
+ return View::make('currency.delete', compact('currency'));
+ }
+
+ public function destroy(TransactionCurrency $currency)
+ {
+ Session::flash('success', 'Currency "' . e($currency->name) . '" deleted');
+
+ $this->_repository->destroy($currency);
+
+ return Redirect::route('currency.index');
+ }
+
+ /**
+ * @param TransactionCurrency $currency
+ *
+ * @return \Illuminate\View\View
+ */
+ public function edit(TransactionCurrency $currency)
+ {
+ $subTitleIcon = 'fa-pencil';
+ $subTitle = 'Edit currency "' . e($currency->name) . '"';
+ $currency->symbol = htmlentities($currency->symbol);
+
+ return View::make('currency.edit', compact('currency', 'subTitle', 'subTitleIcon'));
+
+ }
+
+ public function index()
+ {
+ $currencies = $this->_repository->get();
+
+ /** @var \FireflyIII\Shared\Preferences\Preferences $preferences */
+ $preferences = App::make('FireflyIII\Shared\Preferences\Preferences');
+
+ $currencyPreference = $preferences->get('currencyPreference', 'EUR');
+ $defaultCurrency = $this->_repository->findByCode($currencyPreference->data);
+
+
+ return View::make('currency.index', compact('currencies', 'defaultCurrency'));
+ }
+
+ public function store()
+ {
+ $data = Input::except('_token');
+
+ // always validate:
+ $messages = $this->_repository->validate($data);
+
+ // flash messages:
+ Session::flash('warnings', $messages['warnings']);
+ Session::flash('successes', $messages['successes']);
+ Session::flash('errors', $messages['errors']);
+ if ($messages['errors']->count() > 0) {
+ Session::flash('error', 'Could not store currency: ' . $messages['errors']->first());
+ }
+
+ // return to create screen:
+ if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) {
+ return Redirect::route('currency.create')->withInput();
+ }
+
+ // store:
+ $this->_repository->store($data);
+ Session::flash('success', 'Currency "' . e($data['name']) . '" stored.');
+ if ($data['post_submit_action'] == 'store') {
+ return Redirect::route('currency.index');
+ }
+
+ return Redirect::route('currency.create')->withInput();
+
+ }
+
+ public function update(TransactionCurrency $currency)
+ {
+ $data = Input::except('_token');
+
+ // always validate:
+ $messages = $this->_repository->validate($data);
+
+ // flash messages:
+ Session::flash('warnings', $messages['warnings']);
+ Session::flash('successes', $messages['successes']);
+ Session::flash('errors', $messages['errors']);
+ if ($messages['errors']->count() > 0) {
+ Session::flash('error', 'Could not update currency: ' . $messages['errors']->first());
+ }
+
+ // return to update screen:
+ if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) {
+ return Redirect::route('currency.edit', $currency->id)->withInput();
+ }
+
+ // update
+ $this->_repository->update($currency, $data);
+ Session::flash('success', 'Currency "' . e($data['name']) . '" updated.');
+
+ // go back to list
+ if ($data['post_submit_action'] == 'update') {
+ return Redirect::route('currency.index');
+ }
+
+ return Redirect::route('currency.edit', $currency->id)->withInput(['post_submit_action' => 'return_to_edit']);
+
+ }
+
+}
\ No newline at end of file
diff --git a/app/controllers/GoogleChartController.php b/app/controllers/GoogleChartController.php
index 0eb2b58396..2a5786c5f6 100644
--- a/app/controllers/GoogleChartController.php
+++ b/app/controllers/GoogleChartController.php
@@ -1,12 +1,41 @@
_chart = $chart;
+ $this->_repository = $repository;
+ $this->_start = Session::get('start', Carbon::now()->startOfMonth());
+ $this->_end = Session::get('end', Carbon::now()->endOfMonth());
+
+ }
+
/**
* @param Account $account
* @param string $view
@@ -15,199 +44,37 @@ class GoogleChartController extends BaseController
*/
public function accountBalanceChart(Account $account, $view = 'session')
{
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
+ $this->_chart->addColumn('Day of month', 'date');
+ $this->_chart->addColumn('Balance for ' . $account->name, 'number');
- $chart->addColumn('Day of month', 'date');
- $chart->addColumn('Balance for ' . $account->name, 'number');
+ // TODO this can be combined in some method, it's coming up quite often, is it?
+ $start = $this->_start;
+ $end = $this->_end;
+ $count = $account->transactions()->count();
- /*
- * Loop the date, then loop the accounts, then add balance.
- */
- switch ($view) {
- default:
- case 'session':
- $start = Session::get('start');
- $end = Session::get('end');
- break;
- case 'all':
- $first = $account->transactionjournals()->orderBy('date', 'DESC')->first();
- $last = $account->transactionjournals()->orderBy('date', 'ASC')->first();
- if (is_null($first)) {
- $start = Session::get('start');
- } else {
- $start = clone $first->date;
- }
- if (is_null($last)) {
- $end = Session::get('end');
- } else {
- $end = clone $last->date;
- }
- break;
+ if ($view == 'all' && $count > 0) {
+ $first = $account->transactions()->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->orderBy(
+ 'date', 'ASC'
+ )->first(['transaction_journals.date']);
+ $last = $account->transactions()->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->orderBy(
+ 'date', 'DESC'
+ )->first(['transaction_journals.date']);
+ $start = new Carbon($first->date);
+ $end = new Carbon($last->date);
}
+ // todo until this part.
$current = clone $start;
while ($end >= $current) {
- $row = [clone $current];
- if ($current > Carbon::now()) {
- $row[] = null;
- } else {
- $row[] = Steam::balance($account, $current);
- }
-
- $chart->addRowArray($row);
+ $this->_chart->addRow(clone $current, Steam::balance($account, $current));
$current->addDay();
}
- $chart->generate();
-
- return Response::json($chart->getData());
- }
-
- /**
- * @param Account $account
- * @param string $view
- *
- * @return \Illuminate\Http\JsonResponse
- */
- public function accountSankeyInChart(Account $account, $view = 'session')
- {
- // collect all relevant entries.
- $set = [];
-
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('From', 'string');
- $chart->addColumn('To', 'string', 'domain');
- $chart->addColumn('Weight', 'number');
-
- switch ($view) {
- default:
- case 'session':
- $start = Session::get('start');
- $end = Session::get('end');
- break;
- case 'all':
- $first = $account->transactionjournals()->orderBy('date', 'DESC')->first();
- $last = $account->transactionjournals()->orderBy('date', 'ASC')->first();
- if (is_null($first)) {
- $start = Session::get('start');
- } else {
- $start = clone $first->date;
- }
- if (is_null($last)) {
- $end = Session::get('end');
- } else {
- $end = clone $last->date;
- }
- break;
- }
-
-
- $transactions = $account->transactions()->with(
- ['transactionjournal', 'transactionjournal.transactions' => function ($q) {
- $q->where('amount', '<', 0);
- }, 'transactionjournal.budgets', 'transactionjournal.transactiontype', 'transactionjournal.categories']
- )->before($end)->after($start)->get();
-
- /** @var Transaction $transaction */
- foreach ($transactions as $transaction) {
- $amount = floatval($transaction->amount);
- $type = $transaction->transactionJournal->transactionType->type;
-
- if ($amount > 0 && $type != 'Transfer') {
-
- $otherAccount = $transaction->transactionJournal->transactions[0]->account->name;
- $categoryName = isset($transaction->transactionJournal->categories[0]) ? $transaction->transactionJournal->categories[0]->name : '(no cat)';
- $set[] = [$otherAccount, $categoryName, $amount];
- $set[] = [$categoryName, $account->name, $amount];
- }
- }
- // loop the set, group everything together:
- $grouped = [];
- foreach ($set as $entry) {
- $key = $entry[0] . $entry[1];
- if (isset($grouped[$key])) {
- $grouped[$key][2] += $entry[2];
- } else {
- $grouped[$key] = $entry;
- }
- }
-
- // add rows to the chart:
- foreach ($grouped as $entry) {
- $chart->addRow($entry[0], $entry[1], $entry[2]);
- }
-
- $chart->generate();
-
- return Response::json($chart->getData());
-
- }
-
- /**
- * @param Account $account
- * @param string $view
- *
- * @return \Illuminate\Http\JsonResponse
- */
- public function accountSankeyOutChart(Account $account, $view = 'session')
- {
- // collect all relevant entries.
- $set = [];
-
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('From', 'string');
- $chart->addColumn('To', 'string', 'domain');
- $chart->addColumn('Weight', 'number');
-
- $transactions = $account->transactions()->with(
- ['transactionjournal', 'transactionjournal.transactions', 'transactionjournal.budgets', 'transactionjournal.transactiontype',
- 'transactionjournal.categories']
- )->before(Session::get('end'))->after(
- Session::get('start')
- )->get();
-
- /** @var Transaction $transaction */
- foreach ($transactions as $transaction) {
- $amount = floatval($transaction->amount);
- $type = $transaction->transactionJournal->transactionType->type;
-
- if ($amount < 0 && $type != 'Transfer') {
-
- // from account to a budget (if present).
- $budgetName = isset($transaction->transactionJournal->budgets[0]) ? $transaction->transactionJournal->budgets[0]->name : '(no budget)';
- $set[] = [$account->name, $budgetName, $amount * -1];
-
- // from budget to category.
- $categoryName = isset($transaction->transactionJournal->categories[0]) ? ' ' . $transaction->transactionJournal->categories[0]->name
- : '(no cat)';
- $set[] = [$budgetName, $categoryName, $amount * -1];
- }
- }
- // loop the set, group everything together:
- $grouped = [];
- foreach ($set as $entry) {
- $key = $entry[0] . $entry[1];
- if (isset($grouped[$key])) {
- $grouped[$key][2] += $entry[2];
- } else {
- $grouped[$key] = $entry;
- }
- }
-
- // add rows to the chart:
- foreach ($grouped as $entry) {
- $chart->addRow($entry[0], $entry[1], $entry[2]);
- }
-
- $chart->generate();
-
- return Response::json($chart->getData());
+ $this->_chart->generate();
+ return Response::json($this->_chart->getData());
}
/**
@@ -215,51 +82,34 @@ class GoogleChartController extends BaseController
*/
public function allAccountsBalanceChart()
{
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Day of the month', 'date');
+ $this->_chart->addColumn('Day of the month', 'date');
/** @var \FireflyIII\Shared\Preferences\Preferences $preferences */
$preferences = App::make('FireflyIII\Shared\Preferences\Preferences');
$pref = $preferences->get('frontpageAccounts', []);
- /** @var \FireflyIII\Database\Account $acct */
- $acct = App::make('FireflyIII\Database\Account');
- if (count($pref->data) > 0) {
- $accounts = $acct->getByIds($pref->data);
- } else {
- $accounts = $acct->getAssetAccounts();
- }
+ /** @var \FireflyIII\Database\Account\Account $acct */
+ $acct = App::make('FireflyIII\Database\Account\Account');
+ $accounts = count($pref->data) > 0 ? $acct->getByIds($pref->data) : $acct->getAssetAccounts();
-
- /*
- * Add a column for each account.
- */
/** @var Account $account */
foreach ($accounts as $account) {
- $chart->addColumn('Balance for ' . $account->name, 'number');
+ $this->_chart->addColumn('Balance for ' . $account->name, 'number');
}
- /*
- * Loop the date, then loop the accounts, then add balance.
- */
- $start = Session::get('start');
- $end = Session::get('end');
- $current = clone $start;
+ $current = clone $this->_start;
- while ($end >= $current) {
+ while ($this->_end >= $current) {
$row = [clone $current];
-
foreach ($accounts as $account) {
$row[] = Steam::balance($account, $current);
}
-
- $chart->addRowArray($row);
+ $this->_chart->addRowArray($row);
$current->addDay();
}
- $chart->generate();
+ $this->_chart->generate();
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
}
@@ -268,68 +118,49 @@ class GoogleChartController extends BaseController
*/
public function allBudgetsHomeChart()
{
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Budget', 'string');
- $chart->addColumn('Budgeted', 'number');
- $chart->addColumn('Spent', 'number');
+ $this->_chart->addColumn('Budget', 'string');
+ $this->_chart->addColumn('Budgeted', 'number');
+ $this->_chart->addColumn('Spent', 'number');
- /** @var \FireflyIII\Database\Budget $bdt */
- $bdt = App::make('FireflyIII\Database\Budget');
+ Log::debug('Now in allBudgetsHomeChart()');
+
+ /** @var \FireflyIII\Database\Budget\Budget $bdt */
+ $bdt = App::make('FireflyIII\Database\Budget\Budget');
$budgets = $bdt->get();
- /*
- * Loop budgets:
- */
/** @var Budget $budget */
foreach ($budgets as $budget) {
- /*
- * Is there a repetition starting on this particular date? We can use that.
- */
+ Log::debug('Now working budget #'.$budget->id.', '.$budget->name);
+
/** @var \LimitRepetition $repetition */
- $repetition = $bdt->repetitionOnStartingOnDate($budget, Session::get('start'));
-
- /*
- * If there is, use it. Otherwise, forget it.
- */
+ $repetition = $bdt->repetitionOnStartingOnDate($budget, $this->_start);
if (is_null($repetition)) {
+ \Log::debug('Budget #'.$budget->id.' has no repetition on ' . $this->_start->format('Y-m-d'));
// use the session start and end for our search query
- $searchStart = Session::get('start');
- $searchEnd = Session::get('end');
- // the limit is zero:
- $limit = 0;
-
+ $searchStart = $this->_start;
+ $searchEnd = $this->_end;
+ $limit = 0; // the limit is zero:
} else {
+ \Log::debug('Budget #'.$budget->id.' has a repetition on ' . $this->_start->format('Y-m-d').'!');
// use the limit's start and end for our search query
$searchStart = $repetition->startdate;
$searchEnd = $repetition->enddate;
- // the limit is the repetitions limit:
- $limit = floatval($repetition->amount);
+ $limit = floatval($repetition->amount); // the limit is the repetitions limit:
}
- /*
- * No matter the result of the search for the repetition, get all the transactions associated
- * with the budget, and sum up the expenses made.
- */
$expenses = floatval($budget->transactionjournals()->before($searchEnd)->after($searchStart)->lessThan(0)->sum('amount')) * -1;
if ($expenses > 0) {
- $chart->addRow($budget->name, $limit, $expenses);
+ $this->_chart->addRow($budget->name, $limit, $expenses);
}
}
- /*
- * Finally, get all transactions WITHOUT a budget and add those as well.
- * (yes this method is oddly specific).
- */
- $noBudgetSet = $bdt->transactionsWithoutBudgetInDateRange(Session::get('start'), Session::get('end'));
+ $noBudgetSet = $bdt->transactionsWithoutBudgetInDateRange($this->_start, $this->_end);
$sum = $noBudgetSet->sum('amount') * -1;
- $chart->addRow('No budget', 0, $sum);
+ $this->_chart->addRow('No budget', 0, $sum);
+ $this->_chart->generate();
-
- $chart->generate();
-
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
}
/**
@@ -337,48 +168,26 @@ class GoogleChartController extends BaseController
*/
public function allCategoriesHomeChart()
{
- $data = [];
+ $this->_chart->addColumn('Category', 'string');
+ $this->_chart->addColumn('Spent', 'number');
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Category', 'string');
- $chart->addColumn('Spent', 'number');
+ // query!
+ $set = $this->_repository->getCategorySummary($this->_start, $this->_end);
- /** @var \FireflyIII\Database\TransactionJournal $tj */
- $tj = App::make('FireflyIII\Database\TransactionJournal');
-
- /*
- * Get the journals:
- */
- $journals = $tj->getInDateRange(Session::get('start'), Session::get('end'));
-
- /** @var \TransactionJournal $journal */
- foreach ($journals as $journal) {
- if ($journal->transactionType->type == 'Withdrawal') {
- $amount = $journal->getAmount();
- $category = $journal->categories()->first();
- if (!is_null($category)) {
- if (isset($data[$category->name])) {
- $data[$category->name] += $amount;
- } else {
- $data[$category->name] = $amount;
- }
- }
- }
- }
- arsort($data);
- foreach ($data as $key => $entry) {
- $chart->addRow($key, $entry);
+ foreach ($set as $entry) {
+ $entry->name = strlen($entry->name) == 0 ? '(no category)' : $entry->name;
+ $this->_chart->addRow($entry->name, floatval($entry->sum));
}
+ $this->_chart->generate();
- $chart->generate();
-
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
}
/**
+ * TODO still in use?
+ *
* @param Budget $budget
* @param LimitRepetition $repetition
*
@@ -389,10 +198,8 @@ class GoogleChartController extends BaseController
$start = clone $repetition->startdate;
$end = $repetition->enddate;
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Day', 'date');
- $chart->addColumn('Left', 'number');
+ $this->_chart->addColumn('Day', 'date');
+ $this->_chart->addColumn('Left', 'number');
$amount = $repetition->amount;
@@ -403,105 +210,42 @@ class GoogleChartController extends BaseController
*/
$sum = floatval($budget->transactionjournals()->lessThan(0)->transactionTypes(['Withdrawal'])->onDate($start)->sum('amount'));
$amount += $sum;
- $chart->addRow(clone $start, $amount);
+ $this->_chart->addRow(clone $start, $amount);
$start->addDay();
}
- $chart->generate();
+ $this->_chart->generate();
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
}
/**
- * @param $year
+ * TODO still in use?
*
- * @return \Illuminate\Http\JsonResponse
- */
- public function budgetsReportChart($year)
- {
-
- try {
- $start = new Carbon('01-01-' . $year);
- } catch (Exception $e) {
- App::abort(500);
- }
-
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
-
- /** @var \FireflyIII\Database\Budget $bdt */
- $bdt = App::make('FireflyIII\Database\Budget');
- $budgets = $bdt->get();
-
- $chart->addColumn('Month', 'date');
- /** @var \Budget $budget */
- foreach ($budgets as $budget) {
- $chart->addColumn($budget->name, 'number');
- }
- $chart->addColumn('No budget', 'number');
-
- /*
- * Loop budgets this year.
- */
- $end = clone $start;
- $end->endOfYear();
- while ($start <= $end) {
- $row = [clone $start];
-
- foreach ($budgets as $budget) {
- $row[] = $bdt->spentInMonth($budget, $start);
- }
-
- /*
- * Without a budget:
- */
- $endOfMonth = clone $start;
- $endOfMonth->endOfMonth();
- $set = $bdt->transactionsWithoutBudgetInDateRange($start, $endOfMonth);
- $row[] = floatval($set->sum('amount')) * -1;
-
- $chart->addRowArray($row);
- $start->addMonth();
- }
-
-
- $chart->generate();
-
- return Response::json($chart->getData());
- }
-
- /**
- * @param Component $component
+ * @param Budget $component
* @param $year
*
* @return \Illuminate\Http\JsonResponse
*/
- public function componentsAndSpending(Component $component, $year)
+ public function budgetsAndSpending(Budget $component, $year)
{
try {
- $start = new Carbon('01-01-' . $year);
+ new Carbon('01-01-' . $year);
} catch (Exception $e) {
- App::abort(500);
+ return View::make('error')->with('message', 'Invalid year.');
}
- if ($component->class == 'Budget') {
- /** @var \FireflyIII\Database\Budget $repos */
- $repos = App::make('FireflyIII\Database\Budget');
- } else {
- /** @var \FireflyIII\Database\Category $repos */
- $repos = App::make('FireflyIII\Database\Category');
- }
+ /** @var \FireflyIII\Database\Budget\Budget $repos */
+ $repos = App::make('FireflyIII\Database\Budget\Budget');
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Month', 'date');
- $chart->addColumn('Budgeted', 'number');
- $chart->addColumn('Spent', 'number');
+ $this->_chart->addColumn('Month', 'date');
+ $this->_chart->addColumn('Budgeted', 'number');
+ $this->_chart->addColumn('Spent', 'number');
- $end = clone $start;
+ $start = new Carbon('01-01-' . $year);
+ $end = clone $start;
$end->endOfYear();
while ($start <= $end) {
-
$spent = $repos->spentInMonth($component, $start);
$repetition = $repos->repetitionOnStartingOnDate($component, $start);
if ($repetition) {
@@ -510,15 +254,59 @@ class GoogleChartController extends BaseController
$budgeted = null;
}
- $chart->addRow(clone $start, $budgeted, $spent);
+ $this->_chart->addRow(clone $start, $budgeted, $spent);
$start->addMonth();
}
- $chart->generate();
+ $this->_chart->generate();
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
+
+
+ }
+
+ /**
+ * TODO still in use?
+ *
+ * @param Category $component
+ * @param $year
+ *
+ * @return \Illuminate\Http\JsonResponse
+ */
+ public function categoriesAndSpending(Category $component, $year)
+ {
+ try {
+ new Carbon('01-01-' . $year);
+ } catch (Exception $e) {
+ return View::make('error')->with('message', 'Invalid year.');
+ }
+
+ /** @var \FireflyIII\Database\Category\Category $repos */
+ $repos = App::make('FireflyIII\Database\Category\Category');
+
+ $this->_chart->addColumn('Month', 'date');
+ $this->_chart->addColumn('Budgeted', 'number');
+ $this->_chart->addColumn('Spent', 'number');
+
+ $start = new Carbon('01-01-' . $year);
+ $end = clone $start;
+ $end->endOfYear();
+ while ($start <= $end) {
+
+ $spent = $repos->spentInMonth($component, $start);
+ $budgeted = null;
+
+ $this->_chart->addRow(clone $start, $budgeted, $spent);
+
+ $start->addMonth();
+ }
+
+
+ $this->_chart->generate();
+
+ return Response::json($this->_chart->getData());
}
@@ -530,20 +318,18 @@ class GoogleChartController extends BaseController
*/
public function piggyBankHistory(\Piggybank $piggybank)
{
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Date', 'date');
- $chart->addColumn('Balance', 'number');
+ $this->_chart->addColumn('Date', 'date');
+ $this->_chart->addColumn('Balance', 'number');
- $set = \DB::table('piggybank_events')->where('piggybank_id', $piggybank->id)->groupBy('date')->get(['date', DB::Raw('SUM(`amount`) AS `sum`')]);
+ $set = \DB::table('piggy_bank_events')->where('piggybank_id', $piggybank->id)->groupBy('date')->get(['date', DB::Raw('SUM(`amount`) AS `sum`')]);
foreach ($set as $entry) {
- $chart->addRow(new Carbon($entry->date), floatval($entry->sum));
+ $this->_chart->addRow(new Carbon($entry->date), floatval($entry->sum));
}
- $chart->generate();
+ $this->_chart->generate();
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
}
@@ -555,12 +341,10 @@ class GoogleChartController extends BaseController
public function recurringOverview(RecurringTransaction $recurring)
{
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Date', 'date');
- $chart->addColumn('Max amount', 'number');
- $chart->addColumn('Min amount', 'number');
- $chart->addColumn('Current entry', 'number');
+ $this->_chart->addColumn('Date', 'date');
+ $this->_chart->addColumn('Max amount', 'number');
+ $this->_chart->addColumn('Min amount', 'number');
+ $this->_chart->addColumn('Current entry', 'number');
// get first transaction or today for start:
$first = $recurring->transactionjournals()->orderBy('date', 'ASC')->first();
@@ -578,98 +362,50 @@ class GoogleChartController extends BaseController
$amount = 0;
}
unset($result);
- $chart->addRow(clone $start, $recurring->amount_max, $recurring->amount_min, $amount);
+ $this->_chart->addRow(clone $start, $recurring->amount_max, $recurring->amount_min, $amount);
$start = DateKit::addPeriod($start, $recurring->repeat_freq, 0);
}
- $chart->generate();
+ $this->_chart->generate();
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
}
/**
+ * TODO query move to helper.
+ *
* @return \Illuminate\Http\JsonResponse
* @throws \FireflyIII\Exception\FireflyException
*/
public function recurringTransactionsOverview()
{
-
- /*
- * Set of paid transaction journals.
- * Set of unpaid recurring transactions.
- */
$paid = ['items' => [], 'amount' => 0];
$unpaid = ['items' => [], 'amount' => 0];
+ $this->_chart->addColumn('Name', 'string');
+ $this->_chart->addColumn('Amount', 'number');
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Name', 'string');
- $chart->addColumn('Amount', 'number');
-
- /** @var \FireflyIII\Database\Recurring $rcr */
- $rcr = App::make('FireflyIII\Database\Recurring');
-
- $recurring = $rcr->get();
-
- /** @var \RecurringTransaction $entry */
- foreach ($recurring as $entry) {
- /*
- * Start another loop starting at the $date.
- */
- $start = clone $entry->date;
- $end = Carbon::now();
-
- /*
- * The jump we make depends on the $repeat_freq
- */
- $current = clone $start;
-
- while ($current <= $end) {
- /*
- * Get end of period for $current:
- */
- $currentEnd = DateKit::endOfPeriod($current, $entry->repeat_freq);
-
- /*
- * In the current session range?
- */
- if (\Session::get('end') >= $current and $currentEnd >= \Session::get('start')) {
- /*
- * Lets see if we've already spent money on this recurring transaction (it hath recurred).
- */
- /** @var TransactionJournal $set */
- $journal = $rcr->getJournalForRecurringInRange($entry, $current, $currentEnd);
-
- if (is_null($journal)) {
- $unpaid['items'][] = $entry->name;
- $unpaid['amount'] += (($entry->amount_max + $entry->amount_min) / 2);
- } else {
- $amount = $journal->getAmount();
- $paid['items'][] = $journal->description;
- $paid['amount'] += $amount;
- }
- }
-
- /*
- * Add some time for the next loop!
- */
- $current = DateKit::addPeriod($current, $entry->repeat_freq, intval($entry->skip));
+ $set = $this->_repository->getRecurringSummary($this->_start, $this->_end);
+ foreach ($set as $entry) {
+ if (intval($entry->journalId) == 0) {
+ $unpaid['items'][] = $entry->name;
+ $unpaid['amount'] += floatval($entry->averageAmount);
+ } else {
+ $paid['items'][] = $entry->description;
+ $paid['amount'] += floatval($entry->actualAmount);
}
-
}
- /** @var \RecurringTransaction $entry */
- $chart->addRow('Unpaid: ' . join(', ', $unpaid['items']), $unpaid['amount']);
- $chart->addRow('Paid: ' . join(', ', $paid['items']), $paid['amount']);
-
- $chart->generate();
-
- return Response::json($chart->getData());
+ $this->_chart->addRow('Unpaid: ' . join(', ', $unpaid['items']), $unpaid['amount']);
+ $this->_chart->addRow('Paid: ' . join(', ', $paid['items']), $paid['amount']);
+ $this->_chart->generate();
+ return Response::json($this->_chart->getData());
}
/**
+ * TODO see reports for better way to do this.
+ *
* @param $year
*
* @return \Illuminate\Http\JsonResponse
@@ -679,37 +415,37 @@ class GoogleChartController extends BaseController
try {
$start = new Carbon('01-01-' . $year);
} catch (Exception $e) {
- App::abort(500);
+ return View::make('error')->with('message', 'Invalid year.');
}
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Month', 'date');
- $chart->addColumn('Income', 'number');
- $chart->addColumn('Expenses', 'number');
+ $this->_chart->addColumn('Month', 'date');
+ $this->_chart->addColumn('Income', 'number');
+ $this->_chart->addColumn('Expenses', 'number');
- /** @var \FireflyIII\Database\TransactionJournal $tj */
- $tj = App::make('FireflyIII\Database\TransactionJournal');
+ /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repository */
+ $repository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal');
$end = clone $start;
$end->endOfYear();
while ($start < $end) {
// total income:
- $income = $tj->getSumOfIncomesByMonth($start);
- $expense = $tj->getSumOfExpensesByMonth($start);
+ $income = $repository->getSumOfIncomesByMonth($start);
+ $expense = $repository->getSumOfExpensesByMonth($start);
- $chart->addRow(clone $start, $income, $expense);
+ $this->_chart->addRow(clone $start, $income, $expense);
$start->addMonth();
}
- $chart->generate();
+ $this->_chart->generate();
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
}
/**
+ * TODO see reports for better way to do this.
+ *
* @param $year
*
* @return \Illuminate\Http\JsonResponse
@@ -719,16 +455,14 @@ class GoogleChartController extends BaseController
try {
$start = new Carbon('01-01-' . $year);
} catch (Exception $e) {
- App::abort(500);
+ return View::make('error')->with('message', 'Invalid year.');
}
- /** @var \Grumpydictator\Gchart\GChart $chart */
- $chart = App::make('gchart');
- $chart->addColumn('Summary', 'string');
- $chart->addColumn('Income', 'number');
- $chart->addColumn('Expenses', 'number');
+ $this->_chart->addColumn('Summary', 'string');
+ $this->_chart->addColumn('Income', 'number');
+ $this->_chart->addColumn('Expenses', 'number');
- /** @var \FireflyIII\Database\TransactionJournal $tj */
- $tj = App::make('FireflyIII\Database\TransactionJournal');
+ /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repository */
+ $repository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal');
$end = clone $start;
$end->endOfYear();
@@ -738,20 +472,20 @@ class GoogleChartController extends BaseController
while ($start < $end) {
// total income:
- $income += $tj->getSumOfIncomesByMonth($start);
- $expense += $tj->getSumOfExpensesByMonth($start);
+ $income += $repository->getSumOfIncomesByMonth($start);
+ $expense += $repository->getSumOfExpensesByMonth($start);
$count++;
$start->addMonth();
}
- $chart->addRow('Sum', $income, $expense);
+ $this->_chart->addRow('Sum', $income, $expense);
$count = $count > 0 ? $count : 1;
- $chart->addRow('Average', ($income / $count), ($expense / $count));
+ $this->_chart->addRow('Average', ($income / $count), ($expense / $count));
- $chart->generate();
+ $this->_chart->generate();
- return Response::json($chart->getData());
+ return Response::json($this->_chart->getData());
}
}
\ No newline at end of file
diff --git a/app/controllers/HelpController.php b/app/controllers/HelpController.php
index 1424351c40..ee5f57fbfc 100644
--- a/app/controllers/HelpController.php
+++ b/app/controllers/HelpController.php
@@ -12,11 +12,9 @@ class HelpController extends BaseController
*/
public function show($route)
{
- // no valid route
+ $helpText = '
There is no help for this route!
'; + $helpTitle = 'Help'; if (!Route::has($route)) { - $helpText = 'There is no help for this route!
'; - $helpTitle = 'Help'; - return Response::json(['title' => $helpTitle, 'text' => $helpText]); } @@ -28,25 +26,17 @@ class HelpController extends BaseController return Response::json(['title' => $helpTitle, 'text' => $helpText]); } - // get the help-content from Github: - $URL = 'https://raw.githubusercontent.com/JC5/firefly-iii-help/master/' . e($route) . '.md'; + $uri = 'https://raw.githubusercontent.com/JC5/firefly-iii-help/master/' . e($route) . '.md'; try { - $content = file_get_contents($URL); + $content = file_get_contents($uri); } catch (ErrorException $e) { $content = 'There is no help for this route.
'; } - if (strlen($content) > 0) { - $helpText = \Michelf\Markdown::defaultTransform($content); - $helpTitle = $route; + $helpText = \Michelf\Markdown::defaultTransform($content); + $helpTitle = $route; - Cache::put('help.' . $route . '.text', $helpText, 10080); // a week. - Cache::put('help.' . $route . '.title', $helpTitle, 10080); - - return Response::json(['title' => $helpTitle, 'text' => $helpText]); - } - - $helpText = 'There is no help for this route!
'; - $helpTitle = 'Help'; + Cache::put('help.' . $route . '.text', $helpText, 10080); // a week. + Cache::put('help.' . $route . '.title', $helpTitle, 10080); return Response::json(['title' => $helpTitle, 'text' => $helpText]); diff --git a/app/controllers/HomeController.php b/app/controllers/HomeController.php index 9617608efc..faea3a7f68 100644 --- a/app/controllers/HomeController.php +++ b/app/controllers/HomeController.php @@ -1,4 +1,5 @@ countAssetAccounts(); - $start = Session::get('start'); - $end = Session::get('end'); + $start = Session::get('start', Carbon::now()->startOfMonth()); + $end = Session::get('end', Carbon::now()->endOfMonth()); // get the preference for the home accounts to show: @@ -47,7 +48,7 @@ class HomeController extends BaseController $transactions = []; foreach ($accounts as $account) { - $set = $jrnls->getInDateRangeAccount($account, 10, $start, $end); + $set = $jrnls->getInDateRangeAccount($account, $start, $end, 10); if (count($set) > 0) { $transactions[] = [$set, $account]; } @@ -76,7 +77,7 @@ class HomeController extends BaseController Session::forget('range'); } - return Redirect::back(); + return Redirect::intended('/'); } /** @@ -86,7 +87,7 @@ class HomeController extends BaseController { Navigation::next(); - return Redirect::back(); + return Redirect::intended('/'); } /** @@ -96,6 +97,6 @@ class HomeController extends BaseController { Navigation::prev(); - return Redirect::back(); + return Redirect::intended('/'); } } \ No newline at end of file diff --git a/app/controllers/JsonController.php b/app/controllers/JsonController.php index 9f0512572a..094a3fc040 100644 --- a/app/controllers/JsonController.php +++ b/app/controllers/JsonController.php @@ -14,8 +14,8 @@ class JsonController extends BaseController */ public function categories() { - /** @var \FireflyIII\Database\Category $categories */ - $categories = App::make('FireflyIII\Database\Category'); + /** @var \FireflyIII\Database\Category\Category $categories */ + $categories = App::make('FireflyIII\Database\Category\Category'); $list = $categories->get(); $return = []; foreach ($list as $entry) { @@ -34,8 +34,8 @@ class JsonController extends BaseController */ public function expenseAccounts() { - /** @var \FireflyIII\Database\Account $accounts */ - $accounts = App::make('FireflyIII\Database\Account'); + /** @var \FireflyIII\Database\Account\Account $accounts */ + $accounts = App::make('FireflyIII\Database\Account\Account'); $list = $accounts->getExpenseAccounts(); $return = []; foreach ($list as $entry) { @@ -51,8 +51,8 @@ class JsonController extends BaseController */ public function revenueAccounts() { - /** @var \FireflyIII\Database\Account $accounts */ - $accounts = App::make('FireflyIII\Database\Account'); + /** @var \FireflyIII\Database\Account\Account $accounts */ + $accounts = App::make('FireflyIII\Database\Account\Account'); $list = $accounts->getRevenueAccounts(); $return = []; foreach ($list as $entry) { diff --git a/app/controllers/PiggybankController.php b/app/controllers/PiggybankController.php index eb933934af..307197ac32 100644 --- a/app/controllers/PiggybankController.php +++ b/app/controllers/PiggybankController.php @@ -1,21 +1,35 @@ _repository = $repository; + View::share('title', 'Piggy banks'); + View::share('mainTitleIcon', 'fa-sort-amount-asc'); } /** @@ -27,16 +41,23 @@ class PiggybankController extends BaseController */ public function add(Piggybank $piggybank) { - /** @var \FireflyIII\Database\Piggybank $repos */ - $repos = App::make('FireflyIII\Database\Piggybank'); + \Log::debug('Now in add() for piggy bank #' . $piggybank->id . ' (' . $piggybank->name . ')'); + \Log::debug('Z'); + \Log::debug('currentRelevantRep is null: ' . boolstr($piggybank->currentRelevantRep())); + $leftOnAccount = $this->_repository->leftOnAccount($piggybank->account); + \Log::debug('A'); - $leftOnAccount = $repos->leftOnAccount($piggybank->account); - $savedSoFar = $piggybank->currentRelevantRep()->currentamount; - $leftToSave = $piggybank->targetamount - $savedSoFar; - $amount = min($leftOnAccount, $leftToSave); + $savedSoFar = $piggybank->currentRelevantRep()->currentamount; + \Log::debug('B'); + $leftToSave = $piggybank->targetamount - $savedSoFar; + \Log::debug('C'); + $maxAmount = min($leftOnAccount, $leftToSave); + \Log::debug('D'); - return View::make('piggybanks.add', compact('piggybank'))->with('maxAmount', $amount); + \Log::debug('Now going to view for piggy bank #' . $piggybank->id . ' (' . $piggybank->name . ')'); + + return View::make('piggybanks.add', compact('piggybank', 'maxAmount')); } /** @@ -45,17 +66,15 @@ class PiggybankController extends BaseController public function create() { - /** @var \FireflyIII\Database\Account $acct */ - $acct = App::make('FireflyIII\Database\Account'); + /** @var \FireflyIII\Database\Account\Account $acct */ + $acct = App::make('FireflyIII\Database\Account\Account'); - $periods = Config::get('firefly.piggybank_periods'); + $periods = Config::get('firefly.piggybank_periods'); + $accounts = FFForm::makeSelectList($acct->getAssetAccounts()); + $subTitle = 'Create new piggy bank'; + $subTitleIcon = 'fa-plus'; - - $accounts = FFForm::makeSelectList($acct->getAssetAccounts()); - - return View::make('piggybanks.create', compact('accounts', 'periods'))->with('title', 'Piggy banks')->with('mainTitleIcon', 'fa-sort-amount-asc')->with( - 'subTitle', 'Create new piggy bank' - )->with('subTitleIcon', 'fa-plus'); + return View::make('piggybanks.create', compact('accounts', 'periods', 'subTitle', 'subTitleIcon')); } /** @@ -65,9 +84,9 @@ class PiggybankController extends BaseController */ public function delete(Piggybank $piggybank) { - return View::make('piggybanks.delete')->with('piggybank', $piggybank)->with('subTitle', 'Delete "' . $piggybank->name . '"')->with( - 'title', 'Piggy banks' - )->with('mainTitleIcon', 'fa-sort-amount-asc'); + $subTitle = 'Delete "' . e($piggybank->name) . '"'; + + return View::make('piggybanks.delete', compact('piggybank', 'subTitle')); } /** @@ -77,10 +96,9 @@ class PiggybankController extends BaseController */ public function destroy(Piggybank $piggyBank) { - /** @var \FireflyIII\Database\Piggybank $acct */ - $repos = App::make('FireflyIII\Database\Piggybank'); - $repos->destroy($piggyBank); - Session::flash('success', 'Piggy bank deleted.'); + + Session::flash('success', 'Piggy bank "' . e($piggyBank->name) . '" deleted.'); + $this->_repository->destroy($piggyBank); return Redirect::route('piggybanks.index'); } @@ -93,28 +111,33 @@ class PiggybankController extends BaseController public function edit(Piggybank $piggybank) { - /** @var \FireflyIII\Database\Account $acct */ - $acct = App::make('FireflyIII\Database\Account'); + /** @var \FireflyIII\Database\Account\Account $acct */ + $acct = App::make('FireflyIII\Database\Account\Account'); - $periods = Config::get('firefly.piggybank_periods'); - - $accounts = FFForm::makeSelectList($acct->getAssetAccounts()); + $periods = Config::get('firefly.piggybank_periods'); + $accounts = FFForm::makeSelectList($acct->getAssetAccounts()); + $subTitle = 'Edit piggy bank "' . e($piggybank->name) . '"'; + $subTitleIcon = 'fa-pencil'; /* * Flash some data to fill the form. */ + if (is_null($piggybank->targetdate) || $piggybank->targetdate == '') { + $targetDate = null; + } else { + $targetDate = new Carbon($piggybank->targetdate); + $targetDate = $targetDate->format('Y-m-d'); + } $preFilled = ['name' => $piggybank->name, 'account_id' => $piggybank->account_id, 'targetamount' => $piggybank->targetamount, - 'targetdate' => !is_null($piggybank->targetdate) ? $piggybank->targetdate->format('Y-m-d') : null, + 'targetdate' => $targetDate, 'reminder' => $piggybank->reminder, 'remind_me' => intval($piggybank->remind_me) == 1 || !is_null($piggybank->reminder) ? true : false ]; Session::flash('preFilled', $preFilled); - return View::make('piggybanks.edit', compact('piggybank', 'accounts', 'periods', 'preFilled'))->with('title', 'Piggybanks')->with( - 'mainTitleIcon', 'fa-sort-amount-asc' - )->with('subTitle', 'Edit piggy bank "' . e($piggybank->name) . '"')->with('subTitleIcon', 'fa-pencil'); + return View::make('piggybanks.edit', compact('subTitle', 'subTitleIcon', 'piggybank', 'accounts', 'periods', 'preFilled')); } /** @@ -122,11 +145,8 @@ class PiggybankController extends BaseController */ public function index() { - /** @var \FireflyIII\Database\Piggybank $repos */ - $repos = App::make('FireflyIII\Database\Piggybank'); - /** @var Collection $piggybanks */ - $piggybanks = $repos->get(); + $piggybanks = $this->_repository->get(); $accounts = []; /** @var Piggybank $piggybank */ @@ -140,9 +160,14 @@ class PiggybankController extends BaseController */ $account = $piggybank->account; if (!isset($accounts[$account->id])) { - $accounts[$account->id] = ['name' => $account->name, 'balance' => Steam::balance($account), - 'leftForPiggybanks' => $repos->leftOnAccount($account), 'sumOfSaved' => $piggybank->savedSoFar, - 'sumOfTargets' => floatval($piggybank->targetamount), 'leftToSave' => $piggybank->leftToSave]; + $accounts[$account->id] = [ + 'name' => $account->name, + 'balance' => Steam::balance($account), + 'leftForPiggybanks' => $this->_repository->leftOnAccount($account), + 'sumOfSaved' => $piggybank->savedSoFar, + 'sumOfTargets' => floatval($piggybank->targetamount), + 'leftToSave' => $piggybank->leftToSave + ]; } else { $accounts[$account->id]['sumOfSaved'] += $piggybank->savedSoFar; $accounts[$account->id]['sumOfTargets'] += floatval($piggybank->targetamount); @@ -150,7 +175,7 @@ class PiggybankController extends BaseController } } - return View::make('piggybanks.index', compact('piggybanks', 'accounts'))->with('title', 'Piggy banks')->with('mainTitleIcon', 'fa-sort-amount-asc'); + return View::make('piggybanks.index', compact('piggybanks', 'accounts')); } /** @@ -164,8 +189,8 @@ class PiggybankController extends BaseController { $amount = round(floatval(Input::get('amount')), 2); - /** @var \FireflyIII\Database\Piggybank $acct */ - $repos = App::make('FireflyIII\Database\Piggybank'); + /** @var \FireflyIII\Database\PiggyBank\PiggyBank $acct */ + $repos = App::make('FireflyIII\Database\PiggyBank\PiggyBank'); $leftOnAccount = $repos->leftOnAccount($piggybank->account); $savedSoFar = $piggybank->currentRelevantRep()->currentamount; @@ -226,7 +251,7 @@ class PiggybankController extends BaseController */ public function remove(Piggybank $piggybank) { - return View::make('piggybanks.remove', compact('piggybank')); + return View::make('piggybanks.remove')->with('piggybank', $piggybank); } /** @@ -245,12 +270,9 @@ class PiggybankController extends BaseController $amountPerReminder = $piggybank->amountPerReminder(); $remindersCount = $piggybank->countFutureReminders(); + $subTitle = e($piggybank->name); - return View::make('piggybanks.show', compact('amountPerReminder', 'remindersCount', 'piggybank', 'events'))->with('title', 'Piggy banks')->with( - 'mainTitleIcon', 'fa-sort-amount-asc' - )->with( - 'subTitle', $piggybank->name - ); + return View::make('piggybanks.show', compact('amountPerReminder', 'remindersCount', 'piggybank', 'events', 'subTitle')); } @@ -261,49 +283,35 @@ class PiggybankController extends BaseController { $data = Input::all(); $data['repeats'] = 0; - /** @var \FireflyIII\Database\Piggybank $repos */ - $repos = App::make('FireflyIII\Database\Piggybank'); + $data['user_id'] = Auth::user()->id; - switch ($data['post_submit_action']) { - default: - 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 piggy bank: ' . $messages['errors']->first()); - return Redirect::route('piggybanks.create')->withInput()->withErrors($messages['errors']); - } - // store! - $piggyBank = $repos->store($data); + // always validate: + $messages = $this->_repository->validate($data); - /* - * Create the relevant repetition per Event. - */ - Event::fire('piggybank.store', [$piggyBank]); // new and used. - - Session::flash('success', 'New piggy bank stored!'); - - if ($data['post_submit_action'] == 'create_another') { - return Redirect::route('piggybanks.create')->withInput(); - } else { - return Redirect::route('piggybanks.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('piggybanks.create')->withInput(); - break; + // flash messages: + Session::flash('warnings', $messages['warnings']); + Session::flash('successes', $messages['successes']); + Session::flash('errors', $messages['errors']); + if ($messages['errors']->count() > 0) { + Session::flash('error', 'Could not store piggy bank: ' . $messages['errors']->first()); } + + + // return to create screen: + if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) { + return Redirect::route('piggybanks.create')->withInput(); + } + + // store: + $piggyBank = $this->_repository->store($data); + Event::fire('piggybank.store', [$piggyBank]); // new and used. + Session::flash('success', 'Piggy bank "' . e($data['name']) . '" stored.'); + if ($data['post_submit_action'] == 'store') { + return Redirect::route('piggybanks.index'); + } + + return Redirect::route('piggybanks.create')->withInput(); } /** @@ -315,45 +323,40 @@ class PiggybankController extends BaseController public function update(Piggybank $piggyBank) { - /** @var \FireflyIII\Database\Piggybank $repos */ - $repos = App::make('FireflyIII\Database\Piggybank'); - $data = Input::except('_token'); + $data = Input::except('_token'); + $data['rep_every'] = 0; + $data['reminder_skip'] = 0; + $data['order'] = 0; + $data['remind_me'] = isset($data['remind_me']) ? 1 : 0; + $data['user_id'] = Auth::user()->id; - switch (Input::get('post_submit_action')) { - default: - 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 piggy bank: ' . $messages['errors']->first()); + // always validate: + $messages = $this->_repository->validate($data); - return Redirect::route('piggybanks.edit', $piggyBank->id)->withInput()->withErrors($messages['errors']); - } - // store! - $repos->update($piggyBank, $data); - Event::fire('piggybank.update', [$piggyBank]); // new and used. - Session::flash('success', 'Piggy bank updated!'); - - if ($data['post_submit_action'] == 'return_to_edit') { - return Redirect::route('piggybanks.edit', $piggyBank->id); - } else { - return Redirect::route('piggybanks.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('piggybanks.edit', $piggyBank->id)->withInput(); - break; + // flash messages: + Session::flash('warnings', $messages['warnings']); + Session::flash('successes', $messages['successes']); + Session::flash('errors', $messages['errors']); + if ($messages['errors']->count() > 0) { + Session::flash('error', 'Could not update piggy bank: ' . $messages['errors']->first()); } + // return to update screen: + if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) { + return Redirect::route('piggybanks.edit', $piggyBank->id)->withInput(); + } + + // update + $this->_repository->update($piggyBank, $data); + Session::flash('success', 'Piggy bank "' . e($data['name']) . '" updated.'); + + // go back to list + if ($data['post_submit_action'] == 'update') { + return Redirect::route('piggybanks.index'); + } + + // go back to update screen. + return Redirect::route('piggybanks.edit', $piggyBank->id)->withInput(['post_submit_action' => 'return_to_edit']); } } \ No newline at end of file diff --git a/app/controllers/PreferencesController.php b/app/controllers/PreferencesController.php index 0d6a373843..1330af52ef 100644 --- a/app/controllers/PreferencesController.php +++ b/app/controllers/PreferencesController.php @@ -3,6 +3,8 @@ /** * Class PreferencesController * + * @SuppressWarnings("CyclomaticComplexity") // It's all 5. So ok. + * */ class PreferencesController extends BaseController { @@ -21,8 +23,8 @@ class PreferencesController extends BaseController */ public function index() { - /** @var \FireflyIII\Database\Account $acct */ - $acct = App::make('FireflyIII\Database\Account'); + /** @var \FireflyIII\Database\Account\Account $acct */ + $acct = App::make('FireflyIII\Database\Account\Account'); /** @var \FireflyIII\Shared\Preferences\Preferences $preferences */ $preferences = App::make('FireflyIII\Shared\Preferences\Preferences'); @@ -30,9 +32,13 @@ class PreferencesController extends BaseController $accounts = $acct->getAssetAccounts(); $viewRange = $preferences->get('viewRange', '1M'); $viewRangeValue = $viewRange->data; - $frontpage = $preferences->get('frontpageAccounts', []); + $frontPage = $preferences->get('frontpageAccounts', []); + $budgetMax = $preferences->get('budgetMaximum', 1000); + $budgetMaximum = $budgetMax->data; - return View::make('preferences.index')->with('accounts', $accounts)->with('frontpageAccounts', $frontpage)->with('viewRange', $viewRangeValue); + return View::make('preferences.index', compact('budgetMaximum'))->with('accounts', $accounts)->with('frontpageAccounts', $frontPage)->with( + 'viewRange', $viewRangeValue + ); } /** @@ -40,7 +46,6 @@ class PreferencesController extends BaseController */ public function postIndex() { - /** @var \FireflyIII\Shared\Preferences\Preferences $preferences */ $preferences = App::make('FireflyIII\Shared\Preferences\Preferences'); @@ -58,6 +63,11 @@ class PreferencesController extends BaseController Session::forget('end'); Session::forget('range'); + // budget maximum: + $budgetMaximum = intval(Input::get('budgetMaximum')); + $preferences->set('budgetMaximum', $budgetMaximum); + + Session::flash('success', 'Preferences saved!'); return Redirect::route('preferences'); diff --git a/app/controllers/ProfileController.php b/app/controllers/ProfileController.php index 938d41f28a..d5373ec0c5 100644 --- a/app/controllers/ProfileController.php +++ b/app/controllers/ProfileController.php @@ -32,7 +32,6 @@ class ProfileController extends BaseController { // old, new1, new2 - /** @noinspection PhpUndefinedFieldInspection */ if (!Hash::check(Input::get('old'), Auth::user()->password)) { Session::flash('error', 'Invalid current password!'); @@ -56,8 +55,8 @@ class ProfileController extends BaseController } // update the user with the new password. - /** @var \FireflyIII\Database\User $repository */ - $repository = \App::make('FireflyIII\Database\User'); + /** @var \FireflyIII\Database\User\User $repository */ + $repository = \App::make('FireflyIII\Database\User\User'); $repository->updatePassword(Auth::user(), Input::get('new1')); Session::flash('success', 'Password changed!'); diff --git a/app/controllers/RecurringController.php b/app/controllers/RecurringController.php index bd3a7faed6..84be23917a 100644 --- a/app/controllers/RecurringController.php +++ b/app/controllers/RecurringController.php @@ -49,8 +49,8 @@ class RecurringController extends BaseController { //Event::fire('recurring.destroy', [$recurringTransaction]); - /** @var \FireflyIII\Database\Recurring $repository */ - $repository = App::make('FireflyIII\Database\Recurring'); + /** @var \FireflyIII\Database\RecurringTransaction\RecurringTransaction $repository */ + $repository = App::make('FireflyIII\Database\RecurringTransaction\RecurringTransaction'); $result = $repository->destroy($recurringTransaction); if ($result === true) { @@ -82,8 +82,8 @@ class RecurringController extends BaseController */ public function index() { - /** @var \FireflyIII\Database\Recurring $repos */ - $repos = App::make('FireflyIII\Database\Recurring'); + /** @var \FireflyIII\Database\RecurringTransaction\RecurringTransaction $repos */ + $repos = App::make('FireflyIII\Database\RecurringTransaction\RecurringTransaction'); $recurring = $repos->get(); @@ -103,8 +103,8 @@ class RecurringController extends BaseController return Redirect::back(); } - /** @var \FireflyIII\Database\Recurring $repos */ - $repos = App::make('FireflyIII\Database\Recurring'); + /** @var \FireflyIII\Database\RecurringTransaction\RecurringTransaction $repos */ + $repos = App::make('FireflyIII\Database\RecurringTransaction\RecurringTransaction'); $repos->scanEverything($recurringTransaction); Session::flash('success', 'Rescanned everything.'); @@ -135,8 +135,8 @@ class RecurringController extends BaseController public function store() { $data = Input::except('_token'); - /** @var \FireflyIII\Database\Recurring $repos */ - $repos = App::make('FireflyIII\Database\Recurring'); + /** @var \FireflyIII\Database\RecurringTransaction\RecurringTransaction $repos */ + $repos = App::make('FireflyIII\Database\RecurringTransaction\RecurringTransaction'); switch ($data['post_submit_action']) { default: @@ -183,9 +183,11 @@ class RecurringController extends BaseController */ public function update(RecurringTransaction $recurringTransaction) { - /** @var \FireflyIII\Database\Recurring $repos */ - $repos = App::make('FireflyIII\Database\Recurring'); - $data = Input::except('_token'); + /** @var \FireflyIII\Database\RecurringTransaction\RecurringTransaction $repos */ + $repos = App::make('FireflyIII\Database\RecurringTransaction\RecurringTransaction'); + $data = Input::except('_token'); + $data['active'] = isset($data['active']) ? 1 : 0; + $data['automatch'] = isset($data['automatch']) ? 1 : 0; switch (Input::get('post_submit_action')) { default: diff --git a/app/controllers/RepeatedExpenseController.php b/app/controllers/RepeatedExpenseController.php index b3bdd762e0..71f821dfbc 100644 --- a/app/controllers/RepeatedExpenseController.php +++ b/app/controllers/RepeatedExpenseController.php @@ -1,21 +1,25 @@ _repository = $repository; } /** @@ -23,8 +27,8 @@ class RepeatedExpenseController extends BaseController */ public function create() { - /** @var \FireflyIII\Database\Account $acct */ - $acct = App::make('FireflyIII\Database\Account'); + /** @var \FireflyIII\Database\Account\Account $acct */ + $acct = App::make('FireflyIII\Database\Account\Account'); $periods = Config::get('firefly.piggybank_periods'); @@ -44,8 +48,8 @@ class RepeatedExpenseController extends BaseController $subTitle = 'Overview'; - /** @var \FireflyIII\Database\RepeatedExpense $repository */ - $repository = App::make('FireflyIII\Database\RepeatedExpense'); + /** @var \FireflyIII\Database\PiggyBank\RepeatedExpense $repository */ + $repository = App::make('FireflyIII\Database\PiggyBank\RepeatedExpense'); $expenses = $repository->get(); $expenses->each( @@ -67,13 +71,13 @@ class RepeatedExpenseController extends BaseController $subTitle = $piggyBank->name; $today = Carbon::now(); - /** @var \FireflyIII\Database\RepeatedExpense $repository */ - $repository = App::make('FireflyIII\Database\RepeatedExpense'); + /** @var \FireflyIII\Database\PiggyBank\RepeatedExpense $repository */ + $repository = App::make('FireflyIII\Database\PiggyBank\RepeatedExpense'); $repetitions = $piggyBank->piggybankrepetitions()->get(); $repetitions->each( function (PiggybankRepetition $repetition) use ($repository) { - $repository->calculateParts($repetition); + $repetition->bars = $repository->calculateParts($repetition); } ); @@ -86,50 +90,36 @@ class RepeatedExpenseController extends BaseController */ public function store() { - $data = Input::all(); + $data = Input::except('_token'); $data['repeats'] = 1; - /** @var \FireflyIII\Database\RepeatedExpense $repository */ - $repository = App::make('FireflyIII\Database\RepeatedExpense'); - switch ($data['post_submit_action']) { - default: - throw new FireflyException('Cannot handle post_submit_action "' . e($data['post_submit_action']) . '"'); - break; - case 'create_another': - case 'store': - $messages = $repository->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 repeated expense: ' . $messages['errors']->first()); + // always validate: + $messages = $this->_repository->validate($data); - return Redirect::route('repeated.create')->withInput()->withErrors($messages['errors']); - } - // store! - $repeated = $repository->store($data); - - /* - * Create the relevant repetition per Event. - */ - Event::fire('piggybank.store', [$repeated]); // new and used. - - Session::flash('success', 'New repeated expense stored!'); - - if ($data['post_submit_action'] == 'create_another') { - return Redirect::route('repeated.create')->withInput(); - } else { - return Redirect::route('repeated.index'); - } - break; - case 'validate_only': - $messageBags = $repository->validate($data); - Session::flash('warnings', $messageBags['warnings']); - Session::flash('successes', $messageBags['successes']); - Session::flash('errors', $messageBags['errors']); - - return Redirect::route('repeated.create')->withInput(); - break; + // flash messages: + Session::flash('warnings', $messages['warnings']); + Session::flash('successes', $messages['successes']); + Session::flash('errors', $messages['errors']); + if ($messages['errors']->count() > 0) { + Session::flash('error', 'Could not validate repeated expense: ' . $messages['errors']->first()); } + // return to create screen: + if ($data['post_submit_action'] == 'validate_only' || $messages['errors']->count() > 0) { + return Redirect::route('repeated.create')->withInput(); + } + + // store: + $this->_repository->store($data); + Session::flash('success', 'Budget "' . e($data['name']) . '" stored.'); + if ($data['post_submit_action'] == 'store') { + return Redirect::route('repeated.index'); + } + + // create another. + if ($data['post_submit_action'] == 'create_another') { + return Redirect::route('repeated.create')->withInput(); + } + + return Redirect::route('repeated.index'); } } \ No newline at end of file diff --git a/app/controllers/ReportController.php b/app/controllers/ReportController.php index 1bb335e453..96e806fa0b 100644 --- a/app/controllers/ReportController.php +++ b/app/controllers/ReportController.php @@ -1,11 +1,11 @@ _accounts = $accounts; $this->_journals = $journals; - $this->_reports = $reports; $this->_repository = $repository; } - /** - * @param $year - * @param $month - * - * @return \Illuminate\View\View - */ - public function budgets($year, $month) - { - try { - $start = new Carbon($year . '-' . $month . '-01'); - } catch (Exception $e) { - App::abort(500); - } - $end = clone $start; - $title = 'Reports'; - $subTitle = 'Budgets in ' . $start->format('F Y'); - $mainTitleIcon = 'fa-line-chart'; - $subTitleIcon = 'fa-bar-chart'; - - $end->endOfMonth(); - - - // get a list of all budgets and expenses. - /** @var \FireflyIII\Database\Budget $budgetRepository */ - $budgetRepository = App::make('FireflyIII\Database\Budget'); - - /** @var \FireflyIII\Database\Account $accountRepository */ - $accountRepository = App::make('FireflyIII\Database\Account'); - - - $budgets = $budgetRepository->get(); - - // calculate some stuff: - $budgets->each( - function (Budget $budget) use ($start, $end, $budgetRepository) { - $limitRepetitions = $budget->limitrepetitions()->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d'))->where( - 'enddate', '<=', $end->format( - 'Y-m-d' - ) - )->get(); - $repInfo = []; - /** @var LimitRepetition $repetition */ - foreach ($limitRepetitions as $repetition) { - $spent = $budgetRepository->spentInPeriod($budget, $start, $end); - if ($spent > floatval($repetition->amount)) { - // overspent! - $overspent = true; - $pct = floatval($repetition->amount) / $spent * 100; - - } else { - $overspent = false; - $pct = $spent / floatval($repetition->amount) * 100; - } - $pctDisplay = $spent / floatval($repetition->amount) * 100; - $repInfo[] = [ - 'date' => DateKit::periodShow($repetition->startdate, $repetition->limit->repeat_freq), - 'spent' => $spent, - 'budgeted' => floatval($repetition->amount), - 'left' => floatval($repetition->amount) - $spent, - 'pct' => ceil($pct), - 'pct_display' => ceil($pctDisplay), - 'overspent' => $overspent, - ]; - } - $budget->repInfo = $repInfo; - - } - ); - - $accounts = $accountRepository->getAssetAccounts(); - - $accounts->each( - function (Account $account) use ($start, $end, $accountRepository) { - $journals = $accountRepository->getTransactionJournalsInRange($account, $start, $end); - $budgets = []; - /** @var TransactionJournal $journal */ - foreach ($journals as $journal) { - $budgetId = isset($journal->budgets[0]) ? $journal->budgets[0]->id : 0; - $budgetName = isset($journal->budgets[0]) ? $journal->budgets[0]->name : '(no budget)'; - if (!isset($budgets[$budgetId])) { - $arr = [ - 'budget_id' => $budgetId, - 'budget_name' => $budgetName, - 'spent' => floatval($journal->getAmount()), - 'budgeted' => 0, - ]; - $budgets[$budgetId] = $arr; - } else { - $budgets[$budgetId]['spent'] += floatval($journal->getAmount()); - } - } - foreach ($budgets as $budgetId => $budget) { - $budgets[$budgetId]['left'] = $budget['budgeted'] - $budget['spent']; - } - $account->budgetInfo = $budgets; - } - ); - - - return View::make('reports.budgets', compact('start', 'end', 'title', 'subTitle', 'subTitleIcon', 'mainTitleIcon', 'budgets', 'accounts')); - - } - /** * */ public function index() { $start = $this->_journals->firstDate(); - $months = $this->_reports->listOfMonths(clone $start); - $years = $this->_reports->listOfYears(clone $start); + $months = $this->_repository->listOfMonths(clone $start); + $years = $this->_repository->listOfYears(clone $start); $title = 'Reports'; $mainTitleIcon = 'fa-line-chart'; @@ -163,7 +55,7 @@ class ReportController extends BaseController public function unbalanced($year, $month) { try { - $date = new Carbon($year . '-' . $month . '-01'); + new Carbon($year . '-' . $month . '-01'); } catch (Exception $e) { App::abort(500); } @@ -175,61 +67,37 @@ class ReportController extends BaseController $subTitleIcon = 'fa-bar-chart'; $end->endOfMonth(); - /** @var \FireflyIII\Database\TransactionJournal $journalRepository */ - $journalRepository = App::make('FireflyIII\Database\TransactionJournal'); + /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $journalRepository */ + $journalRepository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal'); + $journals = $journalRepository->getInDateRange($start, $end); - /* - * Get all journals from this month: - */ - $journals = $journalRepository->getInDateRange($start, $end); - - /* - * Filter withdrawals: - */ $withdrawals = $journals->filter( function (TransactionJournal $journal) { - if ($journal->transactionType->type == 'Withdrawal' && count($journal->budgets) == 0) { - - // count groups related to balance. - if ($journal->transactiongroups()->where('relation', 'balance')->count() == 0) { - return $journal; - } + $relations = $journal->transactiongroups()->where('relation', 'balance')->count(); + $budgets = $journal->budgets()->count(); + $type = $journal->transactionType->type; + if ($type == 'Withdrawal' && $budgets == 0 && $relations == 0) { + return $journal; } return null; } ); - /* - * Filter deposits. - */ $deposits = $journals->filter( function (TransactionJournal $journal) { - if ($journal->transactionType->type == 'Deposit' && count($journal->budgets) == 0) { - // count groups related to balance. - if ($journal->transactiongroups()->where('relation', 'balance')->count() == 0) { - return $journal; - } + $relations = $journal->transactiongroups()->where('relation', 'balance')->count(); + $budgets = $journal->budgets()->count(); + $type = $journal->transactionType->type; + if ($type == 'Deposit' && $budgets == 0 && $relations == 0) { + return $journal; } return null; } ); - - /* - * Filter transfers (not yet used) - */ - // $transfers = $journals->filter( - // function (TransactionJournal $journal) { - // if ($journal->transactionType->type == 'Transfer') { - // return $journal; - // } - // } - // ); - $journals = $withdrawals->merge($deposits); - return View::make('reports.unbalanced', compact('start', 'end', 'title', 'subTitle', 'subTitleIcon', 'mainTitleIcon', 'journals')); } @@ -245,74 +113,21 @@ class ReportController extends BaseController } catch (Exception $e) { App::abort(500); } - $date = new Carbon('01-01-' . $year); + $date = new Carbon('01-01-' . $year); + $end = clone $date; + $end->endOfYear(); $title = 'Reports'; $subTitle = $year; $subTitleIcon = 'fa-bar-chart'; $mainTitleIcon = 'fa-line-chart'; - $balances = $this->_reports->yearBalanceReport($date); - $groupedIncomes = $this->_reports->groupByRevenue($date, 'income'); - $groupedExpenses = $this->_reports->groupByRevenue($date, 'expense'); - + $balances = $this->_repository->yearBalanceReport($date); + $groupedIncomes = $this->_repository->revenueGroupedByAccount($date, $end, 15); + $groupedExpenses = $this->_repository->expensesGroupedByAccount($date, $end, 15); return View::make( 'reports.year', compact('date', 'groupedIncomes', 'groupedExpenses', 'year', 'balances', 'title', 'subTitle', 'subTitleIcon', 'mainTitleIcon') ); - - - /* - * For this year, get: - * - the sum of all expenses. - * - the sum of all incomes - * - per month, the sum of all expenses - * - per month, the sum of all incomes - * - 2x for shared and not-shared alike. - * - * - balance difference for all accounts. - */ - - $accounts = $accountRepository->getAssetAccounts(); - - // get some sums going - $summary = []; - - $end = clone $date; - $end->endOfYear(); - while ($date < $end) { - $month = $date->format('F'); - - $income = 0; - $incomeShared = 0; - $expense = 0; - $expenseShared = 0; - - foreach ($accounts as $account) { - if ($account->accountRole == 'sharedExpense') { - $incomeShared += $reportRepository->getIncomeByMonth($account, $date); - $expenseShared += $reportRepository->getExpenseByMonth($account, $date); - } else { - $income += $reportRepository->getIncomeByMonth($account, $date); - $expense += $reportRepository->getExpenseByMonth($account, $date); - } - } - - $summary[] = [ - 'month' => $month, - 'income' => $income, - 'expense' => $expense, - 'incomeShared' => $incomeShared, - 'expenseShared' => $expenseShared, - ]; - $date->addMonth(); - } - - - // draw some charts etc. - return View::make('reports.year', compact('summary', 'date'))->with('title', 'Reports')->with('mainTitleIcon', 'fa-line-chart')->with('subTitle', $year) - ->with( - 'subTitleIcon', 'fa-bar-chart' - )->with('year', $year); } } \ No newline at end of file diff --git a/app/controllers/TransactionController.php b/app/controllers/TransactionController.php index 5885f53f2d..7f1eb8ca3a 100644 --- a/app/controllers/TransactionController.php +++ b/app/controllers/TransactionController.php @@ -45,11 +45,11 @@ class TransactionController extends BaseController } } $unique = array_unique($ids); - if (count($ids) > 0) { + if (count($unique) > 0) { - /** @var \FireflyIII\Database\TransactionJournal $repository */ - $repository = App::make('FireflyIII\Database\TransactionJournal'); - $set = $repository->getByIds($ids); + /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repository */ + $repository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal'); + $set = $repository->getByIds($unique); $set->each( function (TransactionJournal $journal) { $journal->amount = mf($journal->getAmount()); @@ -71,21 +71,17 @@ class TransactionController extends BaseController */ public function create($what = 'deposit') { - /* - * The repositories we need: - */ + /** @var \FireflyIII\Database\Account\Account $accountRepository */ + $accountRepository = App::make('FireflyIII\Database\Account\Account'); - /** @var \FireflyIII\Database\Account $accountRepository */ - $accountRepository = App::make('FireflyIII\Database\Account'); + /** @var \FireflyIII\Database\Budget\Budget $budgetRepository */ + $budgetRepository = App::make('FireflyIII\Database\Budget\Budget'); - /** @var \FireflyIII\Database\Budget $budgetRepository */ - $budgetRepository = App::make('FireflyIII\Database\Budget'); + /** @var \FireflyIII\Database\PiggyBank\PiggyBank $piggyRepository */ + $piggyRepository = App::make('FireflyIII\Database\PiggyBank\PiggyBank'); - /** @var \FireflyIII\Database\Piggybank $piggyRepository */ - $piggyRepository = App::make('FireflyIII\Database\Piggybank'); - - /** @var \FireflyIII\Database\RepeatedExpense $repRepository */ - $repRepository = App::make('FireflyIII\Database\RepeatedExpense'); + /** @var \FireflyIII\Database\PiggyBank\RepeatedExpense $repRepository */ + $repRepository = App::make('FireflyIII\Database\PiggyBank\RepeatedExpense'); // get asset accounts with names and id's . $assetAccounts = FFForm::makeSelectList($accountRepository->getAssetAccounts()); @@ -100,9 +96,6 @@ class TransactionController extends BaseController $piggies[0] = '(no piggy bank)'; asort($piggies); - /* - * respond to a possible given values in the URL. - */ $preFilled = Session::has('preFilled') ? Session::get('preFilled') : []; $respondTo = ['account_id', 'account_from_id']; foreach ($respondTo as $r) { @@ -143,8 +136,8 @@ class TransactionController extends BaseController { $type = $transactionJournal->transactionType->type; - /** @var \FireflyIII\Database\TransactionJournal $repository */ - $repository = App::make('FireflyIII\Database\TransactionJournal'); + /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repository */ + $repository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal'); $repository->destroy($transactionJournal); $return = 'withdrawal'; @@ -172,8 +165,8 @@ class TransactionController extends BaseController $id = intval(Input::get('id')); $sister = intval(Input::get('relateTo')); - /** @var \FireflyIII\Database\TransactionJournal $repository */ - $repository = App::make('FireflyIII\Database\TransactionJournal'); + /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repository */ + $repository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal'); $journal = $repository->find($id); $sis = $repository->find($sister); @@ -207,39 +200,25 @@ class TransactionController extends BaseController * All the repositories we need: */ - /** @var \FireflyIII\Database\Account $accountRepository */ - $accountRepository = App::make('FireflyIII\Database\Account'); + /** @var \FireflyIII\Database\Account\Account $accountRepository */ + $accountRepository = App::make('FireflyIII\Database\Account\Account'); - /** @var \FireflyIII\Database\Budget $budgetRepository */ - $budgetRepository = App::make('FireflyIII\Database\Budget'); + /** @var \FireflyIII\Database\Budget\Budget $budgetRepository */ + $budgetRepository = App::make('FireflyIII\Database\Budget\Budget'); - /** @var \FireflyIII\Database\Piggybank $piggyRepository */ - $piggyRepository = App::make('FireflyIII\Database\Piggybank'); + /** @var \FireflyIII\Database\PiggyBank\PiggyBank $piggyRepository */ + $piggyRepository = App::make('FireflyIII\Database\PiggyBank\PiggyBank'); // type is useful for display: $what = strtolower($journal->transactiontype->type); // get asset accounts with names and id's. + + $budgets = FFForm::makeSelectList($budgetRepository->get(), true); $accounts = FFForm::makeSelectList($accountRepository->getAssetAccounts()); + $piggies = FFForm::makeSelectList($piggyRepository->get(), true); - // get budgets as a select list. - $budgets = FFForm::makeSelectList($budgetRepository->get()); - $budgets[0] = '(no budget)'; - - /* - * Get all piggy banks plus (if any) the relevant piggy bank. Since just one - * of the transactions in the journal has this field, it should all fill in nicely. - */ - // get the piggy banks. - $piggies = FFForm::makeSelectList($piggyRepository->get()); - $piggies[0] = '(no piggy bank)'; - $piggyBankId = 0; - foreach ($journal->transactions as $t) { - if (!is_null($t->piggybank_id)) { - $piggyBankId = $t->piggybank_id; - } - } /* * Data to properly display the edit form. @@ -248,7 +227,7 @@ class TransactionController extends BaseController 'date' => $journal->date->format('Y-m-d'), 'category' => '', 'budget_id' => 0, - 'piggybank_id' => $piggyBankId + 'piggybank_id' => 0 ]; /* @@ -335,8 +314,8 @@ class TransactionController extends BaseController public function index($what) { - /** @var \FireflyIII\Database\TransactionJournal $repository */ - $repository = App::make('FireflyIII\Database\TransactionJournal'); + /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repository */ + $repository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal'); switch ($what) { case 'expenses': @@ -396,8 +375,8 @@ class TransactionController extends BaseController { $search = e(trim(Input::get('searchValue'))); - /** @var \FireflyIII\Database\TransactionJournal $repository */ - $repository = App::make('FireflyIII\Database\TransactionJournal'); + /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repository */ + $repository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal'); $result = $repository->searchRelated($search, $journal); $result->each( @@ -456,8 +435,8 @@ class TransactionController extends BaseController $data['what'] = $what; $data['currency'] = 'EUR'; - /** @var \FireflyIII\Database\TransactionJournal $repository */ - $repository = App::make('FireflyIII\Database\TransactionJournal'); + /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repository */ + $repository = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal'); switch ($data['post_submit_action']) { default: @@ -482,11 +461,7 @@ class TransactionController extends BaseController * Trigger a search for the related (if selected) * piggy bank and store an event. */ - $piggyID = null; - if (!is_null(Input::get('piggybank_id')) && intval(Input::get('piggybank_id')) > 0) { - $piggyID = intval(Input::get('piggybank_id')); - } - Event::fire('transactionJournal.store', [$journal, $piggyID]); // new and used. + Event::fire('transactionJournal.store', [$journal, Input::get('piggybank_id')]); // new and used. /* * Also trigger on both transactions. */ @@ -544,12 +519,13 @@ class TransactionController extends BaseController /** * @param TransactionJournal $journal * + * @return $this * @throws FireflyException */ public function update(TransactionJournal $journal) { - /** @var \FireflyIII\Database\TransactionJournal $repos */ - $repos = App::make('FireflyIII\Database\TransactionJournal'); + /** @var \FireflyIII\Database\TransactionJournal\TransactionJournal $repos */ + $repos = App::make('FireflyIII\Database\TransactionJournal\TransactionJournal'); $data = Input::except('_token'); $data['currency'] = 'EUR'; diff --git a/app/controllers/UserController.php b/app/controllers/UserController.php index 5d101c850f..4cf00ce1a1 100644 --- a/app/controllers/UserController.php +++ b/app/controllers/UserController.php @@ -71,8 +71,8 @@ class UserController extends BaseController return View::make('error')->with('message', 'Not possible'); } - /** @var \FireflyIII\Database\User $repository */ - $repository = App::make('FireflyIII\Database\User'); + /** @var \FireflyIII\Database\User\User $repository */ + $repository = App::make('FireflyIII\Database\User\User'); /** @var \FireflyIII\Shared\Mail\RegistrationInterface $email */ $email = App::make('FireflyIII\Shared\Mail\RegistrationInterface'); @@ -105,8 +105,8 @@ class UserController extends BaseController public function postRemindme() { - /** @var \FireflyIII\Database\User $repository */ - $repository = App::make('FireflyIII\Database\User'); + /** @var \FireflyIII\Database\User\User $repository */ + $repository = App::make('FireflyIII\Database\User\User'); /** @var \FireflyIII\Shared\Mail\RegistrationInterface $email */ $email = App::make('FireflyIII\Shared\Mail\RegistrationInterface'); @@ -163,8 +163,8 @@ class UserController extends BaseController public function reset($reset) { - /** @var \FireflyIII\Database\User $repository */ - $repository = App::make('FireflyIII\Database\User'); + /** @var \FireflyIII\Database\User\User $repository */ + $repository = App::make('FireflyIII\Database\User\User'); /** @var \FireflyIII\Shared\Mail\RegistrationInterface $email */ $email = App::make('FireflyIII\Shared\Mail\RegistrationInterface'); diff --git a/app/database/migrations/2014_06_27_163032_create_users_table.php b/app/database/migrations/2014_06_27_163032_create_users_table.php index ef3ebbabbe..3c72c3ab6c 100644 --- a/app/database/migrations/2014_06_27_163032_create_users_table.php +++ b/app/database/migrations/2014_06_27_163032_create_users_table.php @@ -5,8 +5,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateUsersTable - * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateUsersTable extends Migration { diff --git a/app/database/migrations/2014_06_27_163145_create_account_types_table.php b/app/database/migrations/2014_06_27_163145_create_account_types_table.php index 3c81582a50..7d90098389 100644 --- a/app/database/migrations/2014_06_27_163145_create_account_types_table.php +++ b/app/database/migrations/2014_06_27_163145_create_account_types_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateAccountTypesTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateAccountTypesTable extends Migration { diff --git a/app/database/migrations/2014_06_27_163259_create_accounts_table.php b/app/database/migrations/2014_06_27_163259_create_accounts_table.php index 8a7251f61f..71d3cd8a37 100644 --- a/app/database/migrations/2014_06_27_163259_create_accounts_table.php +++ b/app/database/migrations/2014_06_27_163259_create_accounts_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateAccountsTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateAccountsTable extends Migration { diff --git a/app/database/migrations/2014_06_27_163817_create_components_table.php b/app/database/migrations/2014_06_27_163817_create_components_table.php index 605ef98205..2c4852f02c 100644 --- a/app/database/migrations/2014_06_27_163817_create_components_table.php +++ b/app/database/migrations/2014_06_27_163817_create_components_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateComponentsTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateComponentsTable extends Migration { diff --git a/app/database/migrations/2014_06_27_163818_create_piggybanks_table.php b/app/database/migrations/2014_06_27_163818_create_piggybanks_table.php index 0587903fc0..5ac466d43e 100644 --- a/app/database/migrations/2014_06_27_163818_create_piggybanks_table.php +++ b/app/database/migrations/2014_06_27_163818_create_piggybanks_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreatePiggybanksTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreatePiggybanksTable extends Migration { @@ -46,7 +45,7 @@ class CreatePiggybanksTable extends Migration $table->boolean('remind_me'); $table->integer('order')->unsigned(); - // connect account to piggybank. + // connect account to piggy bank. $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); // for an account, the name must be unique. diff --git a/app/database/migrations/2014_06_27_164042_create_transaction_currencies_table.php b/app/database/migrations/2014_06_27_164042_create_transaction_currencies_table.php index 8cecacf2e8..a6444da219 100644 --- a/app/database/migrations/2014_06_27_164042_create_transaction_currencies_table.php +++ b/app/database/migrations/2014_06_27_164042_create_transaction_currencies_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateTransactionCurrenciesTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateTransactionCurrenciesTable extends Migration { diff --git a/app/database/migrations/2014_06_27_164512_create_transaction_types_table.php b/app/database/migrations/2014_06_27_164512_create_transaction_types_table.php index 568704210e..77a3d9924c 100644 --- a/app/database/migrations/2014_06_27_164512_create_transaction_types_table.php +++ b/app/database/migrations/2014_06_27_164512_create_transaction_types_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateTransactionTypesTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateTransactionTypesTable extends Migration { diff --git a/app/database/migrations/2014_06_27_164619_create_recurring_transactions_table.php b/app/database/migrations/2014_06_27_164619_create_recurring_transactions_table.php index e37936f210..c3e9aea81b 100644 --- a/app/database/migrations/2014_06_27_164619_create_recurring_transactions_table.php +++ b/app/database/migrations/2014_06_27_164619_create_recurring_transactions_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateRecurringTransactionsTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateRecurringTransactionsTable extends Migration { diff --git a/app/database/migrations/2014_06_27_164620_create_transaction_journals_table.php b/app/database/migrations/2014_06_27_164620_create_transaction_journals_table.php index 7f751797c4..b44af8769c 100644 --- a/app/database/migrations/2014_06_27_164620_create_transaction_journals_table.php +++ b/app/database/migrations/2014_06_27_164620_create_transaction_journals_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateTransactionJournalsTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateTransactionJournalsTable extends Migration { diff --git a/app/database/migrations/2014_06_27_164836_create_transactions_table.php b/app/database/migrations/2014_06_27_164836_create_transactions_table.php index 38453f93b6..74765c1910 100644 --- a/app/database/migrations/2014_06_27_164836_create_transactions_table.php +++ b/app/database/migrations/2014_06_27_164836_create_transactions_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateTransactionsTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateTransactionsTable extends Migration { diff --git a/app/database/migrations/2014_06_27_165344_create_component_transaction_table.php b/app/database/migrations/2014_06_27_165344_create_component_transaction_table.php index 99e1d8649c..d5f73f8444 100644 --- a/app/database/migrations/2014_06_27_165344_create_component_transaction_table.php +++ b/app/database/migrations/2014_06_27_165344_create_component_transaction_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateComponentTransactionTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateComponentTransactionTable extends Migration { @@ -18,7 +17,7 @@ class CreateComponentTransactionTable extends Migration */ public function down() { - Schema::drop('component_transaction'); + Schema::dropIfExists('component_transaction'); } /** diff --git a/app/database/migrations/2014_07_05_171326_create_component_transaction_journal_table.php b/app/database/migrations/2014_07_05_171326_create_component_transaction_journal_table.php index 4474c18ec7..2069e961a9 100644 --- a/app/database/migrations/2014_07_05_171326_create_component_transaction_journal_table.php +++ b/app/database/migrations/2014_07_05_171326_create_component_transaction_journal_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateComponentTransactionJournalTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateComponentTransactionJournalTable extends Migration { @@ -30,19 +29,19 @@ class CreateComponentTransactionJournalTable extends Migration { Schema::create( 'component_transaction_journal', function (Blueprint $table) { - $table->increments('id'); - $table->integer('component_id')->unsigned(); - $table->integer('transaction_journal_id')->unsigned(); + $table->increments('id'); + $table->integer('component_id')->unsigned(); + $table->integer('transaction_journal_id')->unsigned(); - // link components with component_id - $table->foreign('component_id')->references('id')->on('components')->onDelete('cascade'); + // link components with component_id + $table->foreign('component_id')->references('id')->on('components')->onDelete('cascade'); - // link transaction journals with transaction_journal_id - $table->foreign('transaction_journal_id')->references('id')->on('transaction_journals')->onDelete('cascade'); + // link transaction journals with transaction_journal_id + $table->foreign('transaction_journal_id')->references('id')->on('transaction_journals')->onDelete('cascade'); - // combo must be unique: - $table->unique(['component_id', 'transaction_journal_id'],'cid_tjid_unique'); - } + // combo must be unique: + $table->unique(['component_id', 'transaction_journal_id'], 'cid_tjid_unique'); + } ); } diff --git a/app/database/migrations/2014_07_06_123842_create_preferences_table.php b/app/database/migrations/2014_07_06_123842_create_preferences_table.php index 058c530f2a..61f12090a2 100644 --- a/app/database/migrations/2014_07_06_123842_create_preferences_table.php +++ b/app/database/migrations/2014_07_06_123842_create_preferences_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreatePreferencesTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreatePreferencesTable extends Migration { diff --git a/app/database/migrations/2014_07_09_204843_create_session_table.php b/app/database/migrations/2014_07_09_204843_create_session_table.php index c4423f33cf..3100f7e9b8 100644 --- a/app/database/migrations/2014_07_09_204843_create_session_table.php +++ b/app/database/migrations/2014_07_09_204843_create_session_table.php @@ -5,7 +5,6 @@ use Illuminate\Database\Migrations\Migration; /** * Class CreateSessionTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateSessionTable extends Migration { diff --git a/app/database/migrations/2014_07_17_183717_create_limits_table.php b/app/database/migrations/2014_07_17_183717_create_limits_table.php index fb3dbe3660..fced678780 100644 --- a/app/database/migrations/2014_07_17_183717_create_limits_table.php +++ b/app/database/migrations/2014_07_17_183717_create_limits_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateLimitsTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateLimitsTable extends Migration { diff --git a/app/database/migrations/2014_07_19_055011_create_limit_repeat_table.php b/app/database/migrations/2014_07_19_055011_create_limit_repeat_table.php index e69902a3eb..1240cf3657 100644 --- a/app/database/migrations/2014_07_19_055011_create_limit_repeat_table.php +++ b/app/database/migrations/2014_07_19_055011_create_limit_repeat_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateLimitRepeatTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateLimitRepeatTable extends Migration { diff --git a/app/database/migrations/2014_08_06_044416_create_component_recurring_transaction_table.php b/app/database/migrations/2014_08_06_044416_create_component_recurring_transaction_table.php index e6f25ed2ec..512387e29b 100644 --- a/app/database/migrations/2014_08_06_044416_create_component_recurring_transaction_table.php +++ b/app/database/migrations/2014_08_06_044416_create_component_recurring_transaction_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateComponentRecurringTransactionTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateComponentRecurringTransactionTable extends Migration { @@ -18,7 +17,7 @@ class CreateComponentRecurringTransactionTable extends Migration */ public function down() { - Schema::drop('component_recurring_transaction'); + Schema::dropIfExists('component_recurring_transaction'); } /** @@ -30,21 +29,21 @@ class CreateComponentRecurringTransactionTable extends Migration { Schema::create( 'component_recurring_transaction', function (Blueprint $table) { - $table->increments('id'); - $table->integer('component_id')->unsigned(); - $table->integer('recurring_transaction_id')->unsigned(); - $table->boolean('optional'); + $table->increments('id'); + $table->integer('component_id')->unsigned(); + $table->integer('recurring_transaction_id')->unsigned(); + $table->boolean('optional'); - // link components with component_id - $table->foreign('component_id')->references('id')->on('components')->onDelete('cascade'); + // link components with component_id + $table->foreign('component_id')->references('id')->on('components')->onDelete('cascade'); - // link transaction journals with transaction_journal_id - $table->foreign('recurring_transaction_id')->references('id')->on('recurring_transactions')->onDelete('cascade'); + // link transaction journals with transaction_journal_id + $table->foreign('recurring_transaction_id')->references('id')->on('recurring_transactions')->onDelete('cascade'); - // component and recurring transaction must be unique. - $table->unique(['component_id','recurring_transaction_id'],'cid_rtid_unique'); + // component and recurring transaction must be unique. + $table->unique(['component_id', 'recurring_transaction_id'], 'cid_rtid_unique'); - } + } ); } diff --git a/app/database/migrations/2014_08_12_173919_create_piggybank_repetitions_table.php b/app/database/migrations/2014_08_12_173919_create_piggybank_repetitions_table.php index 5a8fa36282..d285d99487 100644 --- a/app/database/migrations/2014_08_12_173919_create_piggybank_repetitions_table.php +++ b/app/database/migrations/2014_08_12_173919_create_piggybank_repetitions_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreatePiggyInstance * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreatePiggybankRepetitionsTable extends Migration { diff --git a/app/database/migrations/2014_08_18_100330_create_piggybank_events_table.php b/app/database/migrations/2014_08_18_100330_create_piggybank_events_table.php index f598185157..480f09d658 100644 --- a/app/database/migrations/2014_08_18_100330_create_piggybank_events_table.php +++ b/app/database/migrations/2014_08_18_100330_create_piggybank_events_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreatePiggybankEventsTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreatePiggybankEventsTable extends Migration { diff --git a/app/database/migrations/2014_08_23_113221_create_reminders_table.php b/app/database/migrations/2014_08_23_113221_create_reminders_table.php index 7a3cbc0997..8d231aac04 100644 --- a/app/database/migrations/2014_08_23_113221_create_reminders_table.php +++ b/app/database/migrations/2014_08_23_113221_create_reminders_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateRemindersTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateRemindersTable extends Migration { diff --git a/app/database/migrations/2014_11_10_172053_create_account_meta_table.php b/app/database/migrations/2014_11_10_172053_create_account_meta_table.php index e465b7a5eb..0cbc84ae4d 100644 --- a/app/database/migrations/2014_11_10_172053_create_account_meta_table.php +++ b/app/database/migrations/2014_11_10_172053_create_account_meta_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateAccountMetaTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateAccountMetaTable extends Migration { diff --git a/app/database/migrations/2014_11_29_135749_create_transaction_groups_table.php b/app/database/migrations/2014_11_29_135749_create_transaction_groups_table.php index 31dca7cda5..acba3c84ce 100644 --- a/app/database/migrations/2014_11_29_135749_create_transaction_groups_table.php +++ b/app/database/migrations/2014_11_29_135749_create_transaction_groups_table.php @@ -6,7 +6,6 @@ use Illuminate\Database\Schema\Blueprint; /** * Class CreateTransactionGroupsTable * - * @SuppressWarnings(PHPMD.ShortMethodName) */ class CreateTransactionGroupsTable extends Migration { diff --git a/app/database/migrations/2014_12_13_190730_changes_for_v321.php b/app/database/migrations/2014_12_13_190730_changes_for_v321.php new file mode 100644 index 0000000000..7185cde1b8 --- /dev/null +++ b/app/database/migrations/2014_12_13_190730_changes_for_v321.php @@ -0,0 +1,634 @@ +moveBudgetsBack(); // 1. + $this->moveCategoriesBack(); // 2. + $this->createComponentId(); // 3. + $this->updateComponentInBudgetLimits(); // 4. + $this->createComponentIdForeignKey(); // 5. + $this->dropBudgetIdColumnInBudgetLimits(); // 6. + $createComponents = new CreateComponentTransactionJournalTable; // 7. + $createComponents->up(); + $this->moveBackEntriesForBudgetsInJoinedTable(); // 8. + $this->moveBackEntriesForCategoriesInJoinedTable(); // 9. + $this->dropBudgetJournalTable(); // 10. + $this->dropCategoryJournalTable(); // 11. + $this->dropBudgetTable(); // 12. + $this->dropCategoryTable(); // 13. + $this->renameBudgetLimits(); // 14. + $this->renamePiggyBankEvents(); // 15. + $this->renameBudgetLimitToBudgetInRepetitions(); // 16. + // 17, 18, 19 + $this->dropFieldsFromCurrencyTable(); // 20. + + + } + + public function moveBudgetsBack() + { + Budget::get()->each( + function (Budget $budget) { + Component::firstOrCreate( + [ + 'name' => $budget->name, + 'user_id' => $budget->user_id, + 'class' => 'Budget' + ] + ); + } + ); + } + + public function moveCategoriesBack() + { + Category::get()->each( + function (Category $category) { + Component::firstOrCreate( + [ + 'name' => $category->name, + 'user_id' => $category->user_id, + 'class' => 'Category' + ] + ); + } + ); + } + + public function createComponentId() + { + Schema::table( + 'budget_limits', function (Blueprint $table) { + $table->integer('component_id')->unsigned(); + } + ); + } + + public function updateComponentInBudgetLimits() + { + BudgetLimit::get()->each( + function (BudgetLimit $bl) { + $budgetId = $bl->budget_id; + $budget = Budget::find($budgetId); + if ($budget) { + $component = Component::where('class', 'Budget')->where('user_id', $budget->user_id)->where('name', $budget->name)->first(); + if ($component) { + $bl->component_id = $component->id; + $bl->save(); + } + } + } + ); + } + + public function createComponentIdForeignKey() + { + Schema::table( + 'budget_limits', function (Blueprint $table) { + $table->foreign('component_id', 'limits_component_id_foreign')->references('id')->on('components')->onDelete('cascade'); + } + ); + } + + public function dropBudgetIdColumnInBudgetLimits() + { + Schema::table( + 'budget_limits', function (Blueprint $table) { + $table->dropForeign('bid_foreign'); + $table->dropColumn('budget_id'); // also drop foreign key! + } + ); + } + + public function moveBackEntriesForBudgetsInJoinedTable() + { + $set = DB::table('budget_transaction_journal')->get(); + foreach ($set as $entry) { + $budget = Budget::find($entry->budget_id); + if ($budget) { + $component = Component::where('class', 'Budget')->where('name', $budget->name)->where('user_id', $budget->user_id)->first(); + if ($component) { + DB::table('component_transaction_journal')->insert( + [ + 'component_id' => $component->id, + 'transaction_journal_id' => $entry->transaction_journal_id + ] + ); + } + + } + } + + } + + public function moveBackEntriesForCategoriesInJoinedTable() + { + $set = DB::table('category_transaction_journal')->get(); + foreach ($set as $entry) { + $category = Category::find($entry->category_id); + if ($category) { + $component = Component::where('class', 'Category')->where('name', $category->name)->where('user_id', $category->user_id)->first(); + if ($component) { + DB::table('component_transaction_journal')->insert( + [ + 'component_id' => $component->id, + 'transaction_journal_id' => $entry->transaction_journal_id + ] + ); + } + + } + } + + } + + public function dropBudgetJournalTable() + { + Schema::dropIfExists('budget_transaction_journal'); + } + + public function dropCategoryJournalTable() + { + Schema::dropIfExists('category_transaction_journal'); + } + + public function dropBudgetTable() + { + Schema::dropIfExists('budgets'); + } + + public function dropCategoryTable() + { + Schema::dropIfExists('categories'); + } + + public function renameBudgetLimits() + { + Schema::rename('budget_limits', 'limits'); + } + + public function renamePiggyBankEvents() + { + Schema::rename('piggy_bank_events', 'piggybank_events'); + + } + + public function renameBudgetLimitToBudgetInRepetitions() + { + Schema::table( + 'limit_repetitions', function (Blueprint $table) { + $table->renameColumn('budget_limit_id', 'limit_id'); + } + ); + } + + public function dropFieldsFromCurrencyTable() + { + + Schema::table( + 'transaction_currencies', function (Blueprint $table) { + $table->dropColumn('symbol'); + $table->dropColumn('name'); + } + ); + } + + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + $this->createBudgetTable(); // 1. + $this->createCategoryTable(); // 2. + $this->createBudgetJournalTable(); // 3 + $this->createCategoryJournalTable(); // 4. + $this->moveBudgets(); // 5. + $this->moveCategories(); // 6. + $this->correctNameForBudgetLimits(); // 7. + $this->correctNameForPiggyBankEvents(); // 8. + $this->renameBudgetToBudgetLimitInRepetitions(); // 9. + $this->addBudgetIdFieldToBudgetLimits(); // 10. + $this->moveComponentIdToBudgetId(); // 11. + $this->dropComponentJournalTable(); // 12. + $this->dropComponentRecurringTransactionTable(); // 13. + $this->dropComponentTransactionTable(); // 14. + $this->dropPiggyBankIdFromTransactions(); // 15. + $this->dropComponentIdFromBudgetLimits(); // 16. + $this->expandCurrencyTable(); // 17. + + + // $this->doRenameInLimitRepetitions(); + // $this->doBudgetLimits(); + // $this->doPiggyBankEvents(); + // $this->doCreateCategoryTables(); + // $this->doUpdateTransactionTable(); + // $this->doDropCompRecurTable(); + // $this->doDropCompTransTable(); + // $this->doMoveBudgets(); + // $this->doMoveCategories(); + // $this->doMoveLimitReferences(); + + + } + + public function createBudgetTable() + { + Schema::create( + 'budgets', function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->string('name', 50); + $table->integer('user_id')->unsigned(); + $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + $table->unique(['user_id', 'name']); + } + ); + + + } + + public function createCategoryTable() + { + Schema::create( + 'categories', function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->string('name', 50); + $table->integer('user_id')->unsigned(); + $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + $table->unique(['user_id', 'name']); + } + ); + } + + public function createBudgetJournalTable() + { + Schema::create( + 'budget_transaction_journal', function (Blueprint $table) { + $table->increments('id'); + $table->integer('budget_id')->unsigned(); + $table->integer('transaction_journal_id')->unsigned(); + $table->foreign('budget_id')->references('id')->on('budgets')->onDelete('cascade'); + $table->foreign('transaction_journal_id')->references('id')->on('transaction_journals')->onDelete('cascade'); + $table->unique(['budget_id', 'transaction_journal_id'], 'budid_tjid_unique'); + } + ); + } + + public function createCategoryJournalTable() + { + Schema::create( + 'category_transaction_journal', function (Blueprint $table) { + $table->increments('id'); + $table->integer('category_id')->unsigned(); + $table->integer('transaction_journal_id')->unsigned(); + $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); + $table->foreign('transaction_journal_id')->references('id')->on('transaction_journals')->onDelete('cascade'); + $table->unique(['category_id', 'transaction_journal_id'], 'catid_tjid_unique'); + } + ); + } + + public function moveBudgets() + { + Component::where('class', 'Budget')->get()->each( + function (Component $c) { + $entry = [ + 'user_id' => $c->user_id, + 'name' => $c->name + + ]; + $budget = Budget::firstOrCreate($entry); + Log::debug('Migrated budget #' . $budget->id . ': ' . $budget->name); + // create entry in budget_transaction_journal + $connections = DB::table('component_transaction_journal')->where('component_id', $c->id)->get(); + foreach ($connections as $connection) { + DB::table('budget_transaction_journal')->insert( + [ + 'budget_id' => $budget->id, + 'transaction_journal_id' => $connection->transaction_journal_id + ] + ); + } + } + ); + } + + public function moveCategories() + { + Component::where('class', 'Category')->get()->each( + function (Component $c) { + $entry = [ + 'user_id' => $c->user_id, + 'name' => $c->name + + ]; + $category = Category::firstOrCreate($entry); + Log::debug('Migrated category #' . $category->id . ': ' . $category->name); + // create entry in category_transaction_journal + $connections = DB::table('component_transaction_journal')->where('component_id', $c->id)->get(); + foreach ($connections as $connection) { + DB::table('category_transaction_journal')->insert( + [ + 'category_id' => $category->id, + 'transaction_journal_id' => $connection->transaction_journal_id + ] + ); + } + } + ); + } + + public function correctNameForBudgetLimits() + { + Schema::rename('limits', 'budget_limits'); + } + + public function correctNameForPiggyBankEvents() + { + Schema::rename('piggybank_events', 'piggy_bank_events'); + + } + + public function renameBudgetToBudgetLimitInRepetitions() + { + Schema::table( + 'limit_repetitions', function (Blueprint $table) { + $table->renameColumn('limit_id', 'budget_limit_id'); + } + ); + } + + public function addBudgetIdFieldToBudgetLimits() + { + Schema::table( + 'budget_limits', function (Blueprint $table) { + $table->integer('budget_id', false, true)->nullable()->after('updated_at'); + $table->foreign('budget_id', 'bid_foreign')->references('id')->on('budgets')->onDelete('cascade'); + } + ); + } + + public function moveComponentIdToBudgetId() + { + \Log::debug('Now in moveComponentIdToBudgetId()'); + BudgetLimit::get()->each( + function (BudgetLimit $bl) { + \Log::debug('Now at budgetLimit #' . $bl->id . ' with component_id: ' . $bl->component_id); + $component = Component::find($bl->component_id); + if ($component) { + \Log::debug('Found component with id #' . $component->id . ' and name ' . $component->name); + $budget = Budget::whereName($component->name)->whereUserId($component->user_id)->first(); + if ($budget) { + \Log::debug('Found a budget with ID #' . $budget->id . ' and name ' . $budget->name); + $bl->budget_id = $budget->id; + $bl->save(); + \Log::debug('Connected budgetLimit #' . $bl->id . ' to budget_id' . $budget->id); + } else { + \Log::debug('Could not find a matching budget with name ' . $component->name); + } + } else { + \Log::debug('Could not find a component with id ' . $bl->component_id); + } + } + ); + \Log::debug('Done with moveComponentIdToBudgetId()'); + + } + + public function dropComponentJournalTable() + { + Schema::dropIfExists('component_transaction_journal'); + } + + public function dropComponentRecurringTransactionTable() + { + Schema::dropIfExists('component_recurring_transaction'); + } + + public function dropComponentTransactionTable() + { + Schema::dropIfExists('component_transaction'); + } + + public function dropPiggyBankIdFromTransactions() + { + + Schema::table( + 'transactions', function (Blueprint $table) { + if (Schema::hasColumn('transactions', 'piggybank_id')) { + $table->dropForeign('transactions_piggybank_id_foreign'); + $table->dropColumn('piggybank_id'); + } + } + ); + } + + public function dropComponentIdFromBudgetLimits() + { + Schema::table( + 'budget_limits', function (Blueprint $table) { + $table->dropForeign('limits_component_id_foreign'); + $table->dropColumn('component_id'); + } + ); + } + + public function expandCurrencyTable() + { + Schema::table( + 'transaction_currencies', function (Blueprint $table) { + $table->string('name', 48)->nullable(); + $table->string('symbol', 8)->nullable(); + } + ); + \DB::update('UPDATE `transaction_currencies` SET `symbol` = "€", `name` = "Euro" WHERE `code` = "EUR";'); + } + + // + // public function doRenameInLimitRepetitions() + // { + // Schema::table( + // 'limit_repetitions', function (Blueprint $table) { + // $table->renameColumn('limit_id', 'budget_limit_id'); + // } + // ); + // } + // + // public function doBudgetLimits() + // { + // Schema::rename('limits', 'budget_limits'); + // Schema::table( + // 'budget_limits', function (Blueprint $table) { + // $table->integer('budget_id')->unsigned()->after('updated_at'); + // $table->foreign('budget_id', 'bid_foreign')->references('id')->on('budgets')->onDelete('cascade'); + // } + // ); + // } + // + // public function doPiggyBankEvents() + // { + // Schema::rename('piggybank_events', 'piggy_bank_events'); + // + // } + // + // public function doCreateCategoryTables() + // { + // Schema::create( + // 'categories', function (Blueprint $table) { + // $table->increments('id'); + // $table->timestamps(); + // $table->softDeletes(); + // $table->string('name', 50); + // $table->integer('user_id')->unsigned(); + // $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + // $table->unique(['user_id', 'name']); + // } + // ); + // Schema::create( + // 'category_transaction_journal', function (Blueprint $table) { + // $table->increments('id'); + // $table->integer('category_id')->unsigned(); + // $table->integer('transaction_journal_id')->unsigned(); + // $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); + // $table->foreign('transaction_journal_id')->references('id')->on('transaction_journals')->onDelete('cascade'); + // $table->unique(['category_id', 'transaction_journal_id'], 'catid_tjid_unique'); + // } + // ); + // + // } + // + // public function doUpdateTransactionTable() + // { + // Schema::table( + // 'transactions', function (Blueprint $table) { + // $table->dropForeign('transactions_piggybank_id_foreign'); + // #$table->dropIndex('transactions_piggybank_id_foreign'); + // $table->dropColumn('piggybank_id'); + // } + // ); + // } + // + // public function doDropCompRecurTable() + // { + // Schema::drop('component_recurring_transaction'); + // } + // + // public function doDropCompTransTable() + // { + // Schema::drop('component_transaction'); + // } + // + // public function doMoveBudgets() + // { + // Component::where('class', 'Budget')->get()->each( + // function (Component $c) { + // $entry = [ + // 'user_id' => $c->user_id, + // 'name' => $c->name + // + // ]; + // $budget = Budget::firstOrCreate($entry); + // Log::debug('Migrated budget #' . $budget->id . ': ' . $budget->name); + // // create entry in budget_transaction_journal + // $connections = DB::table('component_transaction_journal')->where('component_id', $c->id)->get(); + // foreach ($connections as $connection) { + // DB::table('budget_transaction_journal')->insert( + // [ + // 'budget_id' => $budget->id, + // 'transaction_journal_id' => $connection->transaction_journal_id + // ] + // ); + // } + // } + // ); + // } + // + // public function doMoveCategories() + // { + // Component::where('class', 'Category')->get()->each( + // function (Component $c) { + // $entry = [ + // 'user_id' => $c->user_id, + // 'name' => $c->name + // + // ]; + // $category = Category::firstOrCreate($entry); + // Log::debug('Migrated category #' . $category->id . ': ' . $category->name); + // // create entry in category_transaction_journal + // $connections = DB::table('component_transaction_journal')->where('component_id', $c->id)->get(); + // foreach ($connections as $connection) { + // DB::table('category_transaction_journal')->insert( + // [ + // 'category_id' => $category->id, + // 'transaction_journal_id' => $connection->transaction_journal_id + // ] + // ); + // } + // } + // ); + // } + // + // public function doMoveLimitReferences() + // { + // throw new \FireflyIII\Exception\FireflyException('TODO'); + // } + +} diff --git a/app/database/production.sqlite b/app/database/production.sqlite deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/app/database/seeds/DefaultUserSeeder.php b/app/database/seeds/DefaultUserSeeder.php index 0e4c292529..4198ae4134 100644 --- a/app/database/seeds/DefaultUserSeeder.php +++ b/app/database/seeds/DefaultUserSeeder.php @@ -8,17 +8,11 @@ class DefaultUserSeeder extends Seeder public function run() { DB::table('users')->delete(); - if (App::environment() == 'testing') { + if (App::environment() == 'testing' || App::environment() == 'homestead') { - User::create( - ['email' => 'thegrumpydictator@gmail.com', 'password' => 'james', 'reset' => null, 'remember_token' => null, 'migrated' => 0] - ); - User::create( - ['email' => 'acceptance@example.com', 'password' => 'acceptance', 'reset' => null, 'remember_token' => null, 'migrated' => 0] - ); - User::create( - ['email' => 'functional@example.com', 'password' => 'functional', 'reset' => null, 'remember_token' => null, 'migrated' => 0] - ); + User::create(['email' => 'thegrumpydictator@gmail.com', 'password' => 'james', 'reset' => null, 'remember_token' => null]); + User::create(['email' => 'acceptance@example.com', 'password' => 'acceptance', 'reset' => null, 'remember_token' => null]); + User::create(['email' => 'functional@example.com', 'password' => 'functional', 'reset' => null, 'remember_token' => null]); } } diff --git a/app/database/seeds/TestContentSeeder.php b/app/database/seeds/TestContentSeeder.php index 202b8ebd11..dabac9f474 100644 --- a/app/database/seeds/TestContentSeeder.php +++ b/app/database/seeds/TestContentSeeder.php @@ -2,20 +2,21 @@ use Carbon\Carbon; +/** + * Class TestContentSeeder + */ class TestContentSeeder extends Seeder { public function run() { - if (App::environment() == 'testing') { + if (App::environment() == 'testing' || App::environment() == 'homestead') { $assetType = AccountType::whereType('Asset account')->first(); $expenseType = AccountType::whereType('Expense account')->first(); $revenueType = AccountType::whereType('Revenue account')->first(); $ibType = AccountType::whereType('Initial balance account')->first(); - $euro = TransactionCurrency::whereCode('EUR')->first(); - $obType = TransactionType::whereType('Opening balance')->first(); $withdrawal = TransactionType::whereType('Withdrawal')->first(); $transfer = TransactionType::whereType('Transfer')->first(); @@ -27,18 +28,147 @@ class TestContentSeeder extends Seeder // create two asset accounts. $checking = Account::create(['user_id' => $user->id, 'account_type_id' => $assetType->id, 'name' => 'Checking account', 'active' => 1]); $savings = Account::create(['user_id' => $user->id, 'account_type_id' => $assetType->id, 'name' => 'Savings account', 'active' => 1]); + Account::create(['user_id' => $user->id, 'account_type_id' => $assetType->id, 'name' => 'Delete me', 'active' => 1]); // create two budgets: $groceriesBudget = Budget::create(['user_id' => $user->id, 'name' => 'Groceries']); $billsBudget = Budget::create(['user_id' => $user->id, 'name' => 'Bills']); + $deleteBudget = Budget::create(['user_id' => $user->id, 'name' => 'Delete me']); + + // some limits: + $startDate = Carbon::now()->startOfMonth(); + $endDate = Carbon::now()->endOfMonth(); + $secondStart = Carbon::now()->subMonth()->startOfMonth(); + $secondEnd = Carbon::now()->subMonth()->endOfMonth(); + $limitOne = BudgetLimit::create( + ['startdate' => $startDate->format('Y-m-d'), 'amount' => 201, 'repeats' => 0, 'repeat_freq' => 'monthly', + 'budget_id' => $groceriesBudget->id] + ); + $limitTwo = BudgetLimit::create( + ['startdate' => $secondStart->format('Y-m-d'), 'amount' => 202, 'repeats' => 0, 'repeat_freq' => 'monthly', + 'budget_id' => $billsBudget->id] + ); + $limitThree = BudgetLimit::create( + ['startdate' => '2014-01-01', 'amount' => 203, 'repeats' => 0, 'repeat_freq' => 'monthly', + 'budget_id' => $deleteBudget->id] + ); + + // and because we have no filters, some repetitions: + $repOne = LimitRepetition::create( + ['budget_limit_id' => $limitOne->id, 'startdate' => $startDate->format('Y-m-d'), 'enddate' => $endDate->format('Y-m-d'), 'amount' => 201] + ); + $repTwo = LimitRepetition::create( + ['budget_limit_id' => $limitTwo->id, 'startdate' => $secondStart->format('Y-m-d'), 'enddate' => $secondEnd->format('Y-m-d'), 'amount' => 202] + ); + $repThree = LimitRepetition::create( + ['budget_limit_id' => $limitThree->id, 'startdate' => '2014-01-01', 'enddate' => '2014-01-31', 'amount' => 203] + ); // create two categories: - $dailyGroceries = Category::create(['user_id' => $user->id, 'name' => 'Daily groceries']); + $dailyGroceries = Category::create(['user_id' => $user->id, 'name' => 'DailyGroceries']); $lunch = Category::create(['user_id' => $user->id, 'name' => 'Lunch']); $house = Category::create(['user_id' => $user->id, 'name' => 'House']); + $deleteMe = Category::create(['user_id' => $user->id, 'name' => 'Delete me']); + + Component::create(['user_id' => $user->id, 'name' => 'Some Component 1', 'class' => 'Budget']); + Component::create(['user_id' => $user->id, 'name' => 'Some Component 2', 'class' => 'Budget']); + Component::create(['user_id' => $user->id, 'name' => 'Some Component 3', 'class' => 'Budget']); + Component::create(['user_id' => $user->id, 'name' => 'Some Component 4', 'class' => 'Category']); + Component::create(['user_id' => $user->id, 'name' => 'Some Component 5', 'class' => 'Category']); + Component::create(['user_id' => $user->id, 'name' => 'Some Component 6', 'class' => 'Category']); + Component::create(['user_id' => $user->id, 'name' => 'Some Component 7', 'class' => 'Category']); + + // piggy bank + $piggy = Piggybank::create( + [ + 'account_id' => $savings->id, + 'name' => 'New camera', + 'targetamount' => 2000, + 'startdate' => Carbon::now()->format('Y-m-d'), + 'targetdate' => null, + 'repeats' => 0, + 'rep_length' => null, + 'rep_every' => 0, + 'rep_times' => null, + 'reminder' => null, + 'reminder_skip' => 0, + 'remind_me' => 0, + 'order' => 0, + ] + ); + PiggyBankEvent::create(['piggybank_id' => 1, 'date' => $startDate->format('Y-m-d'), 'amount' => 100]); + PiggybankRepetition::create( + [ + 'piggybank_id' => $piggy->id, + 'startdate' => Carbon::now()->format('Y-m-d'), + 'targetdate' => null, + 'currentamount' => 0 + ] + ); + + // piggy bank + $piggyTargeted = Piggybank::create( + [ + 'account_id' => $savings->id, + 'name' => 'New clothes', + 'targetamount' => 2000, + 'startdate' => Carbon::now()->format('Y-m-d'), + 'targetdate' => Carbon::now()->addMonths(4)->format('Y-m-d'), + 'repeats' => 0, + 'rep_length' => null, + 'rep_every' => 0, + 'rep_times' => null, + 'reminder' => null, + 'reminder_skip' => 0, + 'remind_me' => 0, + 'order' => 0, + ] + ); + + PiggyBankEvent::create(['piggybank_id' => $piggyTargeted->id, 'date' => $startDate->format('Y-m-d'), 'amount' => 100]); + PiggybankRepetition::create( + [ + 'piggybank_id' => $piggyTargeted->id, + 'startdate' => Carbon::now()->format('Y-m-d'), + 'targetdate' => Carbon::now()->addMonths(4)->format('Y-m-d'), + 'currentamount' => 0 + ] + ); + + // recurring transaction + $recurring = \RecurringTransaction::create( + [ + 'user_id' => $user->id, + 'name' => 'Huur', + 'match' => 'huur,portaal', + 'amount_min' => 500, + 'amount_max' => 700, + 'date' => '2014-01-12', + 'active' => 1, + 'automatch' => 1, + 'repeat_freq' => 'monthly', + 'skip' => 0, + ] + ); + + // recurring transaction + $secondRecurring = \RecurringTransaction::create( + [ + 'user_id' => $user->id, + 'name' => 'Gas licht', + 'match' => 'no,match', + 'amount_min' => 500, + 'amount_max' => 700, + 'date' => '2014-01-12', + 'active' => 1, + 'automatch' => 1, + 'repeat_freq' => 'monthly', + 'skip' => 0, + ] + ); // create some expense accounts. - $ah = Account::create(['user_id' => $user->id, 'account_type_id' => $expenseType->id, 'name' => 'Albert Heijn', 'active' => 1]); + $albert = Account::create(['user_id' => $user->id, 'account_type_id' => $expenseType->id, 'name' => 'Albert Heijn', 'active' => 1]); $plus = Account::create(['user_id' => $user->id, 'account_type_id' => $expenseType->id, 'name' => 'PLUS', 'active' => 1]); $vitens = Account::create(['user_id' => $user->id, 'account_type_id' => $expenseType->id, 'name' => 'Vitens', 'active' => 1]); $greenchoice = Account::create(['user_id' => $user->id, 'account_type_id' => $expenseType->id, 'name' => 'Greenchoice', 'active' => 1]); @@ -48,7 +178,7 @@ class TestContentSeeder extends Seeder // create three revenue accounts. $employer = Account::create(['user_id' => $user->id, 'account_type_id' => $revenueType->id, 'name' => 'Employer', 'active' => 1]); $taxes = Account::create(['user_id' => $user->id, 'account_type_id' => $revenueType->id, 'name' => 'IRS', 'active' => 1]); - $job = Account::create(['user_id' => $user->id, 'account_type_id' => $revenueType->id, 'name' => 'Job', 'active' => 1]); + Account::create(['user_id' => $user->id, 'account_type_id' => $revenueType->id, 'name' => 'Job', 'active' => 1]); // put money in the two accounts (initial balance) $ibChecking = Account::create( @@ -64,10 +194,11 @@ class TestContentSeeder extends Seeder // create some expenses and incomes and what-not (for every month): $start = new Carbon('2014-01-01'); - $end = Carbon::now()->startOfMonth()->subDay(); + $end = Carbon::now()->endOfMonth()->addDay(); while ($start <= $end) { $this->createTransaction( - $checking, $portaal, 500, $withdrawal, 'Rent for ' . $start->format('F Y'), $start->format('Y-m-') . '01', $billsBudget, $house + $checking, $portaal, 500, $withdrawal, 'Huur Portaal for ' . $start->format('F Y'), $start->format('Y-m-') . '01', $billsBudget, $house, + $recurring ); $this->createTransaction( $checking, $vitens, 12, $withdrawal, 'Water for ' . $start->format('F Y'), $start->format('Y-m-') . '02', $billsBudget, $house @@ -87,7 +218,7 @@ class TestContentSeeder extends Seeder $groceriesStart->addDay(); if (intval($groceriesStart->format('d')) % 2 == 0) { $this->createTransaction( - $checking, $ah, $amt, $withdrawal, 'Groceries', $groceriesStart->format('Y-m-d'), $groceriesBudget, $dailyGroceries + $checking, $albert, $amt, $withdrawal, 'Groceries', $groceriesStart->format('Y-m-d'), $groceriesBudget, $dailyGroceries ); } $groceriesStart->addDay(); @@ -121,30 +252,37 @@ class TestContentSeeder extends Seeder } /** - * @param Account $from - * @param Account $to - * @param $amount - * @param TransactionType $type - * @param $description - * @param $date + * @param Account $from + * @param Account $to + * @param $amount + * @param TransactionType $type + * @param $description + * @param $date + * + * @param Budget $budget + * @param Category $category + * @param RecurringTransaction $recurring * * @return TransactionJournal */ public function createTransaction( - Account $from, Account $to, $amount, TransactionType $type, $description, $date, Budget $budget = null, Category $category = null + Account $from, Account $to, $amount, TransactionType $type, $description, $date, Budget $budget = null, Category $category = null, + $recurring = null ) { - $user = User::whereEmail('thegrumpydictator@gmail.com')->first(); - $euro = TransactionCurrency::whereCode('EUR')->first(); + $user = User::whereEmail('thegrumpydictator@gmail.com')->first(); + $euro = TransactionCurrency::whereCode('EUR')->first(); + $recurringID = is_null($recurring) ? null : $recurring->id; /** @var TransactionJournal $journal */ $journal = TransactionJournal::create( [ - 'user_id' => $user->id, - 'transaction_type_id' => $type->id, - 'transaction_currency_id' => $euro->id, - 'description' => $description, - 'completed' => 1, - 'date' => $date + 'user_id' => $user->id, + 'transaction_type_id' => $type->id, + 'transaction_currency_id' => $euro->id, + 'recurring_transaction_id' => $recurringID, + 'description' => $description, + 'completed' => 1, + 'date' => $date ] ); @@ -154,7 +292,6 @@ class TestContentSeeder extends Seeder 'transaction_journal_id' => $journal->id, 'amount' => $amount * -1 ] - ); Transaction::create( [ @@ -162,7 +299,6 @@ class TestContentSeeder extends Seeder 'transaction_journal_id' => $journal->id, 'amount' => $amount ] - ); if (!is_null($budget)) { $journal->budgets()->save($budget); diff --git a/app/database/seeds/TransactionCurrencySeeder.php b/app/database/seeds/TransactionCurrencySeeder.php index 46a08f74fb..20f50e9f60 100644 --- a/app/database/seeds/TransactionCurrencySeeder.php +++ b/app/database/seeds/TransactionCurrencySeeder.php @@ -10,9 +10,8 @@ class TransactionCurrencySeeder extends Seeder { DB::table('transaction_currencies')->delete(); - TransactionCurrency::create( - ['code' => 'EUR'] - ); + TransactionCurrency::create(['code' => 'EUR','name' => 'Euro','symbol' => '€']); + TransactionCurrency::create(['code' => 'USD','name' => 'US Dollar','symbol' => '$']); } } \ No newline at end of file diff --git a/app/filters.php b/app/filters.php index a55467f0e3..8a73c6b6da 100644 --- a/app/filters.php +++ b/app/filters.php @@ -4,11 +4,15 @@ App::before( function ($request) { + + // put IP in session if not already there. + $reminders = []; if (Auth::check()) { Filter::setSessionDateRange(); Reminders::updateReminders(); + Steam::removeEmptyBudgetLimits(); $reminders = Reminders::getReminders(); } View::share('reminders', $reminders); diff --git a/app/lib/Firefly/Database/SingleTableInheritanceEntity.php b/app/lib/Firefly/Database/SingleTableInheritanceEntity.php deleted file mode 100644 index 762ee14ad6..0000000000 --- a/app/lib/Firefly/Database/SingleTableInheritanceEntity.php +++ /dev/null @@ -1,121 +0,0 @@ -mapData((array)$attributes)->newInstance([], true); - $instance->setRawAttributes((array)$attributes, true); - - return $instance; - } - - - /** - * if no subclass is defined, function as normal - * - * @param array $attributes - * - * @return \Illuminate\Database\Eloquent\Model|static - */ - public function mapData(array $attributes) - { - if (!$this->subclassField) { - return $this->newInstance(); - } - - return new $attributes[$this->subclassField]; - } - - - /** - * - * instead of using $this->newInstance(), call - * newInstance() on the object from mapData - * - * @param bool $excludeDeleted - * - * @return \Illuminate\Database\Eloquent\Builder|static - */ - public function newQuery($excludeDeleted = true) - { - // If using Laravel 4.0.x then use the following commented version of this command - // $builder = new Builder($this->newBaseQueryBuilder()); - // newEloquentBuilder() was added in 4.1 - $builder = $this->newEloquentBuilder($this->newBaseQueryBuilder()); - - // Once Firefly has the query builders, it will set the model instances so the - // builder can easily access any information it may need from the model - // while it is constructing and executing various queries against it. - $builder->setModel($this)->with($this->with); - - if ($excludeDeleted && $this->softDelete) { - $builder->whereNull($this->getQualifiedDeletedAtColumn()); - } - - if ($this->subclassField && $this->isSubclass()) { - $builder->where($this->subclassField, '=', get_class($this)); - } - - return $builder; - } - - /** - * @return bool - */ - public function isSubclass() - { - return $this->isSubclass; - } - - /** - * ensure that the subclass field is assigned on save - * - * @param array $rules - * @param array $customMessages - * @param array $options - * @param callable $beforeSave - * @param callable $afterSave - * - * @return bool - */ - public function save( - array $rules = [], - array $customMessages = [], - array $options = [], - \Closure $beforeSave = null, - \Closure $afterSave = null - ) { - if ($this->subclassField) { - $this->attributes[$this->subclassField] = get_class($this); - } - - return parent::save($rules, $customMessages, $options, $beforeSave, $afterSave); - } -} \ No newline at end of file diff --git a/app/lib/Firefly/Exception/FireflyException.php b/app/lib/Firefly/Exception/FireflyException.php deleted file mode 100644 index eb0f038fa3..0000000000 --- a/app/lib/Firefly/Exception/FireflyException.php +++ /dev/null @@ -1,14 +0,0 @@ - 'Amount (min)', - 'amount_max' => 'Amount (max)', - 'match' => 'Matches on', - 'repeat_freq' => 'Repetition', - 'account_from_id' => 'Account from', - 'account_to_id' => 'Account to', - 'account_id' => 'Asset account' - ]; - - return isset($labels[$name]) ? $labels[$name] : str_replace('_', ' ', ucfirst($name)); - - } - - /** - * Return buttons for update/validate/return. - * - * @param $type - * @param $name - */ - public static function ffOptionsList($type, $name) - { - $previousValue = \Input::old('post_submit_action'); - $previousValue = is_null($previousValue) ? 'store' : $previousValue; - /* - * Store. - */ - $store = ''; - switch ($type) { - case 'create': - $store = '' . e($errors->first($name)) . '
'; - } - } - unset($errors); - /* - * If warnings, respond to them: - */ - - if (!is_null($warnings)) { - if ($warnings->has($name)) { - $html .= ''; - $html .= '' . e($warnings->first($name)) . '
'; - } - } - unset($warnings); - - /* - * If successes, respond to them: - */ - - if (!is_null($successes)) { - if ($successes->has($name)) { - $html .= ''; - $html .= '' . e($successes->first($name)) . '
'; - } - } - unset($successes); - - $html .= '