Cleaned up a lot of source, finished the ChartController. [skip ci]

This commit is contained in:
James Cole
2014-07-29 19:37:52 +02:00
parent 9054b20700
commit 9af2b47463
20 changed files with 450 additions and 347 deletions

View File

@@ -1,6 +1,7 @@
<?php <?php
use Firefly\Helper\Controllers\ChartInterface; use Firefly\Helper\Controllers\ChartInterface;
use Firefly\Storage\Account\AccountRepositoryInterface;
/** /**
* Class ChartController * Class ChartController
@@ -9,29 +10,58 @@ class ChartController extends BaseController
{ {
protected $_chart; protected $_chart;
protected $_accounts;
/** /**
* @param ChartInterface $chart * @param ChartInterface $chart
*/ */
public function __construct(ChartInterface $chart) public function __construct(ChartInterface $chart, AccountRepositoryInterface $accounts)
{ {
$this->_chart = $chart; $this->_chart = $chart;
$this->_accounts = $accounts;
} }
/** /**
* @param Account $account * @param Account $account
*
* @return mixed * @return mixed
*/ */
public function homeAccount(Account $account = null) public function homeAccount(Account $account = null)
{ {
// get preferences and accounts (if necessary):
$data = [];
$start = Session::get('start');
$end = Session::get('end');
if (is_null($account)) {
// get, depending on preferences:
/** @var \Firefly\Helper\Preferences\PreferencesHelperInterface $prefs */
$prefs = \App::make('Firefly\Helper\Preferences\PreferencesHelperInterface');
$pref = $prefs->get('frontpageAccounts', []);
if (!is_null($account)) { /** @var \Firefly\Storage\Account\AccountRepositoryInterface $acct */
$data = $this->_chart->account($account); $acct = \App::make('Firefly\Storage\Account\AccountRepositoryInterface');
$accounts = $acct->getByIds($pref->data);
} else { } else {
$data = $this->_chart->accounts(); $accounts = [$account];
} }
// loop and get array data.
$url = count($accounts) == 1
? '<a href="' . route('accounts.show', [$account->id]) . '">View more</a>'
:
'<a href="' . route('accounts.index') . '">View more</a>';
$data = [
'chart_title' => count($accounts) == 1 ? $accounts[0]->name : 'All accounts',
'subtitle' => $url,
'series' => []
];
foreach ($accounts as $account) {
$data['series'][] = $this->_chart->account($account, $start, $end);
}
return Response::json($data); return Response::json($data);
} }
@@ -47,120 +77,38 @@ class ChartController extends BaseController
*/ */
public function homeAccountInfo($name, $day, $month, $year) public function homeAccountInfo($name, $day, $month, $year)
{ {
$account = $this->_accounts->findByName($name); $account = $this->_accounts->findByName($name);
$result = []; $date = Carbon::createFromDate($year, $month, $day);
$sum = 0;
if ($account) { if ($account) {
$date = \Carbon\Carbon::createFromDate($year, $month, $day); $result = $this->_chart->accountDailySummary($account, $date);
$journals = $this->_journals->getByAccountAndDate($account, $date);
// loop all journals:
foreach ($journals as $journal) {
foreach ($journal->transactions as $transaction) {
$name = $transaction->account->name;
if ($transaction->account->id != $account->id) {
$result[$name] = isset($result[$name]) ? $result[$name] + floatval($transaction->amount)
: floatval($transaction->amount);
$sum += floatval($transaction->amount);
}
}
}
}
return View::make('charts.info')->with('rows', $result)->with('sum', $sum); return View::make('charts.info')->with('rows', $result['rows'])->with('sum', $result['sum']);
} else {
return View::make('error')->with('message', 'No account!');
}
} }
/** /**
* @return \Illuminate\Http\JsonResponse * @return \Illuminate\Http\JsonResponse
* @throws Firefly\Exception\FireflyException
*/
public function homeCategories()
{
list($start, $end) = $this->_tk->getDateRangeDates();
$result = [];
// grab all transaction journals in this period:
$journals = $this->_journals->getByDateRange($start, $end);
foreach ($journals as $journal) {
// has to be one:
if (!isset($journal->transactions[0])) {
throw new FireflyException('Journal #' . $journal->id . ' has ' . count($journal->transactions)
. ' transactions!');
}
$transaction = $journal->transactions[0];
$amount = floatval($transaction->amount);
// get budget from journal:
$budget = $journal->categories()->first();
$budgetName = is_null($budget) ? '(no category)' : $budget->name;
$result[$budgetName] = isset($result[$budgetName]) ? $result[$budgetName] + floatval($amount) : $amount;
}
unset($journal, $transaction, $budget, $amount);
// sort
arsort($result);
$chartData = [
];
foreach ($result as $name => $value) {
$chartData[] = [$name, $value];
}
return Response::json($chartData);
}
/**
* @return \Illuminate\Http\JsonResponse
* @throws Firefly\Exception\FireflyException
*/ */
public function homeBudgets() public function homeBudgets()
{ {
// grab all budgets in the time period, like the index does: $start = \Session::get('start');
// get the budgets for this period:
$data = [];
list($start) = $this->_tk->getDateRangeDates(); return Response::json($this->_chart->budgets($start));
$budgets = $this->_budgets->getWithRepetitionsInPeriod($start, \Session::get('range')); }
$repeatFreq = Config::get('firefly.range_to_repeat_freq.' . Session::get('range')); /**
* @return \Illuminate\Http\JsonResponse
*/
public function homeCategories()
{
$start = Session::get('start');
$end = Session::get('end');
return Response::json($this->_chart->categories($start, $end));
$limitInPeriod = 'Envelope for XXX';
$spentInPeriod = 'Spent in XXX';
$data['series'] = [
[
'name' => $limitInPeriod,
'data' => []
],
[
'name' => $spentInPeriod,
'data' => []
],
];
foreach ($budgets as $budget) {
if ($budget->count > 0) {
$data['labels'][] = wordwrap($budget->name, 12, "<br>");
}
foreach ($budget->limits as $limit) {
foreach ($limit->limitrepetitions as $rep) {
//0: envelope for period:
$amount = floatval($rep->amount);
$spent = $rep->spent;
$color = $spent > $amount ? '#FF0000' : null;
$data['series'][0]['data'][] = $amount;
$data['series'][1]['data'][] = ['y' => $rep->spent, 'color' => $color];
}
}
}
return Response::json($data);
} }
} }

View File

@@ -35,6 +35,7 @@ abstract class SingleTableInheritanceEntity extends Ardent
{ {
$instance = $this->mapData((array)$attributes)->newInstance([], true); $instance = $this->mapData((array)$attributes)->newInstance([], true);
$instance->setRawAttributes((array)$attributes, true); $instance->setRawAttributes((array)$attributes, true);
return $instance; return $instance;
} }
@@ -117,6 +118,7 @@ abstract class SingleTableInheritanceEntity extends Ardent
if ($this->subclassField) { if ($this->subclassField) {
$this->attributes[$this->subclassField] = get_class($this); $this->attributes[$this->subclassField] = get_class($this);
} }
return parent::save($rules, $customMessages, $options, $beforeSave, $afterSave); return parent::save($rules, $customMessages, $options, $beforeSave, $afterSave);
} }
} }

View File

@@ -127,8 +127,8 @@ class Account implements AccountInterface
// statistics // statistics
$stats['period']['in'] = floatval( $stats['period']['in'] = floatval(
\Transaction::where('account_id', $account->id)->where('amount', '>', 0)->leftJoin( \Transaction::where('account_id', $account->id)->where('amount', '>', 0)->leftJoin(
'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id' 'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id'
)->leftJoin( )->leftJoin(
'transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id' 'transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id'
)->whereIn('transaction_types.type', ['Deposit', 'Withdrawal'])->where( )->whereIn('transaction_types.type', ['Deposit', 'Withdrawal'])->where(
'transaction_journals.date', '>=', $start->format('Y-m-d') 'transaction_journals.date', '>=', $start->format('Y-m-d')
@@ -138,8 +138,8 @@ class Account implements AccountInterface
$stats['period']['out'] = floatval( $stats['period']['out'] = floatval(
\Transaction::where('account_id', $account->id)->where('amount', '<', 0)->leftJoin( \Transaction::where('account_id', $account->id)->where('amount', '<', 0)->leftJoin(
'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id' 'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id'
)->leftJoin( )->leftJoin(
'transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id' 'transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id'
)->whereIn('transaction_types.type', ['Deposit', 'Withdrawal'])->where( )->whereIn('transaction_types.type', ['Deposit', 'Withdrawal'])->where(
'transaction_journals.date', '>=', $start->format('Y-m-d') 'transaction_journals.date', '>=', $start->format('Y-m-d')
@@ -149,8 +149,8 @@ class Account implements AccountInterface
$stats['period']['t_in'] = floatval( $stats['period']['t_in'] = floatval(
\Transaction::where('account_id', $account->id)->where('amount', '>', 0)->leftJoin( \Transaction::where('account_id', $account->id)->where('amount', '>', 0)->leftJoin(
'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id' 'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id'
)->leftJoin( )->leftJoin(
'transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id' 'transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id'
)->where('transaction_types.type', 'Transfer')->where( )->where('transaction_types.type', 'Transfer')->where(
'transaction_journals.date', '>=', $start->format('Y-m-d') 'transaction_journals.date', '>=', $start->format('Y-m-d')
@@ -159,8 +159,8 @@ class Account implements AccountInterface
$stats['period']['t_out'] = floatval( $stats['period']['t_out'] = floatval(
\Transaction::where('account_id', $account->id)->where('amount', '<', 0)->leftJoin( \Transaction::where('account_id', $account->id)->where('amount', '<', 0)->leftJoin(
'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id' 'transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id'
)->leftJoin( )->leftJoin(
'transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id' 'transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id'
)->where('transaction_types.type', 'Transfer')->where( )->where('transaction_types.type', 'Transfer')->where(
'transaction_journals.date', '>=', $start->format('Y-m-d') 'transaction_journals.date', '>=', $start->format('Y-m-d')

View File

@@ -214,7 +214,8 @@ class Budget implements BudgetInterface
} }
$paginator = \Paginator::make($items, $totalItems, $perPage); $paginator = \Paginator::make($items, $totalItems, $perPage);
$result = [0 => ['date' => 'Not in an envelope', 'limit' => null, 'paginated' => true, $result = [0 => ['date' => 'Not in an envelope', 'limit' => null, 'paginated' => true,
'journals' => $paginator]]; 'journals' => $paginator]];
return $result; return $result;
} }
} }

View File

@@ -1,12 +1,15 @@
<?php <?php
namespace Firefly\Helper\Controllers; namespace Firefly\Helper\Controllers;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
/** /**
* Interface BudgetInterface * Interface BudgetInterface
* *
* @package Firefly\Helper\Controllers * @package Firefly\Helper\Controllers
*/ */
interface BudgetInterface { interface BudgetInterface
{
/** /**
* @param Collection $budgets * @param Collection $budgets

View File

@@ -9,50 +9,13 @@
namespace Firefly\Helper\Controllers; namespace Firefly\Helper\Controllers;
use Carbon\Carbon; use Carbon\Carbon;
use Firefly\Exception\FireflyException;
class Chart implements ChartInterface class Chart implements ChartInterface
{ {
public function account(\Account $account) public function account(\Account $account, Carbon $start, Carbon $end)
{ {
$data = [
'chart_title' => $account->name,
'subtitle' => '<a href="' . route('accounts.show', [$account->id]) . '">View more</a>',
'series' => [$this->_account($account)]
];
return $data;
}
public function accounts()
{
$data = [
'chart_title' => 'All accounts',
'subtitle' => '<a href="' . route('accounts.index') . '">View more</a>',
'series' => []
];
/** @var \Firefly\Helper\Preferences\PreferencesHelperInterface $prefs */
$prefs = \App::make('Firefly\Helper\Preferences\PreferencesHelperInterface');
$pref = $prefs->get('frontpageAccounts', []);
/** @var \Firefly\Storage\Account\AccountRepositoryInterface $acct */
$acct = \App::make('Firefly\Storage\Account\AccountRepositoryInterface');
if ($pref->data == []) {
$accounts = $acct->getActiveDefault();
} else {
$accounts = $acct->getByIds($pref->data);
}
foreach($accounts as $account) {
$data['series'][] = $this->_account($account);
}
return $data;
}
protected function _account(\Account $account)
{
$start = \Session::get('start');
$end = \Session::get('end');
$current = clone $start; $current = clone $start;
$today = new Carbon; $today = new Carbon;
$return = ['name' => $account->name, 'id' => $account->id, 'data' => []]; $return = ['name' => $account->name, 'id' => $account->id, 'data' => []];
@@ -65,7 +28,189 @@ class Chart implements ChartInterface
$current->addDay(); $current->addDay();
} }
return $return; return $return;
} }
public function accountDailySummary(\Account $account, Carbon $date)
{
$result = [
'rows' => [],
'sum' => 0
];
if ($account) {
// get journals in range:
$journals = \Auth::user()->transactionjournals()->with(
[
'transactions',
'transactions.account',
'transactioncurrency',
'transactiontype'
]
)
->distinct()
->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('accounts', 'accounts.id', '=', 'transactions.account_id')
->where('transactions.account_id', $account->id)
->where('transaction_journals.date', $date->format('Y-m-d'))
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.id', 'DESC')
->get(['transaction_journals.*']);
// loop all journals:
foreach ($journals as $journal) {
foreach ($journal->transactions as $transaction) {
$name = $transaction->account->name;
if ($transaction->account->id != $account->id) {
$result['rows'][$name] = isset($result[$name]) ? $result[$name] + floatval($transaction->amount)
: floatval($transaction->amount);
$result['sum'] += floatval($transaction->amount);
}
}
}
}
return $result;
}
/**
* @return array
*/
public function budgets(Carbon $start)
{
// grab all budgets in the time period, like the index does:
// get the budgets for this period:
$data = [];
$budgets = \Auth::user()->budgets()->with(
['limits' => function ($q) {
$q->orderBy('limits.startdate', 'ASC');
}, 'limits.limitrepetitions' => function ($q) use ($start) {
$q->orderBy('limit_repetitions.startdate', 'ASC');
$q->where('startdate', $start->format('Y-m-d'));
}]
)->orderBy('name', 'ASC')->get();
foreach ($budgets as $budget) {
$budget->count = 0;
foreach ($budget->limits as $limit) {
/** @var $rep \LimitRepetition */
foreach ($limit->limitrepetitions as $rep) {
$rep->left = $rep->left();
// overspent:
if ($rep->left < 0) {
$rep->spent = ($rep->left * -1) + $rep->amount;
$rep->overspent = $rep->left * -1;
$total = $rep->spent + $rep->overspent;
$rep->spent_pct = round(($rep->spent / $total) * 100);
$rep->overspent_pct = 100 - $rep->spent_pct;
} else {
$rep->spent = $rep->amount - $rep->left;
$rep->spent_pct = round(($rep->spent / $rep->amount) * 100);
$rep->left_pct = 100 - $rep->spent_pct;
}
}
$budget->count += count($limit->limitrepetitions);
}
}
$limitInPeriod = 'Envelope for XXX';
$spentInPeriod = 'Spent in XXX';
$data['series'] = [
[
'name' => $limitInPeriod,
'data' => []
],
[
'name' => $spentInPeriod,
'data' => []
],
];
foreach ($budgets as $budget) {
if ($budget->count > 0) {
$data['labels'][] = wordwrap($budget->name, 12, "<br>");
}
foreach ($budget->limits as $limit) {
foreach ($limit->limitrepetitions as $rep) {
//0: envelope for period:
$amount = floatval($rep->amount);
$spent = $rep->spent;
$color = $spent > $amount ? '#FF0000' : null;
$data['series'][0]['data'][] = $amount;
$data['series'][1]['data'][] = ['y' => $rep->spent, 'color' => $color];
}
}
}
return $data;
}
public function categories(Carbon $start, Carbon $end)
{
$result = [];
// grab all transaction journals in this period:
$journals = \TransactionJournal::
with(
['components', 'transactions' => function ($q) {
$q->where('amount', '>', 0);
}]
)
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->where('transaction_types.type', 'Withdrawal')
->after($start)->before($end)
->where('completed', 1)
->get(['transaction_journals.*']);
foreach ($journals as $journal) {
// has to be one:
if (!isset($journal->transactions[0])) {
throw new FireflyException('Journal #' . $journal->id . ' has ' . count($journal->transactions)
. ' transactions!');
}
$transaction = $journal->transactions[0];
$amount = floatval($transaction->amount);
// get budget from journal:
$category = $journal->categories()->first();
$categoryName = is_null($category) ? '(no category)' : $category->name;
$result[$categoryName] = isset($result[$categoryName]) ? $result[$categoryName] + floatval($amount)
: $amount;
}
unset($journal, $transaction, $category, $amount);
// sort
arsort($result);
$chartData = [
];
foreach ($result as $name => $value) {
$chartData[] = [$name, $value];
}
return $chartData;
}
public function accountXX(\Account $account)
{
$data = [
'chart_title' => $account->name,
'subtitle' => '<a href="' . route('accounts.show', [$account->id]) . '">View more</a>',
'series' => [$this->_account($account)]
];
return $data;
}
} }

View File

@@ -9,9 +9,16 @@
namespace Firefly\Helper\Controllers; namespace Firefly\Helper\Controllers;
use Carbon\Carbon;
interface ChartInterface interface ChartInterface
{ {
public function account(\Account $account); public function account(\Account $account, Carbon $start, Carbon $end);
public function accounts();
public function categories(Carbon $start, Carbon $end);
public function budgets(Carbon $start);
public function accountDailySummary(\Account $account, Carbon $date);
} }

View File

@@ -9,17 +9,21 @@
namespace Firefly\Helper\Form; namespace Firefly\Helper\Form;
use Illuminate\Events\Dispatcher; use Illuminate\Events\Dispatcher;
/** /**
* Class FormTrigger * Class FormTrigger
* *
* @package Firefly\Helper\Form * @package Firefly\Helper\Form
*/ */
class FormTrigger { class FormTrigger
{
public function registerFormExtensions() { public function registerFormExtensions()
{
\Form::macro( \Form::macro(
'budget', function () { 'budget', function () {
$helper = new \Firefly\Helper\Form\FormHelper; $helper = new \Firefly\Helper\Form\FormHelper;
return $helper->budget(); return $helper->budget();
} }
); );

View File

@@ -35,6 +35,7 @@ class MigrationHelper implements MigrationHelperInterface
// file does not exist: // file does not exist:
if (!file_exists($this->path)) { if (!file_exists($this->path)) {
\Log::error('Migration file ' . $this->path . ' does not exist!'); \Log::error('Migration file ' . $this->path . ' does not exist!');
return false; return false;
} }
@@ -50,6 +51,7 @@ class MigrationHelper implements MigrationHelperInterface
return false; return false;
} }
\Log::info('Migration file ' . $this->path . ' is valid!'); \Log::info('Migration file ' . $this->path . ' is valid!');
return true; return true;
} }
@@ -83,11 +85,13 @@ class MigrationHelper implements MigrationHelperInterface
\DB::rollBack(); \DB::rollBack();
\Log::error('Rollback because of error!'); \Log::error('Rollback because of error!');
\Log::error($e->getMessage()); \Log::error($e->getMessage());
return false; return false;
} }
\DB::commit(); \DB::commit();
\Log::info('Done!'); \Log::info('Done!');
return true; return true;
} }
@@ -164,6 +168,7 @@ class MigrationHelper implements MigrationHelperInterface
{ {
/** @var \Firefly\Storage\Account\AccountRepositoryInterface $accounts */ /** @var \Firefly\Storage\Account\AccountRepositoryInterface $accounts */
$accounts = \App::make('Firefly\Storage\Account\AccountRepositoryInterface'); $accounts = \App::make('Firefly\Storage\Account\AccountRepositoryInterface');
return $accounts->store( return $accounts->store(
[ [
'name' => $component->name, 'name' => $component->name,
@@ -181,6 +186,7 @@ class MigrationHelper implements MigrationHelperInterface
{ {
/** @var \Firefly\Storage\Component\ComponentRepositoryInterface $components */ /** @var \Firefly\Storage\Component\ComponentRepositoryInterface $components */
$components = \App::make('Firefly\Storage\Component\ComponentRepositoryInterface'); $components = \App::make('Firefly\Storage\Component\ComponentRepositoryInterface');
return $components->store(['name' => $component->name, 'class' => 'Category']); return $components->store(['name' => $component->name, 'class' => 'Category']);
} }
@@ -193,6 +199,7 @@ class MigrationHelper implements MigrationHelperInterface
{ {
/** @var \Firefly\Storage\Component\ComponentRepositoryInterface $components */ /** @var \Firefly\Storage\Component\ComponentRepositoryInterface $components */
$components = \App::make('Firefly\Storage\Component\ComponentRepositoryInterface'); $components = \App::make('Firefly\Storage\Component\ComponentRepositoryInterface');
return $components->store(['name' => $component->name, 'class' => 'Budget']); return $components->store(['name' => $component->name, 'class' => 'Budget']);
} }

View File

@@ -28,6 +28,7 @@ class PreferencesHelper implements PreferencesHelperInterface
// create preference, return that: // create preference, return that:
return $this->set($name, $default); return $this->set($name, $default);
} }
return null; return null;
} }

View File

@@ -149,6 +149,7 @@ class Toolkit implements ToolkitInterface
return \Redirect::to($request->url()); return \Redirect::to($request->url());
} }
return null; return null;

View File

@@ -3,6 +3,7 @@
namespace Firefly\Helper\Toolkit; namespace Firefly\Helper\Toolkit;
use Illuminate\Http\Request; use Illuminate\Http\Request;
/** /**
* Interface ToolkitInterface * Interface ToolkitInterface
* *

View File

@@ -77,7 +77,7 @@ interface AccountRepositoryInterface
* *
* @return mixed * @return mixed
*/ */
public function getByIds($ids); public function getByIds(array $ids);
/** /**
* @return mixed * @return mixed

View File

@@ -19,6 +19,83 @@ class EloquentAccountRepository implements AccountRepositoryInterface
{ {
} }
/**
* @return mixed
*/
public function count()
{
return \Auth::user()->accounts()->count();
}
/**
* @param $name
* @param \AccountType $type
*
* @return \Account|mixed
*/
public function createOrFind($name, \AccountType $type)
{
$beneficiary = $this->findByName($name);
if (!$beneficiary) {
$data = [
'name' => $name,
'account_type' => $type
];
return $this->store($data);
}
return $beneficiary;
}
/**
* @param $name
*
* @return \Account|mixed|null
*/
public function createOrFindBeneficiary($name)
{
if (is_null($name) || strlen($name) == 0) {
return null;
}
$type = \AccountType::where('description', 'Beneficiary account')->first();
return $this->createOrFind($name, $type);
}
public function destroy($accountId)
{
$account = $this->find($accountId);
if ($account) {
$account->delete();
return true;
}
return false;
}
/**
* @param $accountId
*
* @return mixed
*/
public function find($accountId)
{
return \Auth::user()->accounts()->where('id', $accountId)->first();
}
/**
* @param $name
*
* @return mixed
*/
public function findByName($name)
{
return \Auth::user()->accounts()->where('name', 'like', '%' . $name . '%')->first();
}
/** /**
* @return mixed * @return mixed
*/ */
@@ -27,45 +104,6 @@ class EloquentAccountRepository implements AccountRepositoryInterface
return \Auth::user()->accounts()->with('accounttype')->orderBy('name', 'ASC')->get(); return \Auth::user()->accounts()->with('accounttype')->orderBy('name', 'ASC')->get();
} }
/**
* @return mixed
*/
public function getBeneficiaries()
{
$list = \Auth::user()->accounts()->leftJoin(
'account_types', 'account_types.id', '=', 'accounts.account_type_id'
)
->where('account_types.description', 'Beneficiary account')->where('accounts.active', 1)
->orderBy('accounts.name', 'ASC')->get(['accounts.*']);
return $list;
}
/**
* @param $ids
*
* @return array|mixed
*/
public function getByIds($ids)
{
if (count($ids) > 0) {
return \Auth::user()->accounts()->with('accounttype')->whereIn('id', $ids)->orderBy('name', 'ASC')->get();
} else {
return [];
}
}
/**
* @return mixed
*/
public function getDefault()
{
return \Auth::user()->accounts()->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->where('account_types.description', 'Default account')
->orderBy('accounts.name', 'ASC')->get(['accounts.*']);
}
/** /**
* @return mixed * @return mixed
*/ */
@@ -92,59 +130,60 @@ class EloquentAccountRepository implements AccountRepositoryInterface
foreach ($list as $entry) { foreach ($list as $entry) {
$return[intval($entry->id)] = $entry->name; $return[intval($entry->id)] = $entry->name;
} }
return $return; return $return;
} }
/** /**
* @return mixed * @return mixed
*/ */
public function count() public function getBeneficiaries()
{ {
return \Auth::user()->accounts()->count(); $list = \Auth::user()->accounts()->leftJoin(
'account_types', 'account_types.id', '=', 'accounts.account_type_id'
)
->where('account_types.description', 'Beneficiary account')->where('accounts.active', 1)
->orderBy('accounts.name', 'ASC')->get(['accounts.*']);
return $list;
} }
/** /**
* @param $name * @param $ids
* *
* @return \Account|mixed|null * @return array|mixed
*/ */
public function createOrFindBeneficiary($name) public function getByIds(array $ids)
{ {
if (is_null($name) || strlen($name) == 0) { if (count($ids) > 0) {
return null; return \Auth::user()->accounts()->with('accounttype')->whereIn('id', $ids)->orderBy('name', 'ASC')->get();
} else {
return $this->getActiveDefault();
} }
$type = \AccountType::where('description', 'Beneficiary account')->first();
return $this->createOrFind($name, $type);
} }
/** /**
* @param $name
* @param \AccountType $type
*
* @return \Account|mixed
*/
public function createOrFind($name, \AccountType $type)
{
$beneficiary = $this->findByName($name);
if (!$beneficiary) {
$data = [
'name' => $name,
'account_type' => $type
];
return $this->store($data);
}
return $beneficiary;
}
/**
* @param $name
*
* @return mixed * @return mixed
*/ */
public function findByName($name) public function getCashAccount()
{ {
return \Auth::user()->accounts()->where('name', 'like', '%' . $name . '%')->first(); $type = \AccountType::where('description', 'Cash account')->first();
$cash = \Auth::user()->accounts()->where('account_type_id', $type->id)->first();
return $cash;
}
/**
* @return mixed
*/
public function getDefault()
{
return \Auth::user()->accounts()->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->where('account_types.description', 'Default account')
->orderBy('accounts.name', 'ASC')->get(['accounts.*']);
} }
/** /**
@@ -183,6 +222,35 @@ class EloquentAccountRepository implements AccountRepositoryInterface
return $account; return $account;
} }
/**
* @param $data
*
* @return \Account|void
*/
public function update($data)
{
$account = $this->find($data['id']);
if ($account) {
// update account accordingly:
$account->name = $data['name'];
if ($account->validate()) {
$account->save();
}
// update initial balance if necessary:
if ($account->accounttype->description == 'Default account') {
$journal = $this->findOpeningBalanceTransaction($account);
$journal->date = new Carbon($data['openingbalancedate']);
$journal->transactions[0]->amount = floatval($data['openingbalance']) * -1;
$journal->transactions[1]->amount = floatval($data['openingbalance']);
$journal->transactions[0]->save();
$journal->transactions[1]->save();
$journal->save();
}
}
return $account;
}
/** /**
* @param \Account $account * @param \Account $account
* @param int $amount * @param int $amount
@@ -212,67 +280,11 @@ class EloquentAccountRepository implements AccountRepositoryInterface
$transactionJournal->createSimpleJournal( $transactionJournal->createSimpleJournal(
$initial, $account, 'Initial Balance for ' . $account->name, $amount, $date $initial, $account, 'Initial Balance for ' . $account->name, $amount, $date
); );
return true; return true;
} }
return false; return false;
} }
/**
* @param $data
*
* @return \Account|void
*/
public function update($data)
{
$account = $this->find($data['id']);
if ($account) {
// update account accordingly:
$account->name = $data['name'];
if ($account->validate()) {
$account->save();
}
// update initial balance if necessary:
if ($account->accounttype->description == 'Default account') {
$journal = $this->findOpeningBalanceTransaction($account);
$journal->date = new Carbon($data['openingbalancedate']);
$journal->transactions[0]->amount = floatval($data['openingbalance']) * -1;
$journal->transactions[1]->amount = floatval($data['openingbalance']);
$journal->transactions[0]->save();
$journal->transactions[1]->save();
$journal->save();
}
}
return $account;
}
public function destroy($accountId) {
$account = $this->find($accountId);
if($account) {
$account->delete();
return true;
}
return false;
}
/**
* @param $accountId
*
* @return mixed
*/
public function find($accountId)
{
return \Auth::user()->accounts()->where('id', $accountId)->first();
}
/**
* @return mixed
*/
public function getCashAccount()
{
$type = \AccountType::where('description', 'Cash account')->first();
$cash = \Auth::user()->accounts()->where('account_type_id', $type->id)->first();
return $cash;
}
} }

View File

@@ -23,6 +23,7 @@ interface BudgetRepositoryInterface
/** /**
* @param $data * @param $data
*
* @return mixed * @return mixed
*/ */
public function update($data); public function update($data);
@@ -36,6 +37,7 @@ interface BudgetRepositoryInterface
/** /**
* @param $data * @param $data
*
* @return mixed * @return mixed
*/ */
public function destroy($data); public function destroy($data);

View File

@@ -29,7 +29,7 @@ class EloquentBudgetRepository implements BudgetRepositoryInterface
public function get() public function get()
{ {
$set = \Auth::user()->budgets()->with( $set = \Auth::user()->budgets()->with(
['limits' => function ($q) { ['limits' => function ($q) {
$q->orderBy('limits.startdate', 'ASC'); $q->orderBy('limits.startdate', 'ASC');
}, 'limits.limitrepetitions' => function ($q) { }, 'limits.limitrepetitions' => function ($q) {
$q->orderBy('limit_repetitions.startdate', 'ASC'); $q->orderBy('limit_repetitions.startdate', 'ASC');
@@ -48,9 +48,11 @@ class EloquentBudgetRepository implements BudgetRepositoryInterface
/** /**
* @param $data * @param $data
*
* @return mixed * @return mixed
*/ */
public function update($data) { public function update($data)
{
$budget = $this->find($data['id']); $budget = $this->find($data['id']);
if ($budget) { if ($budget) {
// update account accordingly: // update account accordingly:
@@ -59,15 +61,19 @@ class EloquentBudgetRepository implements BudgetRepositoryInterface
$budget->save(); $budget->save();
} }
} }
return $budget; return $budget;
} }
public function destroy($budgetId) { public function destroy($budgetId)
{
$budget = $this->find($budgetId); $budget = $this->find($budgetId);
if($budget) { if ($budget) {
$budget->delete(); $budget->delete();
return true; return true;
} }
return false; return false;
} }
@@ -96,41 +102,8 @@ class EloquentBudgetRepository implements BudgetRepositoryInterface
public function getWithRepetitionsInPeriod(Carbon $date, $range) public function getWithRepetitionsInPeriod(Carbon $date, $range)
{ {
$set = \Auth::user()->budgets()->with(
['limits' => function ($q) use ($date) {
$q->orderBy('limits.startdate', 'ASC');
}, 'limits.limitrepetitions' => function ($q) use ($date) {
$q->orderBy('limit_repetitions.startdate', 'ASC');
$q->where('startdate', $date->format('Y-m-d'));
}]
)->orderBy('name', 'ASC')->get();
foreach ($set as $budget) { //return $set;
$budget->count = 0;
foreach ($budget->limits as $limit) {
/** @var $rep \LimitRepetition */
foreach ($limit->limitrepetitions as $rep) {
$rep->left = $rep->left();
// overspent:
if ($rep->left < 0) {
$rep->spent = ($rep->left * -1) + $rep->amount;
$rep->overspent = $rep->left * -1;
$total = $rep->spent + $rep->overspent;
$rep->spent_pct = round(($rep->spent / $total) * 100);
$rep->overspent_pct = 100 - $rep->spent_pct;
} else {
$rep->spent = $rep->amount - $rep->left;
$rep->spent_pct = round(($rep->spent / $rep->amount) * 100);
$rep->left_pct = 100 - $rep->spent_pct;
}
}
$budget->count += count($limit->limitrepetitions);
}
}
return $set;
} }
/** /**
@@ -184,6 +157,7 @@ class EloquentBudgetRepository implements BudgetRepositoryInterface
if ($budget->validate()) { if ($budget->validate()) {
$budget->save(); $budget->save();
} }
return $budget; return $budget;
} }

View File

@@ -28,6 +28,7 @@ class EloquentCategoryRepository implements CategoryRepositoryInterface
if (!$category) { if (!$category) {
return $this->store($name); return $this->store($name);
} }
return $category; return $category;
@@ -40,9 +41,10 @@ class EloquentCategoryRepository implements CategoryRepositoryInterface
*/ */
public function findByName($name) public function findByName($name)
{ {
if($name == '') { if ($name == '') {
return null; return null;
} }
return \Auth::user()->categories()->where('name', 'LIKE', '%' . $name . '%')->first(); return \Auth::user()->categories()->where('name', 'LIKE', '%' . $name . '%')->first();
} }
@@ -58,6 +60,7 @@ class EloquentCategoryRepository implements CategoryRepositoryInterface
$category->name = $name; $category->name = $name;
$category->user()->associate(\Auth::user()); $category->user()->associate(\Auth::user());
$category->save(); $category->save();
return $category; return $category;
} }

View File

@@ -37,6 +37,7 @@ class EloquentLimitRepository implements LimitRepositoryInterface
$budget = \Budget::find($data['budget_id']); $budget = \Budget::find($data['budget_id']);
if (is_null($budget)) { if (is_null($budget)) {
\Session::flash('error', 'No such budget.'); \Session::flash('error', 'No such budget.');
return new \Limit; return new \Limit;
} }
// set the date to the correct start period: // set the date to the correct start period:
@@ -76,6 +77,7 @@ class EloquentLimitRepository implements LimitRepositoryInterface
)->count(); )->count();
if ($count > 0) { if ($count > 0) {
\Session::flash('error', 'There already is an entry for these parameters.'); \Session::flash('error', 'There already is an entry for these parameters.');
return new \Limit; return new \Limit;
} }
// create new limit: // create new limit:
@@ -88,6 +90,7 @@ class EloquentLimitRepository implements LimitRepositoryInterface
if (!$limit->save()) { if (!$limit->save()) {
Session::flash('error', 'Could not save: ' . $limit->errors()->first()); Session::flash('error', 'Could not save: ' . $limit->errors()->first());
} }
return $limit; return $limit;
} }

View File

@@ -171,6 +171,7 @@ class EloquentTransactionJournalRepository implements TransactionJournalReposito
$journal->completed = true; $journal->completed = true;
$journal->save(); $journal->save();
return $journal; return $journal;
} }
@@ -209,6 +210,7 @@ class EloquentTransactionJournalRepository implements TransactionJournalReposito
->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.id', 'DESC')
->take($count) ->take($count)
->get(['transaction_journals.*']); ->get(['transaction_journals.*']);
return $query; return $query;
} }
@@ -234,6 +236,7 @@ class EloquentTransactionJournalRepository implements TransactionJournalReposito
->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.id', 'DESC')
->take($count) ->take($count)
->paginate($count); ->paginate($count);
return $query; return $query;
} }
@@ -245,26 +248,7 @@ class EloquentTransactionJournalRepository implements TransactionJournalReposito
*/ */
public function getByDateRange(Carbon $start, Carbon $end) public function getByDateRange(Carbon $start, Carbon $end)
{ {
// lets make this simple. die('no impl');
$types = [];
foreach (\TransactionType::whereIn('type', ['Withdrawal'])->get() as $t) {
$types[] = $t->id;
}
unset($t);
// get all journals, partly filtered:
$journals = \TransactionJournal::
with(
['components', 'transactions' => function ($q) {
$q->where('amount', '>', 0);
}]
)
->after($start)->before($end)
->where('completed', 1)
->whereIn('transaction_type_id', $types)
->get(['transaction_journals.*']);
unset($types);
return $journals;
} }
/** /**
@@ -292,6 +276,7 @@ class EloquentTransactionJournalRepository implements TransactionJournalReposito
->orderBy('transaction_journals.date', 'DESC') ->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.id', 'DESC')
->get(['transaction_journals.*']); ->get(['transaction_journals.*']);
return $query; return $query;
} }

View File

@@ -33,9 +33,11 @@ class EloquentUserRepository implements UserRepositoryInterface
if (!$user->save()) { if (!$user->save()) {
\Log::error('Invalid user'); \Log::error('Invalid user');
\Session::flash('error', 'Input invalid, please try again: ' . $user->errors()->first()); \Session::flash('error', 'Input invalid, please try again: ' . $user->errors()->first());
return false; return false;
} }
$user->save(); $user->save();
return $user; return $user;
} }
@@ -51,6 +53,7 @@ class EloquentUserRepository implements UserRepositoryInterface
if (\Hash::check($array['password'], $user->password)) { if (\Hash::check($array['password'], $user->password)) {
} }
} }
return false; return false;
} }
@@ -87,6 +90,7 @@ class EloquentUserRepository implements UserRepositoryInterface
$user->password = $password; $user->password = $password;
/** @noinspection PhpUndefinedMethodInspection */ /** @noinspection PhpUndefinedMethodInspection */
$user->save(); $user->save();
return true; return true;
} }