From 83de3482ce3d000e30e805a79d1750512b9e6822 Mon Sep 17 00:00:00 2001 From: James Cole Date: Mon, 28 Dec 2015 17:57:03 +0100 Subject: [PATCH 01/62] Optimised budget year chart. --- .../Controllers/Chart/BudgetController.php | 33 ++++++------ app/Repositories/Budget/BudgetRepository.php | 53 +++++++++++++++++++ .../Budget/BudgetRepositoryInterface.php | 11 ++++ 3 files changed, 81 insertions(+), 16 deletions(-) diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index 8d854c474b..b276cdf313 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -283,9 +283,6 @@ class BudgetController extends Controller */ public function year(BudgetRepositoryInterface $repository, $report_type, Carbon $start, Carbon $end, Collection $accounts) { - $allBudgets = $repository->getBudgets(); - $budgets = new Collection; - // chart properties for cache: $cache = new CacheProperties(); $cache->addProperty($start); @@ -298,26 +295,30 @@ class BudgetController extends Controller return Response::json($cache->get()); // @codeCoverageIgnore } - // filter empty budgets: - foreach ($allBudgets as $budget) { - $spent = $repository->balanceInPeriod($budget, $start, $end, $accounts); - if ($spent != 0) { - $budgets->push($budget); - } - } + $budgetInformation = $repository->getBudgetsAndExpenses($start, $end); + $budgets = new Collection; + $entries = new Collection; - $entries = new Collection; + /** @var array $row */ + foreach ($budgetInformation as $row) { + $budgets->push($row['budget']); + } while ($start < $end) { // month is the current end of the period: $month = clone $start; $month->endOfMonth(); - $row = [clone $start]; + $row = [clone $start]; + $dateFormatted = $start->format('Y-m'); - // each budget, fill the row: - foreach ($budgets as $budget) { - $spent = $repository->balanceInPeriod($budget, $start, $month, $accounts); - $row[] = $spent * -1; + // each budget, check if there is an entry for this month: + /** @var array $row */ + foreach ($budgetInformation as $budgetRow) { + $spent = 0; // nothing spent. + if (isset($budgetRow['entries'][$dateFormatted])) { + $spent = $budgetRow['entries'][$dateFormatted] * -1; // to fit array + } + $row[] = $spent; } $entries->push($row); $start->endOfMonth()->addDay(); diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index a38cd42261..56113c1d76 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -210,6 +210,59 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn return Carbon::now()->startOfYear(); } + /** + * Returns an array with every budget in it and the expenses for each budget + * per month. + * + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function getBudgetsAndExpenses(Carbon $start, Carbon $end) + { + /** @var Collection $set */ + $set = Auth::user()->budgets() + ->leftJoin('budget_transaction_journal', 'budgets.id', '=', 'budget_transaction_journal.budget_id') + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id') + ->leftJoin( + 'transactions', function (JoinClause $join) { + $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0); + } + ) + ->groupBy('budgets.id') + ->groupBy('dateFormatted') + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->get( + [ + 'budgets.*', + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`, "%Y-%m") AS `dateFormatted`'), + DB::Raw('SUM(`transactions`.`amount`) AS `sumAmount`') + ] + ); + + $set = $set->sortBy( + function (Budget $budget) { + return strtolower($budget->name); + } + ); + + $return = []; + foreach ($set as $budget) { + $id = $budget->id; + if (!isset($return[$id])) { + $return[$id] = [ + 'budget' => $budget, + 'entries' => [], + ]; + } + // store each entry: + $return[$id]['entries'][$budget->dateFormatted] = $budget->sumAmount; + } + return $return; + } + /** * @return Collection */ diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 9ac42a85be..4e75e37bc6 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -27,6 +27,17 @@ interface BudgetRepositoryInterface */ public function destroy(Budget $budget); + /** + * Returns an array with every budget in it and the expenses for each budget + * per month. + * + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function getBudgetsAndExpenses(Carbon $start, Carbon $end); + /** * Takes tags into account. * From 6ab6dd6ac3c5011e4ee0ee1c1d3f0baf1a0ebe13 Mon Sep 17 00:00:00 2001 From: James Cole Date: Mon, 28 Dec 2015 19:56:28 +0100 Subject: [PATCH 02/62] First attempt at optimised query for multi-year budget chart. --- .../Controllers/Chart/BudgetController.php | 55 +++--- app/Repositories/Budget/BudgetRepository.php | 157 +++++++++++++++--- .../Budget/BudgetRepositoryInterface.php | 31 +++- 3 files changed, 194 insertions(+), 49 deletions(-) diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index b276cdf313..767a87280b 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -37,6 +37,8 @@ class BudgetController extends Controller } /** + * TODO expand with no budget chart. + * * @param BudgetRepositoryInterface $repository * @param $report_type * @param Carbon $start @@ -61,41 +63,43 @@ class BudgetController extends Controller return Response::json($cache->get()); // @codeCoverageIgnore } - /** - * budget - * year: - * spent: x - * budgeted: x - * year - * spent: x - * budgeted: x + /* + * Get the budgeted amounts for each budgets in each year. */ + $budgetedSet = $repository->getBudgetedPerYear($budgets, $start, $end); + $budgetedArray = []; + /** @var Budget $entry */ + foreach ($budgetedSet as $entry) { + $budgetedArray[$entry->id][$entry->dateFormatted] = $entry->budgeted; + } + + $set = $repository->getBudgetsAndExpensesPerYear($budgets, $accounts, $start, $end); $entries = new Collection; // go by budget, not by year. + /** @var Budget $budget */ foreach ($budgets as $budget) { - $entry = ['name' => '', 'spent' => [], 'budgeted' => []]; - + $entry = ['name' => '', 'spent' => [], 'budgeted' => []]; + $id = $budget->id; $currentStart = clone $start; while ($currentStart < $end) { // fix the date: $currentEnd = clone $currentStart; $currentEnd->endOfYear(); - // get data: - if (is_null($budget->id)) { - $name = trans('firefly.noBudget'); - $sum = $repository->getWithoutBudgetSum($currentStart, $currentEnd); - $budgeted = 0; - } else { - $name = $budget->name; - $sum = $repository->balanceInPeriod($budget, $currentStart, $currentEnd, $accounts); - $budgeted = $repository->getBudgetLimitRepetitions($budget, $currentStart, $currentEnd)->sum('amount'); + // save to array: + $year = $currentStart->year; + $entry['name'] = $budget->name; + $spent = 0; + $budgeted = 0; + if (isset($set[$id]['entries'][$year])) { + $spent = $set[$id]['entries'][$year] * -1; } - // save to array: - $year = $currentStart->year; - $entry['name'] = $name; - $entry['spent'][$year] = ($sum * -1); + if (isset($budgetedArray[$id][$year])) { + $budgeted = round($budgetedArray[$id][$year], 2); + } + + $entry['spent'][$year] = $spent; $entry['budgeted'][$year] = $budgeted; // jump to next year. @@ -106,6 +110,7 @@ class BudgetController extends Controller } // generate chart with data: $data = $this->generator->multiYear($entries); + $cache->store($data); return Response::json($data); @@ -273,6 +278,8 @@ class BudgetController extends Controller } /** + * TODO expand with no budget chart. + * * @param BudgetRepositoryInterface $repository * @param $report_type * @param Carbon $start @@ -295,7 +302,7 @@ class BudgetController extends Controller return Response::json($cache->get()); // @codeCoverageIgnore } - $budgetInformation = $repository->getBudgetsAndExpenses($start, $end); + $budgetInformation = $repository->getBudgetsAndExpensesPerMonth($accounts, $start, $end); $budgets = new Collection; $entries = new Collection; diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 56113c1d76..9b90c88d69 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -5,6 +5,7 @@ namespace FireflyIII\Repositories\Budget; use Auth; use Carbon\Carbon; use DB; +use FireflyIII\Models\Account; use FireflyIII\Models\Budget; use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\LimitRepetition; @@ -214,33 +215,41 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn * Returns an array with every budget in it and the expenses for each budget * per month. * - * @param Carbon $start - * @param Carbon $end + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end * * @return array */ - public function getBudgetsAndExpenses(Carbon $start, Carbon $end) + public function getBudgetsAndExpensesPerMonth(Collection $accounts, Carbon $start, Carbon $end) { + $ids = []; + /** @var Account $account */ + foreach ($accounts as $account) { + $ids[] = $account->id; + } + /** @var Collection $set */ - $set = Auth::user()->budgets() - ->leftJoin('budget_transaction_journal', 'budgets.id', '=', 'budget_transaction_journal.budget_id') - ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id') - ->leftJoin( - 'transactions', function (JoinClause $join) { - $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0); - } - ) - ->groupBy('budgets.id') - ->groupBy('dateFormatted') - ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) - ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) - ->get( - [ - 'budgets.*', - DB::Raw('DATE_FORMAT(`transaction_journals`.`date`, "%Y-%m") AS `dateFormatted`'), - DB::Raw('SUM(`transactions`.`amount`) AS `sumAmount`') - ] - ); + $set = Auth::user()->budgets() + ->leftJoin('budget_transaction_journal', 'budgets.id', '=', 'budget_transaction_journal.budget_id') + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id') + ->leftJoin( + 'transactions', function (JoinClause $join) { + $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0); + } + ) + ->groupBy('budgets.id') + ->groupBy('dateFormatted') + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->whereIn('transactions.account_id', $ids) + ->get( + [ + 'budgets.*', + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`, "%Y-%m") AS `dateFormatted`'), + DB::Raw('SUM(`transactions`.`amount`) AS `sumAmount`') + ] + ); $set = $set->sortBy( function (Budget $budget) { @@ -260,6 +269,7 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn // store each entry: $return[$id]['entries'][$budget->dateFormatted] = $budget->sumAmount; } + return $return; } @@ -503,7 +513,110 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn } return $limit; + } + /** + * Get the budgeted amounts for each budgets in each year. + * + * @param Collection $budgets + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getBudgetedPerYear(Collection $budgets, Carbon $start, Carbon $end) + { + $budgetIds = []; + /** @var Budget $budget */ + foreach ($budgets as $budget) { + $budgetIds[] = $budget->id; + } + + $set = Auth::user()->budgets() + ->leftJoin('budget_limits', 'budgets.id', '=', 'budget_limits.budget_id') + ->leftJoin('limit_repetitions', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id') + ->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d')) + ->where('limit_repetitions.enddate', '<=', $end->format('Y-m-d')) + ->groupBy('budgets.id') + ->groupBy('dateFormatted') + ->whereIn('budgets.id', $budgetIds) + ->get( + [ + 'budgets.*', + DB::Raw('DATE_FORMAT(`limit_repetitions`.`startdate`,"%Y") as `dateFormatted`'), + DB::Raw('SUM(`limit_repetitions`.`amount`) as `budgeted`') + ] + ); + return $set; + } + + /** + * Returns an array with every budget in it and the expenses for each budget + * per year for. + * + * @param Collection $budgets + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function getBudgetsAndExpensesPerYear(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end) + { + $ids = []; + /** @var Account $account */ + foreach ($accounts as $account) { + $ids[] = $account->id; + } + $budgetIds = []; + /** @var Budget $budget */ + foreach ($budgets as $budget) { + $budgetIds[] = $budget->id; + } + + /** @var Collection $set */ + $set = Auth::user()->budgets() + ->leftJoin('budget_transaction_journal', 'budgets.id', '=', 'budget_transaction_journal.budget_id') + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id') + ->leftJoin( + 'transactions', function (JoinClause $join) { + $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0); + } + ) + ->groupBy('budgets.id') + ->groupBy('dateFormatted') + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->whereIn('transactions.account_id', $ids) + ->whereIn('budgets.id', $budgetIds) + ->get( + [ + 'budgets.*', + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`, "%Y") AS `dateFormatted`'), + DB::Raw('SUM(`transactions`.`amount`) AS `sumAmount`') + ] + ); + + $set = $set->sortBy( + function (Budget $budget) { + return strtolower($budget->name); + } + ); + + $return = []; + foreach ($set as $budget) { + $id = $budget->id; + if (!isset($return[$id])) { + $return[$id] = [ + 'budget' => $budget, + 'entries' => [], + ]; + } + // store each entry: + $return[$id]['entries'][$budget->dateFormatted] = $budget->sumAmount; + } + + return $return; } } diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 4e75e37bc6..0c14906983 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -31,12 +31,26 @@ interface BudgetRepositoryInterface * Returns an array with every budget in it and the expenses for each budget * per month. * - * @param Carbon $start - * @param Carbon $end + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end * * @return array */ - public function getBudgetsAndExpenses(Carbon $start, Carbon $end); + public function getBudgetsAndExpensesPerMonth(Collection $accounts, Carbon $start, Carbon $end); + + /** + * Returns an array with every budget in it and the expenses for each budget + * per year for. + * + * @param Collection $budgets + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function getBudgetsAndExpensesPerYear(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end); /** * Takes tags into account. @@ -53,6 +67,17 @@ interface BudgetRepositoryInterface */ public function getActiveBudgets(); + /** + * Get the budgeted amounts for each budgets in each year. + * + * @param Collection $budgets + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getBudgetedPerYear(Collection $budgets, Carbon $start, Carbon $end); + /** * @param Budget $budget * @param Carbon $start From 026683a8e150ffcff77d72ec060317904c50c296 Mon Sep 17 00:00:00 2001 From: James Cole Date: Mon, 28 Dec 2015 20:04:54 +0100 Subject: [PATCH 03/62] Made reportType camelCase. --- .../Controllers/Chart/AccountController.php | 4 +-- .../Controllers/Chart/BudgetController.php | 12 +++---- .../Controllers/Chart/CategoryController.php | 18 +++++------ .../Controllers/Chart/ReportController.php | 8 ++--- app/Http/Controllers/ReportController.php | 32 +++++++++---------- app/Http/routes.php | 18 +++++------ resources/twig/reports/default/month.twig | 4 +-- .../twig/reports/default/multi-year.twig | 4 +-- resources/twig/reports/default/year.twig | 4 +-- 9 files changed, 52 insertions(+), 52 deletions(-) diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php index 5048553403..d403f56dc5 100644 --- a/app/Http/Controllers/Chart/AccountController.php +++ b/app/Http/Controllers/Chart/AccountController.php @@ -37,14 +37,14 @@ class AccountController extends Controller /** * Shows the balances for a given set of dates and accounts. * - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return \Illuminate\Http\JsonResponse */ - public function report($report_type, Carbon $start, Carbon $end, Collection $accounts) + public function report($reportType, Carbon $start, Carbon $end, Collection $accounts) { // chart properties for cache: $cache = new CacheProperties(); diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index 767a87280b..386a10636c 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -40,7 +40,7 @@ class BudgetController extends Controller * TODO expand with no budget chart. * * @param BudgetRepositoryInterface $repository - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts @@ -48,11 +48,11 @@ class BudgetController extends Controller * * @return \Illuminate\Http\JsonResponse */ - public function multiYear(BudgetRepositoryInterface $repository, $report_type, Carbon $start, Carbon $end, Collection $accounts, Collection $budgets) + public function multiYear(BudgetRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts, Collection $budgets) { // chart properties for cache: $cache = new CacheProperties(); - $cache->addProperty($report_type); + $cache->addProperty($reportType); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($accounts); @@ -281,20 +281,20 @@ class BudgetController extends Controller * TODO expand with no budget chart. * * @param BudgetRepositoryInterface $repository - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return \Illuminate\Http\JsonResponse */ - public function year(BudgetRepositoryInterface $repository, $report_type, Carbon $start, Carbon $end, Collection $accounts) + public function year(BudgetRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) { // chart properties for cache: $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($report_type); + $cache->addProperty($reportType); $cache->addProperty($accounts); $cache->addProperty('budget'); $cache->addProperty('year'); diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 6511dd92ac..3866463570 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -130,7 +130,7 @@ class CategoryController extends Controller /** * @param CategoryRepositoryInterface $repository - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts @@ -138,11 +138,11 @@ class CategoryController extends Controller * * @return \Illuminate\Http\JsonResponse */ - public function multiYear(CategoryRepositoryInterface $repository, $report_type, Carbon $start, Carbon $end, Collection $accounts, Collection $categories) + public function multiYear(CategoryRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts, Collection $categories) { // chart properties for cache: $cache = new CacheProperties(); - $cache->addProperty($report_type); + $cache->addProperty($reportType); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($accounts); @@ -296,20 +296,20 @@ class CategoryController extends Controller * grouped by month. * * @param CategoryRepositoryInterface $repository - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return \Illuminate\Http\JsonResponse */ - public function earnedInPeriod(CategoryRepositoryInterface $repository, $report_type, Carbon $start, Carbon $end, Collection $accounts) + public function earnedInPeriod(CategoryRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) { $original = clone $start; $cache = new CacheProperties; // chart properties for cache: $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($report_type); + $cache->addProperty($reportType); $cache->addProperty($accounts); $cache->addProperty('category'); $cache->addProperty('earned-in-period'); @@ -400,20 +400,20 @@ class CategoryController extends Controller * grouped by month. * * @param CategoryRepositoryInterface $repository - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return \Illuminate\Http\JsonResponse */ - public function spentInPeriod(CategoryRepositoryInterface $repository, $report_type, Carbon $start, Carbon $end, Collection $accounts) + public function spentInPeriod(CategoryRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) { $original = clone $start; $cache = new CacheProperties; // chart properties for cache: $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($report_type); + $cache->addProperty($reportType); $cache->addProperty($accounts); $cache->addProperty('category'); $cache->addProperty('spent-in-period'); diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php index 9311589093..f289262064 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -36,14 +36,14 @@ class ReportController extends Controller * Summarizes all income and expenses, per month, for a given year. * * @param ReportQueryInterface $query - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return \Illuminate\Http\JsonResponse */ - public function yearInOut(ReportQueryInterface $query, $report_type, Carbon $start, Carbon $end, Collection $accounts) + public function yearInOut(ReportQueryInterface $query, $reportType, Carbon $start, Carbon $end, Collection $accounts) { // chart properties for cache: $cache = new CacheProperties; @@ -105,14 +105,14 @@ class ReportController extends Controller * Summarizes all income and expenses for a given year. Gives a total and an average. * * @param ReportQueryInterface $query - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return \Illuminate\Http\JsonResponse */ - public function yearInOutSummarized(ReportQueryInterface $query, $report_type, Carbon $start, Carbon $end, Collection $accounts) + public function yearInOutSummarized(ReportQueryInterface $query, $reportType, Carbon $start, Carbon $end, Collection $accounts) { // chart properties for cache: diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index ccf47d7e4a..3ede022898 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -73,14 +73,14 @@ class ReportController extends Controller } /** - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return View */ - public function defaultYear($report_type, Carbon $start, Carbon $end, Collection $accounts) + public function defaultYear($reportType, Carbon $start, Carbon $end, Collection $accounts) { $incomeTopLength = 8; $expenseTopLength = 8; @@ -104,7 +104,7 @@ class ReportController extends Controller return view( 'reports.default.year', compact( - 'start', 'accountReport', 'incomes', 'report_type', 'accountIds', 'end', + 'start', 'accountReport', 'incomes', 'reportType', 'accountIds', 'end', 'expenses', 'incomeTopLength', 'expenseTopLength' ) ); @@ -112,14 +112,14 @@ class ReportController extends Controller /** - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return View */ - public function defaultMonth($report_type, Carbon $start, Carbon $end, Collection $accounts) + public function defaultMonth($reportType, Carbon $start, Carbon $end, Collection $accounts) { $incomeTopLength = 8; $expenseTopLength = 8; @@ -145,27 +145,27 @@ class ReportController extends Controller return view( 'reports.default.month', compact( - 'start', 'end', 'report_type', + 'start', 'end', 'reportType', 'accountReport', 'incomes', 'incomeTopLength', 'expenses', 'expenseTopLength', 'budgets', 'balance', 'categories', 'bills', - 'accountIds', 'report_type' + 'accountIds', 'reportType' ) ); } /** - * @param $report_type + * @param $reportType * @param $start * @param $end * @param $accounts * * @return View */ - public function defaultMultiYear($report_type, $start, $end, $accounts) + public function defaultMultiYear($reportType, $start, $end, $accounts) { @@ -182,19 +182,19 @@ class ReportController extends Controller $accountIds = join(',', $accountIds); return view( - 'reports.default.multi-year', compact('budgets', 'accounts', 'categories', 'start', 'end', 'accountIds', 'report_type') + 'reports.default.multi-year', compact('budgets', 'accounts', 'categories', 'start', 'end', 'accountIds', 'reportType') ); } /** - * @param $report_type + * @param $reportType * @param Carbon $start * @param Carbon $end * @param Collection $accounts * * @return View */ - public function report($report_type, Carbon $start, Carbon $end, Collection $accounts) + public function report($reportType, Carbon $start, Carbon $end, Collection $accounts) { // throw an error if necessary. if ($end < $start) { @@ -206,7 +206,7 @@ class ReportController extends Controller $start = Session::get('first'); } - switch ($report_type) { + switch ($reportType) { default: case 'default': @@ -223,14 +223,14 @@ class ReportController extends Controller // more than one year date difference means year report. if ($start->diffInMonths($end) > 12) { - return $this->defaultMultiYear($report_type, $start, $end, $accounts); + return $this->defaultMultiYear($reportType, $start, $end, $accounts); } // more than two months date difference means year report. if ($start->diffInMonths($end) > 1) { - return $this->defaultYear($report_type, $start, $end, $accounts); + return $this->defaultYear($reportType, $start, $end, $accounts); } - return $this->defaultMonth($report_type, $start, $end, $accounts); + return $this->defaultMonth($reportType, $start, $end, $accounts); } diff --git a/app/Http/routes.php b/app/Http/routes.php index ac043af6f3..21dec7d669 100644 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -389,7 +389,7 @@ Route::group( // accounts: Route::get('/chart/account/frontpage', ['uses' => 'Chart\AccountController@frontpage']); Route::get('/chart/account/expense', ['uses' => 'Chart\AccountController@expenseAccounts']); - Route::get('/chart/account/report/{report_type}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\AccountController@report']); + Route::get('/chart/account/report/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\AccountController@report']); Route::get('/chart/account/{account}', ['uses' => 'Chart\AccountController@single']); @@ -401,8 +401,8 @@ Route::group( Route::get('/chart/budget/frontpage', ['uses' => 'Chart\BudgetController@frontpage']); // this chart is used in reports: - Route::get('/chart/budget/year/{report_type}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\BudgetController@year']); - Route::get('/chart/budget/multi-year/{report_type}/{start_date}/{end_date}/{accountList}/{budgetList}', ['uses' => 'Chart\BudgetController@multiYear']); + Route::get('/chart/budget/year/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\BudgetController@year']); + Route::get('/chart/budget/multi-year/{reportType}/{start_date}/{end_date}/{accountList}/{budgetList}', ['uses' => 'Chart\BudgetController@multiYear']); Route::get('/chart/budget/{budget}/{limitrepetition}', ['uses' => 'Chart\BudgetController@budgetLimit']); Route::get('/chart/budget/{budget}', ['uses' => 'Chart\BudgetController@budget']); @@ -411,10 +411,10 @@ Route::group( Route::get('/chart/category/frontpage', ['uses' => 'Chart\CategoryController@frontpage']); // these three charts are for reports: - Route::get('/chart/category/earned-in-period/{report_type}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\CategoryController@earnedInPeriod']); - Route::get('/chart/category/spent-in-period/{report_type}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\CategoryController@spentInPeriod']); + Route::get('/chart/category/earned-in-period/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\CategoryController@earnedInPeriod']); + Route::get('/chart/category/spent-in-period/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\CategoryController@spentInPeriod']); Route::get( - '/chart/category/multi-year/{report_type}/{start_date}/{end_date}/{accountList}/{categoryList}', ['uses' => 'Chart\CategoryController@multiYear'] + '/chart/category/multi-year/{reportType}/{start_date}/{end_date}/{accountList}/{categoryList}', ['uses' => 'Chart\CategoryController@multiYear'] ); Route::get('/chart/category/{category}/period', ['uses' => 'Chart\CategoryController@currentPeriod']); @@ -425,8 +425,8 @@ Route::group( Route::get('/chart/piggyBank/{piggyBank}', ['uses' => 'Chart\PiggyBankController@history']); // reports: - Route::get('/chart/report/in-out/{report_type}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOut']); - Route::get('/chart/report/in-out-sum/{report_type}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOutSummarized']); + Route::get('/chart/report/in-out/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOut']); + Route::get('/chart/report/in-out-sum/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOutSummarized']); /** @@ -492,7 +492,7 @@ Route::group( * Report Controller */ Route::get('/reports', ['uses' => 'ReportController@index', 'as' => 'reports.index']); - Route::get('/reports/report/{report_type}/{start_date}/{end_date}/{accountList}', ['uses' => 'ReportController@report', 'as' => 'reports.report']); + Route::get('/reports/report/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'ReportController@report', 'as' => 'reports.report']); /** * Search Controller diff --git a/resources/twig/reports/default/month.twig b/resources/twig/reports/default/month.twig index 4a1008753b..4b7a9401a5 100644 --- a/resources/twig/reports/default/month.twig +++ b/resources/twig/reports/default/month.twig @@ -1,7 +1,7 @@ {% extends "./layout/default.twig" %} {% block breadcrumbs %} - {{ Breadcrumbs.renderIfExists(Route.getCurrentRoute.getName, start, end, report_type, accountIds) }} + {{ Breadcrumbs.renderIfExists(Route.getCurrentRoute.getName, start, end, reportType, accountIds) }} {% endblock %} {% block content %} @@ -75,7 +75,7 @@ // to report another URL: var startDate = '{{ start.format('Ymd') }}'; var endDate = '{{ end.format('Ymd') }}'; - var reportType = '{{ report_type }}'; + var reportType = '{{ reportType }}'; var accountIds = '{{ accountIds }}'; var incomeTopLength = {{ incomeTopLength }}; diff --git a/resources/twig/reports/default/multi-year.twig b/resources/twig/reports/default/multi-year.twig index 6e7b218791..1d1334b1b9 100644 --- a/resources/twig/reports/default/multi-year.twig +++ b/resources/twig/reports/default/multi-year.twig @@ -1,7 +1,7 @@ {% extends "./layout/default.twig" %} {% block breadcrumbs %} - {{ Breadcrumbs.renderIfExists(Route.getCurrentRoute.getName, start, end, report_type, accountIds) }} + {{ Breadcrumbs.renderIfExists(Route.getCurrentRoute.getName, start, end, reportType, accountIds) }} {% endblock %} {% block content %} @@ -125,7 +125,7 @@ // to report another URL: var startDate = '{{ start.format('Ymd') }}'; var endDate = '{{ end.format('Ymd') }}'; - var reportType = '{{ report_type }}'; + var reportType = '{{ reportType }}'; var accountIds = '{{ accountIds }}'; diff --git a/resources/twig/reports/default/year.twig b/resources/twig/reports/default/year.twig index d69be74f88..b54a71131d 100644 --- a/resources/twig/reports/default/year.twig +++ b/resources/twig/reports/default/year.twig @@ -1,7 +1,7 @@ {% extends "./layout/default.twig" %} {% block breadcrumbs %} - {{ Breadcrumbs.renderIfExists(Route.getCurrentRoute.getName, start, end, report_type, accountIds) }} + {{ Breadcrumbs.renderIfExists(Route.getCurrentRoute.getName, start, end, reportType, accountIds) }} {% endblock %} {% block content %} @@ -92,7 +92,7 @@ // to report another URL: var startDate = '{{ start.format('Ymd') }}'; var endDate = '{{ end.format('Ymd') }}'; - var reportType = '{{ report_type }}'; + var reportType = '{{ reportType }}'; var accountIds = '{{ accountIds }}'; From 77056dcf8de544ca2069a5381775e79c752dfdd9 Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 29 Dec 2015 08:27:05 +0100 Subject: [PATCH 04/62] Cleanup. --- app/Http/Controllers/TransactionController.php | 2 +- app/Models/AccountType.php | 1 + app/Models/PiggyBankEvent.php | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/app/Http/Controllers/TransactionController.php b/app/Http/Controllers/TransactionController.php index 8db37205bd..604a10d789 100644 --- a/app/Http/Controllers/TransactionController.php +++ b/app/Http/Controllers/TransactionController.php @@ -285,7 +285,7 @@ class TransactionController extends Controller $what = strtolower($journal->getTransactionType()); $subTitle = trans('firefly.' . $journal->getTransactionType()) . ' "' . e($journal->description) . '"'; - return view('transactions.show', compact('journal','events', 'subTitle', 'what')); + return view('transactions.show', compact('journal', 'events', 'subTitle', 'what')); } /** diff --git a/app/Models/AccountType.php b/app/Models/AccountType.php index 6716a9ab69..65b1e0474c 100644 --- a/app/Models/AccountType.php +++ b/app/Models/AccountType.php @@ -33,6 +33,7 @@ class AccountType extends Model /** * @return array */ + /** @noinspection PhpMissingParentCallCommonInspection */ public function getDates() { return ['created_at', 'updated_at']; diff --git a/app/Models/PiggyBankEvent.php b/app/Models/PiggyBankEvent.php index a06e3dd35a..d2c016e356 100644 --- a/app/Models/PiggyBankEvent.php +++ b/app/Models/PiggyBankEvent.php @@ -32,6 +32,7 @@ class PiggyBankEvent extends Model /** * @return array */ + /** @noinspection PhpMissingParentCallCommonInspection */ public function getDates() { return ['created_at', 'updated_at', 'date']; From 38fe9e7e1cc72c92ed80f6226f433254ec7ace37 Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 29 Dec 2015 08:27:13 +0100 Subject: [PATCH 05/62] Optimised chart. --- .../Controllers/Chart/BudgetController.php | 13 +++- app/Repositories/Budget/BudgetRepository.php | 72 +++++++++++++++---- .../Budget/BudgetRepositoryInterface.php | 12 ++++ 3 files changed, 81 insertions(+), 16 deletions(-) diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index 386a10636c..1f3d2f5723 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -190,15 +190,24 @@ class BudgetController extends Controller return Response::json($cache->get()); // @codeCoverageIgnore } + $set = $repository->getExpensesPerDay($budget, $start, $end); $entries = new Collection; $amount = $repetition->amount; + // get sum (har har)! while ($start <= $end) { + $formatted = $start->format('Y-m-d'); + $filtered = $set->filter( + function (Budget $obj) use ($formatted) { + return $obj->date == $formatted; + } + ); + $sum = is_null($filtered->first()) ? '0' : $filtered->first()->dailyAmount; + /* * Sum of expenses on this day: */ - $sum = $repository->expensesOnDay($budget, $start); - $amount = bcadd($amount, $sum); + $amount = round(bcadd($amount, $sum), 2); $entries->push([clone $start, $amount]); $start->addDay(); } diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 9b90c88d69..6a06fd533b 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -37,6 +37,49 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn } + /** + * Returns the expenses for this budget grouped per day, with the date + * in "date" (a string, not a Carbon) and the amount in "dailyAmount". + * + * @param Budget $budget + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getExpensesPerDay(Budget $budget, Carbon $start, Carbon $end) + { + /* + * select transaction_journals.date, SUM(transactions.amount) as dailyAmount from budgets +left join budget_transaction_journal ON budget_transaction_journal.budget_id = budgets.id +left join transaction_journals ON budget_transaction_journal.transaction_journal_id = transaction_journals.id +left join transactions ON transaction_journals.id = transactions.transaction_journal_id +where + +transaction_journals.date >= "2015-12-01" +and transaction_journals.date <= "2015-12-31" +and budgets.id = 1 +and transactions.amount < 0 +group by transaction_journals.date +order by transaction_journals.date + */ + + $set = Auth::user()->budgets() + ->leftJoin('budget_transaction_journal', 'budget_transaction_journal.budget_id', '=', 'budgets.id') + ->leftJoin('transaction_journals', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->where('budgets.id', $budget->id) + ->where('transactions.amount', '<', 0) + ->groupBy('transaction_journals.date') + ->orderBy('transaction_journals.date') + ->get(['transaction_journals.date', DB::Raw('SUM(`transactions`.`amount`) as `dailyAmount`')]); + + return $set; + + } + /** * @param Budget $budget * @@ -534,20 +577,21 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn } $set = Auth::user()->budgets() - ->leftJoin('budget_limits', 'budgets.id', '=', 'budget_limits.budget_id') - ->leftJoin('limit_repetitions', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id') - ->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d')) - ->where('limit_repetitions.enddate', '<=', $end->format('Y-m-d')) - ->groupBy('budgets.id') - ->groupBy('dateFormatted') - ->whereIn('budgets.id', $budgetIds) - ->get( - [ - 'budgets.*', - DB::Raw('DATE_FORMAT(`limit_repetitions`.`startdate`,"%Y") as `dateFormatted`'), - DB::Raw('SUM(`limit_repetitions`.`amount`) as `budgeted`') - ] - ); + ->leftJoin('budget_limits', 'budgets.id', '=', 'budget_limits.budget_id') + ->leftJoin('limit_repetitions', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id') + ->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d')) + ->where('limit_repetitions.enddate', '<=', $end->format('Y-m-d')) + ->groupBy('budgets.id') + ->groupBy('dateFormatted') + ->whereIn('budgets.id', $budgetIds) + ->get( + [ + 'budgets.*', + DB::Raw('DATE_FORMAT(`limit_repetitions`.`startdate`,"%Y") as `dateFormatted`'), + DB::Raw('SUM(`limit_repetitions`.`amount`) as `budgeted`') + ] + ); + return $set; } diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 0c14906983..11dbcae4c1 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -20,6 +20,18 @@ interface BudgetRepositoryInterface */ public function cleanupBudgets(); + /** + * Returns the expenses for this budget grouped per day, with the date + * in "date" (a string, not a Carbon) and the amount in "dailyAmount". + * + * @param Budget $budget + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getExpensesPerDay(Budget $budget, Carbon $start, Carbon $end); + /** * @param Budget $budget * From 658265c93845e786a0329a2d9bc8d70a82f543b4 Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 29 Dec 2015 08:45:43 +0100 Subject: [PATCH 06/62] Optimised whole budget chart to use less queries. --- .../Controllers/Chart/BudgetController.php | 28 ++++++----- app/Repositories/Budget/BudgetRepository.php | 48 +++++++++++++------ .../Budget/BudgetRepositoryInterface.php | 12 +++++ 3 files changed, 62 insertions(+), 26 deletions(-) diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index 1f3d2f5723..8f197a6a88 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -130,11 +130,6 @@ class BudgetController extends Controller $first = $repository->getFirstBudgetLimitDate($budget); $range = Preferences::get('viewRange', '1M')->data; $last = Session::get('end', new Carbon); - $final = clone $last; - $final->addYears(2); - $last = Navigation::endOfX($last, $range, $final); - $accounts = $accountRepository->getAccounts(['Default account', 'Asset account', 'Cash account']); - // chart properties for cache: $cache = new CacheProperties(); @@ -142,18 +137,29 @@ class BudgetController extends Controller $cache->addProperty($last); $cache->addProperty('budget'); if ($cache->has()) { + return Response::json($cache->get()); // @codeCoverageIgnore } + $final = clone $last; + $final->addYears(2); + $last = Navigation::endOfX($last, $range, $final); $entries = new Collection; + // get all expenses: + $set = $repository->getExpensesPerMonth($budget, $first, $last); while ($first < $last) { - $end = Navigation::addPeriod($first, $range, 0); - $end->subDay(); - $chartDate = clone $end; - $chartDate->startOfMonth(); - $spent = $repository->balanceInPeriod($budget, $first, $end, $accounts) * -1; - $entries->push([$chartDate, $spent]); + $monthFormatted = $first->format('Y-m'); + + $filtered = $set->filter( + function (Budget $obj) use ($monthFormatted) { + return $obj->dateFormatted == $monthFormatted; + } + ); + $spent = is_null($filtered->first()) ? '0' : $filtered->first()->monthlyAmount; + + $entries->push([$first, round(($spent * -1), 2)]); + $first = Navigation::addPeriod($first, $range, 0); } diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 6a06fd533b..a828ede212 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -49,26 +49,12 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn */ public function getExpensesPerDay(Budget $budget, Carbon $start, Carbon $end) { - /* - * select transaction_journals.date, SUM(transactions.amount) as dailyAmount from budgets -left join budget_transaction_journal ON budget_transaction_journal.budget_id = budgets.id -left join transaction_journals ON budget_transaction_journal.transaction_journal_id = transaction_journals.id -left join transactions ON transaction_journals.id = transactions.transaction_journal_id -where - -transaction_journals.date >= "2015-12-01" -and transaction_journals.date <= "2015-12-31" -and budgets.id = 1 -and transactions.amount < 0 -group by transaction_journals.date -order by transaction_journals.date - */ - $set = Auth::user()->budgets() ->leftJoin('budget_transaction_journal', 'budget_transaction_journal.budget_id', '=', 'budgets.id') ->leftJoin('transaction_journals', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->whereNull('transaction_journals.deleted_at') ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) ->where('budgets.id', $budget->id) ->where('transactions.amount', '<', 0) @@ -77,7 +63,39 @@ order by transaction_journals.date ->get(['transaction_journals.date', DB::Raw('SUM(`transactions`.`amount`) as `dailyAmount`')]); return $set; + } + /** + * Returns the expenses for this budget grouped per month, with the date + * in "dateFormatted" (a string, not a Carbon) and the amount in "dailyAmount". + * + * @param Budget $budget + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getExpensesPerMonth(Budget $budget, Carbon $start, Carbon $end) + { + $set = Auth::user()->budgets() + ->leftJoin('budget_transaction_journal', 'budget_transaction_journal.budget_id', '=', 'budgets.id') + ->leftJoin('transaction_journals', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->whereNull('transaction_journals.deleted_at') + ->where('budgets.id', $budget->id) + ->where('transactions.amount', '<', 0) + ->groupBy('dateFormatted') + ->orderBy('transaction_journals.date') + ->get( + [ + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`, "%Y-%m") AS `dateFormatted`'), + DB::Raw('SUM(`transactions`.`amount`) as `monthlyAmount`') + ] + ); + + return $set; } /** diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 11dbcae4c1..c1109188f7 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -32,6 +32,18 @@ interface BudgetRepositoryInterface */ public function getExpensesPerDay(Budget $budget, Carbon $start, Carbon $end); + /** + * Returns the expenses for this budget grouped per month, with the date + * in "date" (a string, not a Carbon) and the amount in "dailyAmount". + * + * @param Budget $budget + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getExpensesPerMonth(Budget $budget, Carbon $start, Carbon $end); + /** * @param Budget $budget * From 0fd0d7d080d99bda06f9afd3da69b17b989b8eac Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 29 Dec 2015 10:08:40 +0100 Subject: [PATCH 07/62] Less queries for category frontpage chart. --- .../Controllers/Chart/CategoryController.php | 1 - .../Category/CategoryRepository.php | 75 ++++++++++++------- 2 files changed, 46 insertions(+), 30 deletions(-) diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 3866463570..c71e2ef579 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -123,7 +123,6 @@ class CategoryController extends Controller $data = $this->generator->frontpage($set); $cache->store($data); - return Response::json($data); } diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index bf8eb047af..3af5b4bff1 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -4,7 +4,6 @@ namespace FireflyIII\Repositories\Category; use Auth; use Carbon\Carbon; -use Crypt; use DB; use FireflyIII\Models\Category; use FireflyIII\Models\TransactionJournal; @@ -137,7 +136,6 @@ class CategoryRepository extends ComponentRepository implements CategoryReposito /** - * * @param Carbon $start * @param Carbon $end * @@ -145,36 +143,55 @@ class CategoryRepository extends ComponentRepository implements CategoryReposito */ public function getCategoriesAndExpenses(Carbon $start, Carbon $end) { - $set = Auth::user()->transactionjournals() - ->leftJoin( - 'category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id' - ) - ->leftJoin('categories', 'categories.id', '=', 'category_transaction_journal.category_id') - ->before($end) - ->where('categories.user_id', Auth::user()->id) - ->after($start) - ->transactionTypes([TransactionType::WITHDRAWAL]) - ->get(['categories.id as category_id', 'categories.encrypted as category_encrypted', 'categories.name', 'transaction_journals.*']); - - bcscale(2); - $result = []; + $set = Auth::user()->categories() + ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id') + ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') + ->leftJoin( + 'transactions', function (JoinClause $join) { + $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0); + } + ) + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->whereIn('transaction_types.type', [TransactionType::WITHDRAWAL]) + ->whereNull('transaction_journals.deleted_at') + ->groupBy('categories.id') + ->orderBy('totalAmount') + ->get( + [ + 'categories.*', + DB::Raw('SUM(`transactions`.`amount`) as `totalAmount`') + ] + ); + $array = []; + /** @var Category $entry */ foreach ($set as $entry) { - $categoryId = intval($entry->category_id); - if (isset($result[$categoryId])) { - $result[$categoryId]['sum'] = bcadd($result[$categoryId]['sum'], $entry->amount); - } else { - $isEncrypted = intval($entry->category_encrypted) === 1 ? true : false; - $name = strlen($entry->name) === 0 ? trans('firefly.no_category') : $entry->name; - $name = $isEncrypted ? Crypt::decrypt($name) : $name; - $result[$categoryId] = [ - 'name' => $name, - 'sum' => $entry->amount, - ]; - - } + $id = $entry->id; + $array[$id] = ['name' => $entry->name, 'sum' => $entry->totalAmount]; } - return $result; + // without category: + $single = Auth::user()->transactionjournals() + ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') + ->leftJoin( + 'transactions', function (JoinClause $join) { + $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0); + } + ) + ->whereNull('category_transaction_journal.id') + ->whereNull('transaction_journals.deleted_at') + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->whereIn('transaction_types.type', [TransactionType::WITHDRAWAL]) + ->whereNull('transaction_journals.deleted_at') + ->first([DB::Raw('SUM(transactions.amount) as `totalAmount`')]); + $noCategory = is_null($single->totalAmount) ? '0' : $single->totalAmount; + $array[0] = ['name' => trans('firefly.no_category'), 'sum' => $noCategory]; + + return $array; + } /** From 35154dc7a32d892da5f0238d2ae9d9e92af2f6c6 Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 29 Dec 2015 18:55:30 +0100 Subject: [PATCH 08/62] Another chart optimised --- .../Controllers/Chart/CategoryController.php | 130 +++++------------- .../Category/CategoryRepository.php | 111 ++++++++++++++- .../Category/CategoryRepositoryInterface.php | 26 ++++ 3 files changed, 172 insertions(+), 95 deletions(-) diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index c71e2ef579..7d6a97b24a 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -304,8 +304,7 @@ class CategoryController extends Controller */ public function earnedInPeriod(CategoryRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) { - $original = clone $start; - $cache = new CacheProperties; // chart properties for cache: + $cache = new CacheProperties; // chart properties for cache: $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($reportType); @@ -315,78 +314,42 @@ class CategoryController extends Controller if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore } - $categories = new Collection; - $sets = new Collection; - $entries = new Collection; - // run a very special query each month: - $start = clone $original; - while ($start < $end) { - $currentEnd = clone $start; - $currentStart = clone $start; - $currentStart->startOfMonth(); - $currentEnd->endOfMonth(); - // get a list of categories, and what the user has earned for that category - // (if the user has earned anything) - $set = $repository->earnedForAccounts($accounts, $currentStart, $currentEnd); - $categories = $categories->merge($set); - // save the set combined with the data that is in it: - // for example: - // december 2015, salary:1000, bonus:200 - $sets->push([$currentStart, $set]); - $start->addMonth(); - } - // filter categories into a single bunch. Useful later on. - // $categories contains all the categories the user has earned money - // in in this period. - $categories = $categories->unique('id'); - $categories = $categories->sortBy( + $set = $repository->earnedForAccountsPerMonth($accounts, $start, $end); + $categories = $set->unique('id')->sortBy( function (Category $category) { return $category->name; } ); + $entries = new Collection; - // start looping the time again, this time processing the - // data for each month. - $start = clone $original; - while ($start < $end) { - $currentEnd = clone $start; - $currentStart = clone $start; - $currentStart->startOfMonth(); - $currentEnd->endOfMonth(); - - // in $sets we have saved all the sets of data for each month - // so now we need to retrieve the corrent one. - // match is on date of course. - $currentSet = $sets->first( - function ($key, $value) use ($currentStart) { - // set for this date. - return ($value[0] == $currentStart); + while ($start < $end) { // filter the set: + $row = [clone $start]; + // get possibly relevant entries from the big $set + $currentSet = $set->filter( + function (Category $category) use ($start) { + return $category->dateFormatted == $start->format("Y-m"); } ); - // create a row used later on. - $row = [clone $currentStart]; - - // loop all categories: + // check for each category if its in the current set. /** @var Category $category */ foreach ($categories as $category) { - // if entry is not null, we've earned money in this period for this category. - $entry = $currentSet[1]->first( - function ($key, $value) use ($category) { - return $value->id == $category->id; + // if its in there, use the value. + $entry = $currentSet->filter( + function (Category $cat) use ($category) { + return ($cat->id == $category->id); } - ); - // save amount + )->first(); if (!is_null($entry)) { - $row[] = $entry->earned; + $row[] = round($entry->earned, 2); } else { $row[] = 0; } } + $entries->push($row); $start->addMonth(); } - $data = $this->generator->earnedInPeriod($categories, $entries); $cache->store($data); @@ -408,8 +371,7 @@ class CategoryController extends Controller */ public function spentInPeriod(CategoryRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) { - $original = clone $start; - $cache = new CacheProperties; // chart properties for cache: + $cache = new CacheProperties; // chart properties for cache: $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($reportType); @@ -419,66 +381,46 @@ class CategoryController extends Controller if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore } - $categories = new Collection; - $sets = new Collection; - $entries = new Collection; - // run a very special query each month: - $start = clone $original; - while ($start < $end) { - $currentEnd = clone $start; - $currentStart = clone $start; - $currentStart->startOfMonth(); - $currentEnd->endOfMonth(); - $set = $repository->spentForAccounts($accounts, $currentStart, $currentEnd); - $categories = $categories->merge($set); - $sets->push([$currentStart, $set]); - $start->addMonth(); - } - $categories = $categories->unique('id'); - $categories = $categories->sortBy( + $set = $repository->spentForAccountsPerMonth($accounts, $start, $end); + $categories = $set->unique('id')->sortBy( function (Category $category) { return $category->name; } ); + $entries = new Collection; - $start = clone $original; - while ($start < $end) { - $currentEnd = clone $start; - $currentStart = clone $start; - $currentStart->startOfMonth(); - $currentEnd->endOfMonth(); - $currentSet = $sets->first( - function ($key, $value) use ($currentStart) { - // set for this date. - return ($value[0] == $currentStart); + while ($start < $end) { // filter the set: + $row = [clone $start]; + // get possibly relevant entries from the big $set + $currentSet = $set->filter( + function (Category $category) use ($start) { + return $category->dateFormatted == $start->format("Y-m"); } ); - $row = [clone $currentStart]; - + // check for each category if its in the current set. /** @var Category $category */ foreach ($categories as $category) { - /** @var Category $entry */ - $entry = $currentSet[1]->first( - function ($key, $value) use ($category) { - return $value->id == $category->id; + // if its in there, use the value. + $entry = $currentSet->filter( + function (Category $cat) use ($category) { + return ($cat->id == $category->id); } - ); + )->first(); if (!is_null($entry)) { - $row[] = $entry->spent; + $row[] = round(($entry->spent * -1), 2); } else { $row[] = 0; } } + $entries->push($row); $start->addMonth(); } - $data = $this->generator->spentInPeriod($categories, $entries); $cache->store($data); return $data; - } } diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index 3af5b4bff1..e97bcb2dff 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -531,6 +531,61 @@ class CategoryRepository extends ComponentRepository implements CategoryReposito } + /** + * Returns a collection of Categories appended with the amount of money that has been earned + * in these categories, based on the $accounts involved, in period X, grouped per month. + * The amount earned in category X in period X is saved in field "earned". + * + * @param $accounts + * @param $start + * @param $end + * + * @return Collection + */ + public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end) + { + $accountIds = []; + foreach ($accounts as $account) { + $accountIds[] = $account->id; + } + + + $collection = Auth::user()->categories() + ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id') + ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') + ->leftJoin( + 'transactions AS t_src', function (JoinClause $join) { + $join->on('t_src.transaction_journal_id', '=', 'transaction_journals.id')->where('t_src.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions AS t_dest', function (JoinClause $join) { + $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0); + } + ) + ->whereIn('t_dest.account_id', $accountIds)// to these accounts (earned) + ->whereNotIn('t_src.account_id', $accountIds)//-- but not from these accounts + ->whereIn( + 'transaction_types.type', [TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE] + ) + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->groupBy('categories.id') + ->groupBy('dateFormatted') + ->get( + [ + 'categories.*', + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") as `dateFormatted`'), + DB::Raw('SUM(`t_dest`.`amount`) AS `earned`') + ] + ); + + return $collection; + + + } + /** * Returns a collection of Categories appended with the amount of money that has been earned * in these categories, based on the $accounts involved, in period X. @@ -568,7 +623,7 @@ class CategoryRepository extends ComponentRepository implements CategoryReposito ->whereNotIn('t_src.account_id', $accountIds)//-- but not from these accounts ->whereIn( 'transaction_types.type', [TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE] - )// earned from these things. + ) ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) ->groupBy('categories.id') @@ -624,4 +679,58 @@ class CategoryRepository extends ComponentRepository implements CategoryReposito return $collection; } + + /** + * Returns a collection of Categories appended with the amount of money that has been spent + * in these categories, based on the $accounts involved, in period X, grouped per month. + * The amount earned in category X in period X is saved in field "spent". + * + * @param $accounts + * @param $start + * @param $end + * + * @return Collection + */ + public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end) + { + $accountIds = []; + foreach ($accounts as $account) { + $accountIds[] = $account->id; + } + + + $collection = Auth::user()->categories() + ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id') + ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') + ->leftJoin( + 'transactions AS t_src', function (JoinClause $join) { + $join->on('t_src.transaction_journal_id', '=', 'transaction_journals.id')->where('t_src.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions AS t_dest', function (JoinClause $join) { + $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0); + } + ) + ->whereIn('t_src.account_id', $accountIds)// from these accounts (spent) + ->whereNotIn('t_dest.account_id', $accountIds)//-- but not from these accounts (spent internally) + ->whereIn( + 'transaction_types.type', [TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE] + )// spent on these things. + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->groupBy('categories.id') + ->groupBy('dateFormatted') + ->get( + [ + 'categories.*', + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") as `dateFormatted`'), + DB::Raw('SUM(`t_src`.`amount`) AS `spent`') + ] + ); + + return $collection; + } + } diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index 34553e7ea3..a3d82b8db4 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -63,6 +63,32 @@ interface CategoryRepositoryInterface */ public function spentForAccounts(Collection $accounts, Carbon $start, Carbon $end); + /** + * Returns a collection of Categories appended with the amount of money that has been spent + * in these categories, based on the $accounts involved, in period X, grouped per month. + * The amount earned in category X in period X is saved in field "spent". + * + * @param $accounts + * @param $start + * @param $end + * + * @return Collection + */ + public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); + + /** + * Returns a collection of Categories appended with the amount of money that has been earned + * in these categories, based on the $accounts involved, in period X, grouped per month. + * The amount earned in category X in period X is saved in field "earned". + * + * @param $accounts + * @param $start + * @param $end + * + * @return Collection + */ + public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); + /** * @return Collection */ From 95f4a83f41a2fd81e12804e06c9b96f454eec570 Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 29 Dec 2015 22:44:13 +0100 Subject: [PATCH 09/62] Split category repository into two repositories. One for database calls for single categories, the other pertaining all categories. --- app/Helpers/Report/ReportHelper.php | 6 +- app/Http/Controllers/CategoryController.php | 32 +- .../Controllers/Chart/CategoryController.php | 26 +- .../Category/CategoryRepository.php | 343 +----------------- .../Category/CategoryRepositoryInterface.php | 161 -------- .../Category/SingleCategoryRepository.php | 337 +++++++++++++++++ .../SingleCategoryRepositoryInterface.php | 166 +++++++++ 7 files changed, 542 insertions(+), 529 deletions(-) create mode 100644 app/Repositories/Category/SingleCategoryRepository.php create mode 100644 app/Repositories/Category/SingleCategoryRepositoryInterface.php diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 43349c78a1..22765419d5 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -61,9 +61,13 @@ class ReportHelper implements ReportHelperInterface */ /** @var \FireflyIII\Repositories\Category\CategoryRepositoryInterface $repository */ $repository = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface'); + + /** @var \FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface $singleRepository */ + $singleRepository = app('FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface'); + $set = $repository->getCategories(); foreach ($set as $category) { - $spent = $repository->balanceInPeriod($category, $start, $end, $accounts); + $spent = $singleRepository->balanceInPeriod($category, $start, $end, $accounts); $category->spent = $spent; $object->addCategory($category); } diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php index 04ef878492..d878afa9aa 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryController.php @@ -5,6 +5,7 @@ use Carbon\Carbon; use FireflyIII\Http\Requests\CategoryFormRequest; use FireflyIII\Models\Category; use FireflyIII\Repositories\Category\CategoryRepositoryInterface; +use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface; use FireflyIII\Support\CacheProperties; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; @@ -68,12 +69,12 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository - * @param Category $category + * @param SingleCategoryRepositoryInterface $repository + * @param Category $category * * @return \Illuminate\Http\RedirectResponse */ - public function destroy(CategoryRepositoryInterface $repository, Category $category) + public function destroy(SingleCategoryRepositoryInterface $repository, Category $category) { $name = $category->name; @@ -107,17 +108,18 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository + * @param CategoryRepositoryInterface $repository + * @param SingleCategoryRepositoryInterface $singleRepository * * @return \Illuminate\View\View */ - public function index(CategoryRepositoryInterface $repository) + public function index(CategoryRepositoryInterface $repository, SingleCategoryRepositoryInterface $singleRepository) { $categories = $repository->getCategories(); $categories->each( - function (Category $category) use ($repository) { - $category->lastActivity = $repository->getLatestActivity($category); + function (Category $category) use ($singleRepository) { + $category->lastActivity = $singleRepository->getLatestActivity($category); } ); @@ -143,14 +145,14 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository + * @param SingleCategoryRepositoryInterface $repository * @param Category $category * * @param $date * * @return \Illuminate\View\View */ - public function showWithDate(CategoryRepositoryInterface $repository, Category $category, $date) + public function showWithDate(SingleCategoryRepositoryInterface $repository, Category $category, $date) { $carbon = new Carbon($date); $range = Preferences::get('viewRange', '1M')->data; @@ -170,12 +172,12 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository + * @param SingleCategoryRepositoryInterface $repository * @param Category $category * * @return \Illuminate\View\View */ - public function show(CategoryRepositoryInterface $repository, Category $category) + public function show(SingleCategoryRepositoryInterface $repository, Category $category) { $hideCategory = true; // used in list. $page = intval(Input::get('page')); @@ -226,11 +228,11 @@ class CategoryController extends Controller /** * @param CategoryFormRequest $request - * @param CategoryRepositoryInterface $repository + * @param SingleCategoryRepositoryInterface $repository * * @return \Illuminate\Http\RedirectResponse */ - public function store(CategoryFormRequest $request, CategoryRepositoryInterface $repository) + public function store(CategoryFormRequest $request, SingleCategoryRepositoryInterface $repository) { $categoryData = [ 'name' => $request->input('name'), @@ -253,12 +255,12 @@ class CategoryController extends Controller /** * @param CategoryFormRequest $request - * @param CategoryRepositoryInterface $repository + * @param SingleCategoryRepositoryInterface $repository * @param Category $category * * @return \Illuminate\Http\RedirectResponse */ - public function update(CategoryFormRequest $request, CategoryRepositoryInterface $repository, Category $category) + public function update(CategoryFormRequest $request, SingleCategoryRepositoryInterface $repository, Category $category) { $categoryData = [ 'name' => $request->input('name'), diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 7d6a97b24a..08f5116adb 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -7,6 +7,7 @@ use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Category; use FireflyIII\Repositories\Category\CategoryRepositoryInterface; +use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; use Navigation; @@ -38,12 +39,12 @@ class CategoryController extends Controller /** * Show an overview for a category for all time, per month/week/year. * - * @param CategoryRepositoryInterface $repository - * @param Category $category + * @param SingleCategoryRepositoryInterface $repository + * @param Category $category * * @return \Symfony\Component\HttpFoundation\Response */ - public function all(CategoryRepositoryInterface $repository, Category $category) + public function all(SingleCategoryRepositoryInterface $repository, Category $category) { // oldest transaction in category: $start = $repository->getFirstActivityDate($category); @@ -137,8 +138,13 @@ class CategoryController extends Controller * * @return \Illuminate\Http\JsonResponse */ - public function multiYear(CategoryRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts, Collection $categories) + public function multiYear($reportType, Carbon $start, Carbon $end, Collection $accounts, Collection $categories) { + /** @var CategoryRepositoryInterface $repository */ + $repository = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface'); + /** @var SingleCategoryRepositoryInterface $singleRepository */ + $singleRepository = app('FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface'); + // chart properties for cache: $cache = new CacheProperties(); $cache->addProperty($reportType); @@ -180,8 +186,8 @@ class CategoryController extends Controller $earned = $repository->earnedNoCategoryForAccounts($accounts, $currentStart, $currentEnd); } else { $name = $category->name; - $spent = $repository->spentInPeriodForAccounts($category, $accounts, $currentStart, $currentEnd); - $earned = $repository->earnedInPeriodForAccounts($category, $accounts, $currentStart, $currentEnd); + $spent = $singleRepository->spentInPeriodForAccounts($category, $accounts, $currentStart, $currentEnd); + $earned = $singleRepository->earnedInPeriodForAccounts($category, $accounts, $currentStart, $currentEnd); } // save to array: @@ -206,12 +212,12 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository + * @param SingleCategoryRepositoryInterface $repository * @param Category $category * * @return \Symfony\Component\HttpFoundation\Response */ - public function currentPeriod(CategoryRepositoryInterface $repository, Category $category) + public function currentPeriod(SingleCategoryRepositoryInterface $repository, Category $category) { $start = clone Session::get('start', Carbon::now()->startOfMonth()); $end = Session::get('end', Carbon::now()->endOfMonth()); @@ -246,14 +252,14 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository + * @param SingleCategoryRepositoryInterface $repository * @param Category $category * * @param $date * * @return \Symfony\Component\HttpFoundation\Response */ - public function specificPeriod(CategoryRepositoryInterface $repository, Category $category, $date) + public function specificPeriod(SingleCategoryRepositoryInterface $repository, Category $category, $date) { $carbon = new Carbon($date); $range = Preferences::get('viewRange', '1M')->data; diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index e97bcb2dff..8ccc840780 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -6,9 +6,7 @@ use Auth; use Carbon\Carbon; use DB; use FireflyIII\Models\Category; -use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; -use FireflyIII\Repositories\Shared\ComponentRepository; use FireflyIII\Support\CacheProperties; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; @@ -18,32 +16,9 @@ use Illuminate\Support\Collection; * * @package FireflyIII\Repositories\Category */ -class CategoryRepository extends ComponentRepository implements CategoryRepositoryInterface +class CategoryRepository implements CategoryRepositoryInterface { - /** - * @param Category $category - * - * @return int - */ - public function countJournals(Category $category) - { - return $category->transactionJournals()->count(); - - } - - /** - * @param Category $category - * - * @return boolean - */ - public function destroy(Category $category) - { - $category->delete(); - - return true; - } - /** * @return Collection */ @@ -194,62 +169,6 @@ class CategoryRepository extends ComponentRepository implements CategoryReposito } - /** - * @param Category $category - * - * @return Carbon - */ - public function getFirstActivityDate(Category $category) - { - /** @var TransactionJournal $first */ - $first = $category->transactionjournals()->orderBy('date', 'ASC')->first(); - if ($first) { - return $first->date; - } - - return new Carbon; - - } - - /** - * @param Category $category - * @param int $page - * - * @return Collection - */ - public function getJournals(Category $category, $page) - { - $offset = $page > 0 ? $page * 50 : 0; - - return $category->transactionJournals()->withRelevantData()->take(50)->offset($offset) - ->orderBy('transaction_journals.date', 'DESC') - ->orderBy('transaction_journals.order', 'ASC') - ->orderBy('transaction_journals.id', 'DESC') - ->get( - ['transaction_journals.*'] - ); - - } - - /** - * @param Category $category - * - * @return Carbon|null - */ - public function getLatestActivity(Category $category) - { - $latest = $category->transactionjournals() - ->orderBy('transaction_journals.date', 'DESC') - ->orderBy('transaction_journals.order', 'ASC') - ->orderBy('transaction_journals.id', 'DESC') - ->first(); - if ($latest) { - return $latest->date; - } - - return null; - } - /** * @param Carbon $start * @param Carbon $end @@ -270,266 +189,6 @@ class CategoryRepository extends ComponentRepository implements CategoryReposito ->get(['transaction_journals.*']); } - /** - * @param Category $category - * @param Carbon $start - * @param Carbon $end - * @param Collection $accounts - * - * @return string - */ - public function balanceInPeriod(Category $category, Carbon $start, Carbon $end, Collection $accounts) - { - return $this->commonBalanceInPeriod($category, $start, $end, $accounts); - } - - /** - * Corrected for tags - * - * @param Category $category - * @param Carbon $date - * - * @return string - */ - public function spentOnDaySum(Category $category, Carbon $date) - { - return $category->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->onDate($date)->get(['transaction_journals.*'])->sum('amount'); - } - - /** - * @param array $data - * - * @return Category - */ - public function store(array $data) - { - $newCategory = new Category( - [ - 'user_id' => $data['user'], - 'name' => $data['name'], - ] - ); - $newCategory->save(); - - return $newCategory; - } - - /** - * @param Category $category - * @param array $data - * - * @return Category - */ - public function update(Category $category, array $data) - { - // update the account: - $category->name = $data['name']; - $category->save(); - - return $category; - } - - /** - * @deprecated - * This method returns the sum of the journals in the category, optionally - * limited by a start or end date. - * - * @param Category $category - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function journalsSum(Category $category, Carbon $start = null, Carbon $end = null) - { - $query = $category->transactionJournals() - ->orderBy('transaction_journals.date', 'DESC') - ->orderBy('transaction_journals.order', 'ASC') - ->orderBy('transaction_journals.id', 'DESC'); - if (!is_null($start)) { - $query->after($start); - } - - if (!is_null($end)) { - $query->before($end); - } - - return $query->get(['transaction_journals.*'])->sum('amount'); - - } - - /** - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * - * @return string - */ - public function spentInPeriod(Category $category, Carbon $start, Carbon $end) - { - $cache = new CacheProperties; // we must cache this. - $cache->addProperty($category->id); - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty('spentInPeriod'); - - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - - $sum = $category->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->before($end)->after($start)->get(['transaction_journals.*']) - ->sum( - 'amount' - ); - - $cache->store($sum); - - return $sum; - } - - /** - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * - * @return string - */ - public function earnedInPeriod(Category $category, Carbon $start, Carbon $end) - { - $cache = new CacheProperties; // we must cache this. - $cache->addProperty($category->id); - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty('earnedInPeriod'); - - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - - $sum = $category->transactionjournals()->transactionTypes([TransactionType::DEPOSIT])->before($end)->after($start)->get(['transaction_journals.*']) - ->sum( - 'amount' - ); - - $cache->store($sum); - - return $sum; - } - - - /** - * @param Category $category - * @param int $page - * @param Carbon $start - * @param Carbon $end - * - * @return mixed - */ - public function getJournalsInRange(Category $category, $page, Carbon $start, Carbon $end) - { - $offset = $page > 0 ? $page * 50 : 0; - - return $category->transactionJournals() - ->after($start) - ->before($end) - ->withRelevantData()->take(50)->offset($offset) - ->orderBy('transaction_journals.date', 'DESC') - ->orderBy('transaction_journals.order', 'ASC') - ->orderBy('transaction_journals.id', 'DESC') - ->get( - ['transaction_journals.*'] - ); - } - - /** - * @param Category $category - * - * @param Carbon $start - * @param Carbon $end - * - * @return int - */ - public function countJournalsInRange(Category $category, Carbon $start, Carbon $end) - { - return $category->transactionJournals()->before($end)->after($start)->count(); - } - - /** - * - * Corrected for tags. - * - * @param Category $category - * @param Carbon $date - * - * @return float - */ - public function earnedOnDaySum(Category $category, Carbon $date) - { - return $category->transactionjournals()->transactionTypes([TransactionType::DEPOSIT])->onDate($date)->get(['transaction_journals.*'])->sum('amount'); - } - - /** - * Calculates how much is spent in this period. - * - * @param Category $category - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function spentInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end) - { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - - $sum - = $category - ->transactionjournals() - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->after($start) - ->before($end) - ->whereIn('transactions.account_id', $accountIds) - ->transactionTypes([TransactionType::WITHDRAWAL]) - ->get(['transaction_journals.*']) - ->sum('amount'); - - return $sum; - - } - - /** - * Calculate how much is earned in this period. - * - * @param Category $category - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function earnedInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end) - { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - $sum - = $category - ->transactionjournals() - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->before($end) - ->whereIn('transactions.account_id', $accountIds) - ->transactionTypes([TransactionType::DEPOSIT]) - ->after($start) - ->get(['transaction_journals.*']) - ->sum('amount'); - - return $sum; - - } /** * Returns a collection of Categories appended with the amount of money that has been earned diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index a3d82b8db4..9878738d75 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -13,29 +13,6 @@ use Illuminate\Support\Collection; */ interface CategoryRepositoryInterface { - /** - * @param Category $category - * - * @return int - */ - public function countJournals(Category $category); - - /** - * @param Category $category - * - * @param Carbon $start - * @param Carbon $end - * - * @return int - */ - public function countJournalsInRange(Category $category, Carbon $start, Carbon $end); - - /** - * @param Category $category - * - * @return boolean - */ - public function destroy(Category $category); /** * Returns a collection of Categories appended with the amount of money that has been earned @@ -94,31 +71,6 @@ interface CategoryRepositoryInterface */ public function getCategories(); - - /** - * Calculates how much is spent in this period. - * - * @param Category $category - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function spentInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end); - - /** - * Calculate how much is earned in this period. - * - * @param Category $category - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function earnedInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end); - /** * Returns the amount spent without category by accounts in period. * @@ -151,52 +103,6 @@ interface CategoryRepositoryInterface */ public function getCategoriesAndExpenses(Carbon $start, Carbon $end); - /** - * @param Category $category - * - * @return Carbon - */ - public function getFirstActivityDate(Category $category); - - /** - * @param Category $category - * @param int $page - * - * @return Collection - */ - public function getJournals(Category $category, $page); - - /** - * @param Category $category - * @param int $page - * - * @param Carbon $start - * @param Carbon $end - * - * @return Collection - */ - public function getJournalsInRange(Category $category, $page, Carbon $start, Carbon $end); - - /** - * @deprecated - * This method returns the sum of the journals in the category, optionally - * limited by a start or end date. - * - * @param Category $category - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function journalsSum(Category $category, Carbon $start = null, Carbon $end = null); - - /** - * @param Category $category - * - * @return Carbon|null - */ - public function getLatestActivity(Category $category); - /** * @param Carbon $start * @param Carbon $end @@ -205,71 +111,4 @@ interface CategoryRepositoryInterface */ public function getWithoutCategory(Carbon $start, Carbon $end); - /** - * Corrected for tags and list of accounts. - * - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * @param Collection $accounts - * - * @return string - */ - public function balanceInPeriod(Category $category, Carbon $start, Carbon $end, Collection $accounts); - - /** - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * - * @return string - */ - public function spentInPeriod(Category $category, Carbon $start, Carbon $end); - - /** - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * - * @return string - */ - public function earnedInPeriod(Category $category, Carbon $start, Carbon $end); - - /** - * - * Corrected for tags. - * - * @param Category $category - * @param Carbon $date - * - * @return float - */ - public function spentOnDaySum(Category $category, Carbon $date); - - /** - * - * Corrected for tags. - * - * @param Category $category - * @param Carbon $date - * - * @return float - */ - public function earnedOnDaySum(Category $category, Carbon $date); - - /** - * @param array $data - * - * @return Category - */ - public function store(array $data); - - /** - * @param Category $category - * @param array $data - * - * @return Category - */ - public function update(Category $category, array $data); - } diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php new file mode 100644 index 0000000000..5c115c9ce1 --- /dev/null +++ b/app/Repositories/Category/SingleCategoryRepository.php @@ -0,0 +1,337 @@ +commonBalanceInPeriod($category, $start, $end, $accounts); + } + + + /** + * @param Category $category + * + * @return int + */ + public function countJournals(Category $category) + { + return $category->transactionJournals()->count(); + + } + + /** + * @param Category $category + * + * @param Carbon $start + * @param Carbon $end + * + * @return int + */ + public function countJournalsInRange(Category $category, Carbon $start, Carbon $end) + { + return $category->transactionJournals()->before($end)->after($start)->count(); + } + + /** + * @param Category $category + * + * @return boolean + */ + public function destroy(Category $category) + { + $category->delete(); + + return true; + } + + /** + * @param Category $category + * @param \Carbon\Carbon $start + * @param \Carbon\Carbon $end + * + * @return string + */ + public function earnedInPeriod(Category $category, Carbon $start, Carbon $end) + { + $cache = new CacheProperties; // we must cache this. + $cache->addProperty($category->id); + $cache->addProperty($start); + $cache->addProperty($end); + $cache->addProperty('earnedInPeriod'); + + if ($cache->has()) { + return $cache->get(); // @codeCoverageIgnore + } + + $sum = $category->transactionjournals()->transactionTypes([TransactionType::DEPOSIT])->before($end)->after($start)->get(['transaction_journals.*']) + ->sum( + 'amount' + ); + + $cache->store($sum); + + return $sum; + } + + + /** + * Calculate how much is earned in this period. + * + * @param Category $category + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return string + */ + public function earnedInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end) + { + $accountIds = []; + foreach ($accounts as $account) { + $accountIds[] = $account->id; + } + $sum + = $category + ->transactionjournals() + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->before($end) + ->whereIn('transactions.account_id', $accountIds) + ->transactionTypes([TransactionType::DEPOSIT]) + ->after($start) + ->get(['transaction_journals.*']) + ->sum('amount'); + + return $sum; + + } + + /** + * + * Corrected for tags. + * + * @param Category $category + * @param Carbon $date + * + * @return float + */ + public function earnedOnDaySum(Category $category, Carbon $date) + { + return $category->transactionjournals()->transactionTypes([TransactionType::DEPOSIT])->onDate($date)->get(['transaction_journals.*'])->sum('amount'); + } + + /** + * @param Category $category + * + * @return Carbon + */ + public function getFirstActivityDate(Category $category) + { + /** @var TransactionJournal $first */ + $first = $category->transactionjournals()->orderBy('date', 'ASC')->first(); + if ($first) { + return $first->date; + } + + return new Carbon; + + } + + /** + * @param Category $category + * @param int $page + * + * @return Collection + */ + public function getJournals(Category $category, $page) + { + $offset = $page > 0 ? $page * 50 : 0; + + return $category->transactionJournals()->withRelevantData()->take(50)->offset($offset) + ->orderBy('transaction_journals.date', 'DESC') + ->orderBy('transaction_journals.order', 'ASC') + ->orderBy('transaction_journals.id', 'DESC') + ->get( + ['transaction_journals.*'] + ); + + } + + /** + * @param Category $category + * @param int $page + * @param Carbon $start + * @param Carbon $end + * + * @return mixed + */ + public function getJournalsInRange(Category $category, $page, Carbon $start, Carbon $end) + { + $offset = $page > 0 ? $page * 50 : 0; + + return $category->transactionJournals() + ->after($start) + ->before($end) + ->withRelevantData()->take(50)->offset($offset) + ->orderBy('transaction_journals.date', 'DESC') + ->orderBy('transaction_journals.order', 'ASC') + ->orderBy('transaction_journals.id', 'DESC') + ->get( + ['transaction_journals.*'] + ); + } + + + /** + * @param Category $category + * + * @return Carbon|null + */ + public function getLatestActivity(Category $category) + { + $latest = $category->transactionjournals() + ->orderBy('transaction_journals.date', 'DESC') + ->orderBy('transaction_journals.order', 'ASC') + ->orderBy('transaction_journals.id', 'DESC') + ->first(); + if ($latest) { + return $latest->date; + } + + return null; + } + + + /** + * Calculates how much is spent in this period. + * + * @param Category $category + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return string + */ + public function spentInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end) + { + $accountIds = []; + foreach ($accounts as $account) { + $accountIds[] = $account->id; + } + + $sum + = $category + ->transactionjournals() + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->after($start) + ->before($end) + ->whereIn('transactions.account_id', $accountIds) + ->transactionTypes([TransactionType::WITHDRAWAL]) + ->get(['transaction_journals.*']) + ->sum('amount'); + + return $sum; + + } + + /** + * @param Category $category + * @param \Carbon\Carbon $start + * @param \Carbon\Carbon $end + * + * @return string + */ + public function spentInPeriod(Category $category, Carbon $start, Carbon $end) + { + $cache = new CacheProperties; // we must cache this. + $cache->addProperty($category->id); + $cache->addProperty($start); + $cache->addProperty($end); + $cache->addProperty('spentInPeriod'); + + if ($cache->has()) { + return $cache->get(); // @codeCoverageIgnore + } + + $sum = $category->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->before($end)->after($start)->get(['transaction_journals.*']) + ->sum( + 'amount' + ); + + $cache->store($sum); + + return $sum; + } + + + /** + * Corrected for tags + * + * @param Category $category + * @param Carbon $date + * + * @return string + */ + public function spentOnDaySum(Category $category, Carbon $date) + { + return $category->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->onDate($date)->get(['transaction_journals.*'])->sum('amount'); + } + + /** + * @param array $data + * + * @return Category + */ + public function store(array $data) + { + $newCategory = new Category( + [ + 'user_id' => $data['user'], + 'name' => $data['name'], + ] + ); + $newCategory->save(); + + return $newCategory; + } + + /** + * @param Category $category + * @param array $data + * + * @return Category + */ + public function update(Category $category, array $data) + { + // update the account: + $category->name = $data['name']; + $category->save(); + + return $category; + } + + +} \ No newline at end of file diff --git a/app/Repositories/Category/SingleCategoryRepositoryInterface.php b/app/Repositories/Category/SingleCategoryRepositoryInterface.php new file mode 100644 index 0000000000..c23784e51d --- /dev/null +++ b/app/Repositories/Category/SingleCategoryRepositoryInterface.php @@ -0,0 +1,166 @@ + Date: Tue, 29 Dec 2015 22:48:55 +0100 Subject: [PATCH 10/62] Some cleaning up. --- .../Csv/Specifix/RabobankDescription.php | 32 +++---- app/Helpers/Report/ReportHelper.php | 2 +- .../Controllers/Auth/PasswordController.php | 1 + app/Http/Controllers/CategoryController.php | 48 +++++----- .../Controllers/Chart/CategoryController.php | 32 +++---- app/Http/Controllers/JsonController.php | 8 +- app/Http/Controllers/ReportController.php | 6 +- app/Models/PiggyBankEvent.php | 2 +- .../Category/CategoryRepositoryInterface.php | 95 +++++++++---------- .../SingleCategoryRepositoryInterface.php | 1 - app/Support/Steam.php | 1 + 11 files changed, 114 insertions(+), 114 deletions(-) diff --git a/app/Helpers/Csv/Specifix/RabobankDescription.php b/app/Helpers/Csv/Specifix/RabobankDescription.php index 19304f16db..426688d758 100644 --- a/app/Helpers/Csv/Specifix/RabobankDescription.php +++ b/app/Helpers/Csv/Specifix/RabobankDescription.php @@ -29,6 +29,22 @@ class RabobankDescription } + /** + * @param array $data + */ + public function setData($data) + { + $this->data = $data; + } + + /** + * @param array $row + */ + public function setRow($row) + { + $this->row = $row; + } + /** * Fixes Rabobank specific thing. */ @@ -46,21 +62,5 @@ class RabobankDescription } - /** - * @param array $data - */ - public function setData($data) - { - $this->data = $data; - } - - /** - * @param array $row - */ - public function setRow($row) - { - $this->row = $row; - } - } diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 22765419d5..084cd6ed3e 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -65,7 +65,7 @@ class ReportHelper implements ReportHelperInterface /** @var \FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface $singleRepository */ $singleRepository = app('FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface'); - $set = $repository->getCategories(); + $set = $repository->getCategories(); foreach ($set as $category) { $spent = $singleRepository->balanceInPeriod($category, $start, $end, $accounts); $category->spent = $spent; diff --git a/app/Http/Controllers/Auth/PasswordController.php b/app/Http/Controllers/Auth/PasswordController.php index 93eda589b0..72944e31f1 100644 --- a/app/Http/Controllers/Auth/PasswordController.php +++ b/app/Http/Controllers/Auth/PasswordController.php @@ -78,6 +78,7 @@ class PasswordController extends Controller } abort(404); + return ''; } diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php index d878afa9aa..4257e86e58 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryController.php @@ -4,8 +4,8 @@ use Auth; use Carbon\Carbon; use FireflyIII\Http\Requests\CategoryFormRequest; use FireflyIII\Models\Category; -use FireflyIII\Repositories\Category\CategoryRepositoryInterface; -use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface; +use FireflyIII\Repositories\Category\CategoryRepositoryInterface as CRI; +use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface as SCRI; use FireflyIII\Support\CacheProperties; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; @@ -69,12 +69,12 @@ class CategoryController extends Controller } /** - * @param SingleCategoryRepositoryInterface $repository - * @param Category $category + * @param SCRI $repository + * @param Category $category * * @return \Illuminate\Http\RedirectResponse */ - public function destroy(SingleCategoryRepositoryInterface $repository, Category $category) + public function destroy(SCRI $repository, Category $category) { $name = $category->name; @@ -108,12 +108,12 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository - * @param SingleCategoryRepositoryInterface $singleRepository + * @param CRI $repository + * @param SCRI $singleRepository * * @return \Illuminate\View\View */ - public function index(CategoryRepositoryInterface $repository, SingleCategoryRepositoryInterface $singleRepository) + public function index(CRI $repository, SCRI $singleRepository) { $categories = $repository->getCategories(); @@ -127,11 +127,11 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository + * @param CRI $repository * * @return \Illuminate\View\View */ - public function noCategory(CategoryRepositoryInterface $repository) + public function noCategory(CRI $repository) { $start = Session::get('start', Carbon::now()->startOfMonth()); $end = Session::get('end', Carbon::now()->startOfMonth()); @@ -145,14 +145,14 @@ class CategoryController extends Controller } /** - * @param SingleCategoryRepositoryInterface $repository - * @param Category $category + * @param SCRI $repository + * @param Category $category * - * @param $date + * @param $date * * @return \Illuminate\View\View */ - public function showWithDate(SingleCategoryRepositoryInterface $repository, Category $category, $date) + public function showWithDate(SCRI $repository, Category $category, $date) { $carbon = new Carbon($date); $range = Preferences::get('viewRange', '1M')->data; @@ -172,12 +172,12 @@ class CategoryController extends Controller } /** - * @param SingleCategoryRepositoryInterface $repository - * @param Category $category + * @param SCRI $repository + * @param Category $category * * @return \Illuminate\View\View */ - public function show(SingleCategoryRepositoryInterface $repository, Category $category) + public function show(SCRI $repository, Category $category) { $hideCategory = true; // used in list. $page = intval(Input::get('page')); @@ -227,12 +227,12 @@ class CategoryController extends Controller } /** - * @param CategoryFormRequest $request - * @param SingleCategoryRepositoryInterface $repository + * @param CategoryFormRequest $request + * @param SCRI $repository * * @return \Illuminate\Http\RedirectResponse */ - public function store(CategoryFormRequest $request, SingleCategoryRepositoryInterface $repository) + public function store(CategoryFormRequest $request, SCRI $repository) { $categoryData = [ 'name' => $request->input('name'), @@ -254,13 +254,13 @@ class CategoryController extends Controller /** - * @param CategoryFormRequest $request - * @param SingleCategoryRepositoryInterface $repository - * @param Category $category + * @param CategoryFormRequest $request + * @param SCRI $repository + * @param Category $category * * @return \Illuminate\Http\RedirectResponse */ - public function update(CategoryFormRequest $request, SingleCategoryRepositoryInterface $repository, Category $category) + public function update(CategoryFormRequest $request, SCRI $repository, Category $category) { $categoryData = [ 'name' => $request->input('name'), diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 08f5116adb..6a96bc5bdc 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -6,8 +6,8 @@ namespace FireflyIII\Http\Controllers\Chart; use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Category; -use FireflyIII\Repositories\Category\CategoryRepositoryInterface; -use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface; +use FireflyIII\Repositories\Category\CategoryRepositoryInterface as CRI; +use FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface as SCRI; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; use Navigation; @@ -39,12 +39,12 @@ class CategoryController extends Controller /** * Show an overview for a category for all time, per month/week/year. * - * @param SingleCategoryRepositoryInterface $repository - * @param Category $category + * @param SCRI $repository + * @param Category $category * * @return \Symfony\Component\HttpFoundation\Response */ - public function all(SingleCategoryRepositoryInterface $repository, Category $category) + public function all(SCRI $repository, Category $category) { // oldest transaction in category: $start = $repository->getFirstActivityDate($category); @@ -88,11 +88,11 @@ class CategoryController extends Controller /** * Show this month's category overview. * - * @param CategoryRepositoryInterface $repository + * @param CRI $repository * * @return \Symfony\Component\HttpFoundation\Response */ - public function frontpage(CategoryRepositoryInterface $repository) + public function frontpage(CRI $repository) { $start = Session::get('start', Carbon::now()->startOfMonth()); @@ -212,12 +212,12 @@ class CategoryController extends Controller } /** - * @param SingleCategoryRepositoryInterface $repository - * @param Category $category + * @param SCRI $repository + * @param Category $category * * @return \Symfony\Component\HttpFoundation\Response */ - public function currentPeriod(SingleCategoryRepositoryInterface $repository, Category $category) + public function currentPeriod(SCRI $repository, Category $category) { $start = clone Session::get('start', Carbon::now()->startOfMonth()); $end = Session::get('end', Carbon::now()->endOfMonth()); @@ -252,14 +252,14 @@ class CategoryController extends Controller } /** - * @param SingleCategoryRepositoryInterface $repository + * @param SCRI $repository * @param Category $category * * @param $date * * @return \Symfony\Component\HttpFoundation\Response */ - public function specificPeriod(SingleCategoryRepositoryInterface $repository, Category $category, $date) + public function specificPeriod(SCRI $repository, Category $category, $date) { $carbon = new Carbon($date); $range = Preferences::get('viewRange', '1M')->data; @@ -300,7 +300,7 @@ class CategoryController extends Controller * Returns a chart of what has been earned in this period in each category * grouped by month. * - * @param CategoryRepositoryInterface $repository + * @param CRI $repository * @param $reportType * @param Carbon $start * @param Carbon $end @@ -308,7 +308,7 @@ class CategoryController extends Controller * * @return \Illuminate\Http\JsonResponse */ - public function earnedInPeriod(CategoryRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) + public function earnedInPeriod(CRI $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) { $cache = new CacheProperties; // chart properties for cache: $cache->addProperty($start); @@ -367,7 +367,7 @@ class CategoryController extends Controller * Returns a chart of what has been spent in this period in each category * grouped by month. * - * @param CategoryRepositoryInterface $repository + * @param CRI $repository * @param $reportType * @param Carbon $start * @param Carbon $end @@ -375,7 +375,7 @@ class CategoryController extends Controller * * @return \Illuminate\Http\JsonResponse */ - public function spentInPeriod(CategoryRepositoryInterface $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) + public function spentInPeriod(CRI $repository, $reportType, Carbon $start, Carbon $end, Collection $accounts) { $cache = new CacheProperties; // chart properties for cache: $cache->addProperty($start); diff --git a/app/Http/Controllers/JsonController.php b/app/Http/Controllers/JsonController.php index a7729bf8e1..6bb10d4743 100644 --- a/app/Http/Controllers/JsonController.php +++ b/app/Http/Controllers/JsonController.php @@ -5,7 +5,7 @@ use Carbon\Carbon; use FireflyIII\Helpers\Report\ReportQueryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface; -use FireflyIII\Repositories\Category\CategoryRepositoryInterface; +use FireflyIII\Repositories\Category\CategoryRepositoryInterface as CRI; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Support\CacheProperties; @@ -60,7 +60,7 @@ class JsonController extends Controller } /** - * @param BillRepositoryInterface $repository + * @param BillRepositoryInterface $repository * * @return \Symfony\Component\HttpFoundation\Response */ @@ -173,11 +173,11 @@ class JsonController extends Controller /** * Returns a list of categories. * - * @param CategoryRepositoryInterface $repository + * @param CRI $repository * * @return \Illuminate\Http\JsonResponse */ - public function categories(CategoryRepositoryInterface $repository) + public function categories(CRI $repository) { $list = $repository->getCategories(); $return = []; diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index 3ede022898..e799779e59 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -66,9 +66,9 @@ class ReportController extends Controller return view( 'reports.index', compact( - 'months', 'accounts', 'start', 'accountList', - 'startOfMonth', 'endOfMonth', 'startOfYear', 'endOfYear' - ) + 'months', 'accounts', 'start', 'accountList', + 'startOfMonth', 'endOfMonth', 'startOfYear', 'endOfYear' + ) ); } diff --git a/app/Models/PiggyBankEvent.php b/app/Models/PiggyBankEvent.php index d2c016e356..60609f37ae 100644 --- a/app/Models/PiggyBankEvent.php +++ b/app/Models/PiggyBankEvent.php @@ -13,7 +13,7 @@ use Illuminate\Database\Eloquent\Model; * @property integer $transaction_journal_id * @property \Carbon\Carbon $date * @property float $amount - * @property \FireflyIII\Models\PiggyBank $piggyBank + * @property \FireflyIII\Models\PiggyBank $piggyBank * @property-read \FireflyIII\Models\TransactionJournal $transactionJournal * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\PiggyBankEvent whereId($value) * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\PiggyBankEvent whereCreatedAt($value) diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index 9878738d75..32b9892cd5 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -3,7 +3,6 @@ namespace FireflyIII\Repositories\Category; use Carbon\Carbon; -use FireflyIII\Models\Category; use Illuminate\Support\Collection; /** @@ -27,6 +26,53 @@ interface CategoryRepositoryInterface */ public function earnedForAccounts(Collection $accounts, Carbon $start, Carbon $end); + /** + * Returns a collection of Categories appended with the amount of money that has been earned + * in these categories, based on the $accounts involved, in period X, grouped per month. + * The amount earned in category X in period X is saved in field "earned". + * + * @param $accounts + * @param $start + * @param $end + * + * @return Collection + */ + public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); + + /** + * Returns the amount earned without category by accounts in period. + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return string + */ + public function earnedNoCategoryForAccounts(Collection $accounts, Carbon $start, Carbon $end); + + /** + * @return Collection + */ + public function getCategories(); + + /** + * Corrected for tags. + * + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function getCategoriesAndExpenses(Carbon $start, Carbon $end); + + /** + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getWithoutCategory(Carbon $start, Carbon $end); + /** * Returns a collection of Categories appended with the amount of money that has been spent * in these categories, based on the $accounts involved, in period X. @@ -53,24 +99,6 @@ interface CategoryRepositoryInterface */ public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); - /** - * Returns a collection of Categories appended with the amount of money that has been earned - * in these categories, based on the $accounts involved, in period X, grouped per month. - * The amount earned in category X in period X is saved in field "earned". - * - * @param $accounts - * @param $start - * @param $end - * - * @return Collection - */ - public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); - - /** - * @return Collection - */ - public function getCategories(); - /** * Returns the amount spent without category by accounts in period. * @@ -82,33 +110,4 @@ interface CategoryRepositoryInterface */ public function spentNoCategoryForAccounts(Collection $accounts, Carbon $start, Carbon $end); - /** - * Returns the amount earned without category by accounts in period. - * - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function earnedNoCategoryForAccounts(Collection $accounts, Carbon $start, Carbon $end); - - /** - * Corrected for tags. - * - * @param Carbon $start - * @param Carbon $end - * - * @return array - */ - public function getCategoriesAndExpenses(Carbon $start, Carbon $end); - - /** - * @param Carbon $start - * @param Carbon $end - * - * @return Collection - */ - public function getWithoutCategory(Carbon $start, Carbon $end); - } diff --git a/app/Repositories/Category/SingleCategoryRepositoryInterface.php b/app/Repositories/Category/SingleCategoryRepositoryInterface.php index c23784e51d..4c5a4ffa2a 100644 --- a/app/Repositories/Category/SingleCategoryRepositoryInterface.php +++ b/app/Repositories/Category/SingleCategoryRepositoryInterface.php @@ -98,7 +98,6 @@ interface SingleCategoryRepositoryInterface public function getJournals(Category $category, $page); - /** * @param Category $category * @param int $page diff --git a/app/Support/Steam.php b/app/Support/Steam.php index 4b711f18e3..de77081704 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -76,6 +76,7 @@ class Steam * Gets the balance for the given account during the whole range, using this format: * * [yyyy-mm-dd] => 123,2 + * * @param Account $account * @param Carbon $start * @param Carbon $end From 449c6dfde511521b78e28653080d063bcd0ee72d Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 29 Dec 2015 22:51:31 +0100 Subject: [PATCH 11/62] Bind new class. --- app/Providers/FireflyServiceProvider.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Providers/FireflyServiceProvider.php b/app/Providers/FireflyServiceProvider.php index 6f5643752d..d04d6c2d9c 100644 --- a/app/Providers/FireflyServiceProvider.php +++ b/app/Providers/FireflyServiceProvider.php @@ -83,6 +83,7 @@ class FireflyServiceProvider extends ServiceProvider $this->app->bind('FireflyIII\Repositories\Account\AccountRepositoryInterface', 'FireflyIII\Repositories\Account\AccountRepository'); $this->app->bind('FireflyIII\Repositories\Budget\BudgetRepositoryInterface', 'FireflyIII\Repositories\Budget\BudgetRepository'); $this->app->bind('FireflyIII\Repositories\Category\CategoryRepositoryInterface', 'FireflyIII\Repositories\Category\CategoryRepository'); + $this->app->bind('FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface', 'FireflyIII\Repositories\Category\SingleCategoryRepository'); $this->app->bind('FireflyIII\Repositories\Journal\JournalRepositoryInterface', 'FireflyIII\Repositories\Journal\JournalRepository'); $this->app->bind('FireflyIII\Repositories\Bill\BillRepositoryInterface', 'FireflyIII\Repositories\Bill\BillRepository'); $this->app->bind('FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface', 'FireflyIII\Repositories\PiggyBank\PiggyBankRepository'); From 39b88e82071b4938cff26f3a063367a4fc76aa26 Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 08:00:52 +0100 Subject: [PATCH 12/62] Added an alias to make methods more readable. --- app/Http/Controllers/AccountController.php | 30 +++++++++---------- app/Http/Controllers/BudgetController.php | 6 ++-- .../Controllers/Chart/AccountController.php | 10 +++---- .../Controllers/Chart/BudgetController.php | 15 +++++----- app/Http/Controllers/CsvController.php | 4 +-- app/Http/Controllers/HomeController.php | 6 ++-- app/Http/Controllers/JsonController.php | 18 +++++------ app/Http/Controllers/NewUserController.php | 12 ++++---- app/Http/Controllers/PiggyBankController.php | 20 ++++++------- .../Controllers/PreferencesController.php | 6 ++-- app/Http/Controllers/ReportController.php | 6 ++-- .../Controllers/TransactionController.php | 10 +++---- 12 files changed, 71 insertions(+), 72 deletions(-) diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php index b7a6c4c006..11d207773d 100644 --- a/app/Http/Controllers/AccountController.php +++ b/app/Http/Controllers/AccountController.php @@ -6,7 +6,7 @@ use Config; use ExpandedForm; use FireflyIII\Http\Requests\AccountFormRequest; use FireflyIII\Models\Account; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use Input; use Preferences; use Session; @@ -56,12 +56,12 @@ class AccountController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param Account $account * * @return \Illuminate\View\View */ - public function delete(AccountRepositoryInterface $repository, Account $account) + public function delete(ARI $repository, Account $account) { $typeName = Config::get('firefly.shortNamesByFullName.' . $account->accountType->type); $subTitle = trans('firefly.delete_' . $typeName . '_account', ['name' => $account->name]); @@ -77,12 +77,12 @@ class AccountController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param Account $account * * @return \Illuminate\Http\RedirectResponse */ - public function destroy(AccountRepositoryInterface $repository, Account $account) + public function destroy(ARI $repository, Account $account) { $type = $account->accountType->type; $typeName = Config::get('firefly.shortNamesByFullName.' . $type); @@ -98,12 +98,12 @@ class AccountController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param Account $account * * @return \Illuminate\View\View */ - public function edit(AccountRepositoryInterface $repository, Account $account) + public function edit(ARI $repository, Account $account) { $what = Config::get('firefly.shortNamesByFullName')[$account->accountType->type]; @@ -143,12 +143,12 @@ class AccountController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param $what * * @return \Illuminate\View\View */ - public function index(AccountRepositoryInterface $repository, $what) + public function index(ARI $repository, $what) { $subTitle = trans('firefly.' . $what . '_accounts'); $subTitleIcon = Config::get('firefly.subIconsByIdentifier.' . $what); @@ -184,12 +184,12 @@ class AccountController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param Account $account * * @return \Illuminate\View\View */ - public function show(AccountRepositoryInterface $repository, Account $account) + public function show(ARI $repository, Account $account) { $page = intval(Input::get('page')) == 0 ? 1 : intval(Input::get('page')); $subTitleIcon = Config::get('firefly.subTitlesByIdentifier.' . $account->accountType->type); @@ -204,11 +204,11 @@ class AccountController extends Controller /** * @param AccountFormRequest $request - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @return \Illuminate\Http\RedirectResponse */ - public function store(AccountFormRequest $request, AccountRepositoryInterface $repository) + public function store(AccountFormRequest $request, ARI $repository) { $accountData = [ 'name' => $request->input('name'), @@ -243,12 +243,12 @@ class AccountController extends Controller /** * @param AccountFormRequest $request - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param Account $account * * @return \Illuminate\Http\RedirectResponse */ - public function update(AccountFormRequest $request, AccountRepositoryInterface $repository, Account $account) + public function update(AccountFormRequest $request, ARI $repository, Account $account) { $accountData = [ diff --git a/app/Http/Controllers/BudgetController.php b/app/Http/Controllers/BudgetController.php index 6e92369b22..1cf1e15225 100644 --- a/app/Http/Controllers/BudgetController.php +++ b/app/Http/Controllers/BudgetController.php @@ -6,7 +6,7 @@ use Carbon\Carbon; use FireflyIII\Http\Requests\BudgetFormRequest; use FireflyIII\Models\Budget; use FireflyIII\Models\LimitRepetition; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use Input; use Navigation; @@ -134,11 +134,11 @@ class BudgetController extends Controller /** * @param BudgetRepositoryInterface $repository * - * @param AccountRepositoryInterface $accountRepository + * @param ARI $accountRepository * * @return \Illuminate\View\View */ - public function index(BudgetRepositoryInterface $repository, AccountRepositoryInterface $accountRepository) + public function index(BudgetRepositoryInterface $repository, ARI $accountRepository) { $budgets = $repository->getActiveBudgets(); $inactive = $repository->getInactiveBudgets(); diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php index d403f56dc5..92cd33233a 100644 --- a/app/Http/Controllers/Chart/AccountController.php +++ b/app/Http/Controllers/Chart/AccountController.php @@ -5,7 +5,7 @@ namespace FireflyIII\Http\Controllers\Chart; use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; use Preferences; @@ -68,11 +68,11 @@ class AccountController extends Controller /** * Shows the balances for all the user's expense accounts. * - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @return \Symfony\Component\HttpFoundation\Response */ - public function expenseAccounts(AccountRepositoryInterface $repository) + public function expenseAccounts(ARI $repository) { $start = clone Session::get('start', Carbon::now()->startOfMonth()); $end = clone Session::get('end', Carbon::now()->endOfMonth()); @@ -98,11 +98,11 @@ class AccountController extends Controller /** * Shows the balances for all the user's frontpage accounts. * - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @return \Symfony\Component\HttpFoundation\Response */ - public function frontpage(AccountRepositoryInterface $repository) + public function frontpage(ARI $repository) { $frontPage = Preferences::get('frontPageAccounts', []); $start = clone Session::get('start', Carbon::now()->startOfMonth()); diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index 8f197a6a88..64ccd5c591 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -6,7 +6,7 @@ use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Budget; use FireflyIII\Models\LimitRepetition; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; @@ -117,13 +117,12 @@ class BudgetController extends Controller } /** - * @param BudgetRepositoryInterface $repository - * @param AccountRepositoryInterface $accountRepository - * @param Budget $budget + * @param BudgetRepositoryInterface $repository + * @param Budget $budget * * @return \Symfony\Component\HttpFoundation\Response */ - public function budget(BudgetRepositoryInterface $repository, AccountRepositoryInterface $accountRepository, Budget $budget) + public function budget(BudgetRepositoryInterface $repository, Budget $budget) { // dates and times @@ -146,7 +145,7 @@ class BudgetController extends Controller $last = Navigation::endOfX($last, $range, $final); $entries = new Collection; // get all expenses: - $set = $repository->getExpensesPerMonth($budget, $first, $last); + $set = $repository->getExpensesPerMonth($budget, $first, $last); // TODO while ($first < $last) { $monthFormatted = $first->format('Y-m'); @@ -230,11 +229,11 @@ class BudgetController extends Controller * * @param BudgetRepositoryInterface $repository * - * @param AccountRepositoryInterface $accountRepository + * @param ARI $accountRepository * * @return \Symfony\Component\HttpFoundation\Response */ - public function frontpage(BudgetRepositoryInterface $repository, AccountRepositoryInterface $accountRepository) + public function frontpage(BudgetRepositoryInterface $repository, ARI $accountRepository) { $start = Session::get('start', Carbon::now()->startOfMonth()); $end = Session::get('end', Carbon::now()->endOfMonth()); diff --git a/app/Http/Controllers/CsvController.php b/app/Http/Controllers/CsvController.php index e3c864ce85..f2cac49ff6 100644 --- a/app/Http/Controllers/CsvController.php +++ b/app/Http/Controllers/CsvController.php @@ -8,7 +8,7 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Csv\Data; use FireflyIII\Helpers\Csv\Importer; use FireflyIII\Helpers\Csv\WizardInterface; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use Illuminate\Http\Request; use Input; use Log; @@ -150,7 +150,7 @@ class CsvController extends Controller * * @return \Illuminate\View\View */ - public function index(AccountRepositoryInterface $repository) + public function index(ARI $repository) { $subTitle = trans('firefly.csv_import'); diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 6239791a60..a838ba8736 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -4,7 +4,7 @@ use Artisan; use Carbon\Carbon; use Config; use FireflyIII\Models\Tag; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use Input; use Preferences; use Session; @@ -62,11 +62,11 @@ class HomeController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View */ - public function index(AccountRepositoryInterface $repository) + public function index(ARI $repository) { $types = Config::get('firefly.accountTypesByIdentifier.asset'); $count = $repository->countAccounts($types); diff --git a/app/Http/Controllers/JsonController.php b/app/Http/Controllers/JsonController.php index 6bb10d4743..7ba3db7f7a 100644 --- a/app/Http/Controllers/JsonController.php +++ b/app/Http/Controllers/JsonController.php @@ -3,7 +3,7 @@ use Amount; use Carbon\Carbon; use FireflyIII\Helpers\Report\ReportQueryInterface; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface as CRI; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; @@ -113,11 +113,11 @@ class JsonController extends Controller /** * @param ReportQueryInterface $reportQuery * - * @param AccountRepositoryInterface $accountRepository + * @param ARI $accountRepository * * @return \Symfony\Component\HttpFoundation\Response */ - public function boxIn(ReportQueryInterface $reportQuery, AccountRepositoryInterface $accountRepository) + public function boxIn(ReportQueryInterface $reportQuery, ARI $accountRepository) { $start = Session::get('start', Carbon::now()->startOfMonth()); $end = Session::get('end', Carbon::now()->endOfMonth()); @@ -142,11 +142,11 @@ class JsonController extends Controller /** * @param ReportQueryInterface $reportQuery * - * @param AccountRepositoryInterface $accountRepository + * @param ARI $accountRepository * * @return \Symfony\Component\HttpFoundation\Response */ - public function boxOut(ReportQueryInterface $reportQuery, AccountRepositoryInterface $accountRepository) + public function boxOut(ReportQueryInterface $reportQuery, ARI $accountRepository) { $start = Session::get('start', Carbon::now()->startOfMonth()); $end = Session::get('end', Carbon::now()->endOfMonth()); @@ -191,11 +191,11 @@ class JsonController extends Controller /** * Returns a JSON list of all beneficiaries. * - * @param AccountRepositoryInterface $accountRepository + * @param ARI $accountRepository * * @return \Illuminate\Http\JsonResponse */ - public function expenseAccounts(AccountRepositoryInterface $accountRepository) + public function expenseAccounts(ARI $accountRepository) { $list = $accountRepository->getAccounts(['Expense account', 'Beneficiary account']); $return = []; @@ -208,11 +208,11 @@ class JsonController extends Controller } /** - * @param AccountRepositoryInterface $accountRepository + * @param ARI $accountRepository * * @return \Illuminate\Http\JsonResponse */ - public function revenueAccounts(AccountRepositoryInterface $accountRepository) + public function revenueAccounts(ARI $accountRepository) { $list = $accountRepository->getAccounts(['Revenue account']); $return = []; diff --git a/app/Http/Controllers/NewUserController.php b/app/Http/Controllers/NewUserController.php index a500010852..384223dc1b 100644 --- a/app/Http/Controllers/NewUserController.php +++ b/app/Http/Controllers/NewUserController.php @@ -5,8 +5,8 @@ use Carbon\Carbon; use Config; use FireflyIII\Http\Requests\NewUserFormRequest; use FireflyIII\Models\AccountMeta; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use Preferences; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; +use Preferences ; use Session; use View; @@ -20,11 +20,11 @@ class NewUserController extends Controller /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @@return \Illuminate\Http\RedirectResponse|\Illuminate\View\View */ - public function index(AccountRepositoryInterface $repository) + public function index(ARI $repository) { View::share('title', 'Welcome to Firefly!'); View::share('mainTitleIcon', 'fa-fire'); @@ -43,11 +43,11 @@ class NewUserController extends Controller /** * @param NewUserFormRequest $request - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @return \Illuminate\Http\RedirectResponse */ - public function submit(NewUserFormRequest $request, AccountRepositoryInterface $repository) + public function submit(NewUserFormRequest $request, ARI $repository) { // create normal asset account: $assetAccount = [ diff --git a/app/Http/Controllers/PiggyBankController.php b/app/Http/Controllers/PiggyBankController.php index c0bf03eabd..40c43481a8 100644 --- a/app/Http/Controllers/PiggyBankController.php +++ b/app/Http/Controllers/PiggyBankController.php @@ -6,7 +6,7 @@ use Config; use ExpandedForm; use FireflyIII\Http\Requests\PiggyBankFormRequest; use FireflyIII\Models\PiggyBank; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use Illuminate\Support\Collection; use Input; @@ -40,12 +40,12 @@ class PiggyBankController extends Controller /** * Add money to piggy bank * - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param PiggyBank $piggyBank * * @return $this */ - public function add(AccountRepositoryInterface $repository, PiggyBank $piggyBank) + public function add(ARI $repository, PiggyBank $piggyBank) { bcscale(2); $date = Session::get('end', Carbon::now()->endOfMonth()); @@ -58,11 +58,11 @@ class PiggyBankController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @return mixed */ - public function create(AccountRepositoryInterface $repository) + public function create(ARI $repository) { $periods = Config::get('firefly.piggy_bank_periods'); @@ -116,12 +116,12 @@ class PiggyBankController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param PiggyBank $piggyBank * * @return View */ - public function edit(AccountRepositoryInterface $repository, PiggyBank $piggyBank) + public function edit(ARI $repository, PiggyBank $piggyBank) { $periods = Config::get('firefly.piggy_bank_periods'); @@ -162,7 +162,7 @@ class PiggyBankController extends Controller * * @return View */ - public function index(AccountRepositoryInterface $repository, PiggyBankRepositoryInterface $piggyRepository) + public function index(ARI $repository, PiggyBankRepositoryInterface $piggyRepository) { /** @var Collection $piggyBanks */ $piggyBanks = $piggyRepository->getPiggyBanks(); @@ -219,12 +219,12 @@ class PiggyBankController extends Controller /** * @param PiggyBankRepositoryInterface $repository - * @param AccountRepositoryInterface $accounts + * @param ARI $accounts * @param PiggyBank $piggyBank * * @return \Illuminate\Http\RedirectResponse */ - public function postAdd(PiggyBankRepositoryInterface $repository, AccountRepositoryInterface $accounts, PiggyBank $piggyBank) + public function postAdd(PiggyBankRepositoryInterface $repository, ARI $accounts, PiggyBank $piggyBank) { bcscale(2); $amount = round(Input::get('amount'), 2); diff --git a/app/Http/Controllers/PreferencesController.php b/app/Http/Controllers/PreferencesController.php index c782b418e4..9cc7d3e861 100644 --- a/app/Http/Controllers/PreferencesController.php +++ b/app/Http/Controllers/PreferencesController.php @@ -1,7 +1,7 @@ getAccounts(['Default account', 'Asset account']); $viewRangePref = Preferences::get('viewRange', '1M'); diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index e799779e59..cf33981d93 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -3,7 +3,7 @@ use Carbon\Carbon; use FireflyIII\Helpers\Report\ReportHelperInterface; use FireflyIII\Models\Account; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use Illuminate\Support\Collection; use Session; use View; @@ -35,12 +35,12 @@ class ReportController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @return View * @internal param ReportHelperInterface $helper */ - public function index(AccountRepositoryInterface $repository) + public function index(ARI $repository) { $start = Session::get('first'); $months = $this->helper->listOfMonths($start); diff --git a/app/Http/Controllers/TransactionController.php b/app/Http/Controllers/TransactionController.php index 604a10d789..1ed7e5a78a 100644 --- a/app/Http/Controllers/TransactionController.php +++ b/app/Http/Controllers/TransactionController.php @@ -14,7 +14,7 @@ use FireflyIII\Models\PiggyBankEvent; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use Illuminate\Support\Collection; use Input; @@ -43,12 +43,12 @@ class TransactionController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param string $what * * @return \Illuminate\View\View */ - public function create(AccountRepositoryInterface $repository, $what = TransactionType::DEPOSIT) + public function create(ARI $repository, $what = TransactionType::DEPOSIT) { $what = strtolower($what); $maxFileSize = Steam::phpBytes(ini_get('upload_max_filesize')); @@ -133,12 +133,12 @@ class TransactionController extends Controller /** * Shows the view to edit a transaction. * - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param TransactionJournal $journal * * @return $this */ - public function edit(AccountRepositoryInterface $repository, TransactionJournal $journal) + public function edit(ARI $repository, TransactionJournal $journal) { // cannot edit opening balance if ($journal->isOpeningBalance()) { From a3d2a9e00b9109b3ce66eabbf15f4ad2b8f3f3e9 Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 08:15:04 +0100 Subject: [PATCH 13/62] Some cleaning up, and I hope simplification. --- .../Controllers/Chart/CategoryController.php | 9 +- .../Category/CategoryRepository.php | 143 ++++++++++-------- .../Category/CategoryRepositoryInterface.php | 29 ++-- app/Sql/Query.php | 17 +++ 4 files changed, 114 insertions(+), 84 deletions(-) create mode 100644 app/Sql/Query.php diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 6a96bc5bdc..41a28b36b6 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -129,7 +129,6 @@ class CategoryController extends Controller } /** - * @param CategoryRepositoryInterface $repository * @param $reportType * @param Carbon $start * @param Carbon $end @@ -140,9 +139,9 @@ class CategoryController extends Controller */ public function multiYear($reportType, Carbon $start, Carbon $end, Collection $accounts, Collection $categories) { - /** @var CategoryRepositoryInterface $repository */ + /** @var CRI $repository */ $repository = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface'); - /** @var SingleCategoryRepositoryInterface $singleRepository */ + /** @var SCRI $singleRepository */ $singleRepository = app('FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface'); // chart properties for cache: @@ -182,8 +181,8 @@ class CategoryController extends Controller // get data: if (is_null($category->id)) { $name = trans('firefly.noCategory'); - $spent = $repository->spentNoCategoryForAccounts($accounts, $currentStart, $currentEnd); - $earned = $repository->earnedNoCategoryForAccounts($accounts, $currentStart, $currentEnd); + $spent = $repository->sumSpentNoCategory($accounts, $currentStart, $currentEnd); + $earned = $repository->sumEarnedNoCategory($accounts, $currentStart, $currentEnd); } else { $name = $category->name; $spent = $singleRepository->spentInPeriodForAccounts($category, $accounts, $currentStart, $currentEnd); diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index 8ccc840780..269255cba6 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -7,6 +7,7 @@ use Carbon\Carbon; use DB; use FireflyIII\Models\Category; use FireflyIII\Models\TransactionType; +use FireflyIII\Sql\Query; use FireflyIII\Support\CacheProperties; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; @@ -44,72 +45,6 @@ class CategoryRepository implements CategoryRepositoryInterface return $set; } - /** - * Returns the amount earned without category by accounts in period. - * - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function earnedNoCategoryForAccounts(Collection $accounts, Carbon $start, Carbon $end) - { - - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - - // is deposit AND account_from is in the list of $accounts - // not from any of the accounts in the list? - - return Auth::user() - ->transactionjournals() - ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') - ->whereNull('category_transaction_journal.id') - ->before($end) - ->after($start) - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->whereIn('transactions.account_id', $accountIds) - ->transactionTypes([TransactionType::DEPOSIT]) - ->get(['transaction_journals.*'])->sum('amount'); - } - - - /** - * Returns the amount spent without category by accounts in period. - * - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function spentNoCategoryForAccounts(Collection $accounts, Carbon $start, Carbon $end) - { - - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - - // is withdrawal or transfer AND account_from is in the list of $accounts - - - return Auth::user() - ->transactionjournals() - ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') - ->whereNull('category_transaction_journal.id') - ->before($end) - ->after($start) - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->whereIn('transactions.account_id', $accountIds) - ->transactionTypes([TransactionType::WITHDRAWAL]) - ->get(['transaction_journals.*'])->sum('amount'); - } - - /** * @param Carbon $start * @param Carbon $end @@ -147,6 +82,7 @@ class CategoryRepository implements CategoryRepositoryInterface } // without category: + // TODO REMOVE ME $single = Auth::user()->transactionjournals() ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') @@ -392,4 +328,79 @@ class CategoryRepository implements CategoryRepositoryInterface return $collection; } + + /** + * Returns the total amount of money related to transactions without any category connected to + * it. Returns either the spent amount. + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return string + */ + public function sumSpentNoCategory(Collection $accounts, Carbon $start, Carbon $end) + { + return $this->sumNoCategory($accounts, $start, $end, Query::SPENT); + } + + /** + * Returns the total amount of money related to transactions without any category connected to + * it. Returns either the earned amount. + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return string + */ + public function sumEarnedNoCategory(Collection $accounts, Carbon $start, Carbon $end) + { + return $this->sumNoCategory($accounts, $start, $end, Query::EARNED); + } + + /** + * Returns the total amount of money related to transactions without any category connected to + * it. Returns either the earned or the spent amount. + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * @param int $group + * + * @return string + */ + protected function sumNoCategory(Collection $accounts, Carbon $start, Carbon $end, $group = Query::EARNED) + { + $accountIds = []; + foreach ($accounts as $account) { + $accountIds[] = $account->id; + } + if ($group == Query::EARNED) { + $types = [TransactionType::DEPOSIT]; + } else { + $types = [TransactionType::WITHDRAWAL]; + } + + // is withdrawal or transfer AND account_from is in the list of $accounts + $single = Auth::user() + ->transactionjournals() + ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->whereNull('category_transaction_journal.id') + ->before($end) + ->after($start) + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->whereIn('transactions.account_id', $accountIds) + ->transactionTypes($types) + ->first( + [ + DB::Raw('SUM(`transactions`.`amount`) as `sum`)')] + ); + if (!is_null($single)) { + return $single->sum; + } + + return '0'; + + } } diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index 32b9892cd5..fd44e95db5 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -3,6 +3,7 @@ namespace FireflyIII\Repositories\Category; use Carbon\Carbon; +use FireflyIII\Sql\Query; use Illuminate\Support\Collection; /** @@ -39,17 +40,6 @@ interface CategoryRepositoryInterface */ public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); - /** - * Returns the amount earned without category by accounts in period. - * - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function earnedNoCategoryForAccounts(Collection $accounts, Carbon $start, Carbon $end); - /** * @return Collection */ @@ -100,7 +90,8 @@ interface CategoryRepositoryInterface public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); /** - * Returns the amount spent without category by accounts in period. + * Returns the total amount of money related to transactions without any category connected to + * it. Returns either the spent amount. * * @param Collection $accounts * @param Carbon $start @@ -108,6 +99,18 @@ interface CategoryRepositoryInterface * * @return string */ - public function spentNoCategoryForAccounts(Collection $accounts, Carbon $start, Carbon $end); + public function sumSpentNoCategory(Collection $accounts, Carbon $start, Carbon $end); + + /** + * Returns the total amount of money related to transactions without any category connected to + * it. Returns either the earned amount. + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return string + */ + public function sumEarnedNoCategory(Collection $accounts, Carbon $start, Carbon $end); } diff --git a/app/Sql/Query.php b/app/Sql/Query.php new file mode 100644 index 0000000000..9f31ad83fe --- /dev/null +++ b/app/Sql/Query.php @@ -0,0 +1,17 @@ + Date: Wed, 30 Dec 2015 08:21:11 +0100 Subject: [PATCH 14/62] More code cleanup. --- app/Helpers/Report/ReportHelper.php | 2 +- app/Http/Controllers/CategoryController.php | 4 +- app/Http/Controllers/JsonController.php | 2 +- .../Category/CategoryRepository.php | 145 +++--------------- .../Category/CategoryRepositoryInterface.php | 42 ++--- 5 files changed, 39 insertions(+), 156 deletions(-) diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 084cd6ed3e..7dc00d2fd3 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -65,7 +65,7 @@ class ReportHelper implements ReportHelperInterface /** @var \FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface $singleRepository */ $singleRepository = app('FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface'); - $set = $repository->getCategories(); + $set = $repository->listCategories(); foreach ($set as $category) { $spent = $singleRepository->balanceInPeriod($category, $start, $end, $accounts); $category->spent = $spent; diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php index 4257e86e58..fe7a1ebeae 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryController.php @@ -115,7 +115,7 @@ class CategoryController extends Controller */ public function index(CRI $repository, SCRI $singleRepository) { - $categories = $repository->getCategories(); + $categories = $repository->listCategories(); $categories->each( function (Category $category) use ($singleRepository) { @@ -135,7 +135,7 @@ class CategoryController extends Controller { $start = Session::get('start', Carbon::now()->startOfMonth()); $end = Session::get('end', Carbon::now()->startOfMonth()); - $list = $repository->getWithoutCategory($start, $end); + $list = $repository->listNoCategory($start, $end); $subTitle = trans( 'firefly.without_category_between', ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)] diff --git a/app/Http/Controllers/JsonController.php b/app/Http/Controllers/JsonController.php index 7ba3db7f7a..7005084b4b 100644 --- a/app/Http/Controllers/JsonController.php +++ b/app/Http/Controllers/JsonController.php @@ -179,7 +179,7 @@ class JsonController extends Controller */ public function categories(CRI $repository) { - $list = $repository->getCategories(); + $list = $repository->listCategories(); $return = []; foreach ($list as $entry) { $return[] = $entry->name; diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index 269255cba6..5e1deb4636 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -8,7 +8,6 @@ use DB; use FireflyIII\Models\Category; use FireflyIII\Models\TransactionType; use FireflyIII\Sql\Query; -use FireflyIII\Support\CacheProperties; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; @@ -21,31 +20,8 @@ class CategoryRepository implements CategoryRepositoryInterface { /** - * @return Collection - */ - public function getCategories() - { - $cache = new CacheProperties; - $cache->addProperty('category-list'); - - if ($cache->has()) { - return $cache->get(); - } - - /** @var Collection $set */ - $set = Auth::user()->categories()->orderBy('name', 'ASC')->get(); - $set = $set->sortBy( - function (Category $category) { - return strtolower($category->name); - } - ); - - $cache->store($set); - - return $set; - } - - /** + * TODO REMOVE ME + * * @param Carbon $start * @param Carbon $end * @@ -106,12 +82,33 @@ class CategoryRepository implements CategoryRepositoryInterface } /** + * Returns a list of all the categories belonging to a user. + * + * @return Collection + */ + public function listCategories() + { + /** @var Collection $set */ + $set = Auth::user()->categories()->orderBy('name', 'ASC')->get(); + $set = $set->sortBy( + function (Category $category) { + return strtolower($category->name); + } + ); + + return $set; + } + + /** + * Returns a list of transaction journals in the range (all types, all accounts) that have no category + * associated to them. + * * @param Carbon $start * @param Carbon $end * * @return Collection */ - public function getWithoutCategory(Carbon $start, Carbon $end) + public function listNoCategory(Carbon $start, Carbon $end) { return Auth::user() ->transactionjournals() @@ -181,100 +178,6 @@ class CategoryRepository implements CategoryRepositoryInterface } - /** - * Returns a collection of Categories appended with the amount of money that has been earned - * in these categories, based on the $accounts involved, in period X. - * The amount earned in category X in period X is saved in field "earned". - * - * @param $accounts - * @param $start - * @param $end - * - * @return Collection - */ - public function earnedForAccounts(Collection $accounts, Carbon $start, Carbon $end) - { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - - - $collection = Auth::user()->categories() - ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id') - ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') - ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') - ->leftJoin( - 'transactions AS t_src', function (JoinClause $join) { - $join->on('t_src.transaction_journal_id', '=', 'transaction_journals.id')->where('t_src.amount', '<', 0); - } - ) - ->leftJoin( - 'transactions AS t_dest', function (JoinClause $join) { - $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0); - } - ) - ->whereIn('t_dest.account_id', $accountIds)// to these accounts (earned) - ->whereNotIn('t_src.account_id', $accountIds)//-- but not from these accounts - ->whereIn( - 'transaction_types.type', [TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE] - ) - ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) - ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) - ->groupBy('categories.id') - ->get(['categories.*', DB::Raw('SUM(`t_dest`.`amount`) AS `earned`')]); - - return $collection; - - - } - - /** - * Returns a collection of Categories appended with the amount of money that has been spent - * in these categories, based on the $accounts involved, in period X. - * The amount earned in category X in period X is saved in field "spent". - * - * @param $accounts - * @param $start - * @param $end - * - * @return Collection - */ - public function spentForAccounts(Collection $accounts, Carbon $start, Carbon $end) - { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - - - $collection = Auth::user()->categories() - ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id') - ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') - ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') - ->leftJoin( - 'transactions AS t_src', function (JoinClause $join) { - $join->on('t_src.transaction_journal_id', '=', 'transaction_journals.id')->where('t_src.amount', '<', 0); - } - ) - ->leftJoin( - 'transactions AS t_dest', function (JoinClause $join) { - $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0); - } - ) - ->whereIn('t_src.account_id', $accountIds)// from these accounts (spent) - ->whereNotIn('t_dest.account_id', $accountIds)//-- but not from these accounts (spent internally) - ->whereIn( - 'transaction_types.type', [TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE] - )// spent on these things. - ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) - ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) - ->groupBy('categories.id') - ->get(['categories.*', DB::Raw('SUM(`t_dest`.`amount`) AS `spent`')]); - - return $collection; - } - /** * Returns a collection of Categories appended with the amount of money that has been spent * in these categories, based on the $accounts involved, in period X, grouped per month. diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index fd44e95db5..2bf6825beb 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -14,18 +14,6 @@ use Illuminate\Support\Collection; interface CategoryRepositoryInterface { - /** - * Returns a collection of Categories appended with the amount of money that has been earned - * in these categories, based on the $accounts involved, in period X. - * The amount earned in category X in period X is saved in field "earned". - * - * @param $accounts - * @param $start - * @param $end - * - * @return Collection - */ - public function earnedForAccounts(Collection $accounts, Carbon $start, Carbon $end); /** * Returns a collection of Categories appended with the amount of money that has been earned @@ -40,11 +28,6 @@ interface CategoryRepositoryInterface */ public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); - /** - * @return Collection - */ - public function getCategories(); - /** * Corrected for tags. * @@ -56,25 +39,22 @@ interface CategoryRepositoryInterface public function getCategoriesAndExpenses(Carbon $start, Carbon $end); /** + * Returns a list of all the categories belonging to a user. + * + * @return Collection + */ + public function listCategories(); + + /** + * Returns a list of transaction journals in the range (all types, all accounts) that have no category + * associated to them. + * * @param Carbon $start * @param Carbon $end * * @return Collection */ - public function getWithoutCategory(Carbon $start, Carbon $end); - - /** - * Returns a collection of Categories appended with the amount of money that has been spent - * in these categories, based on the $accounts involved, in period X. - * The amount earned in category X in period X is saved in field "spent". - * - * @param $accounts - * @param $start - * @param $end - * - * @return Collection - */ - public function spentForAccounts(Collection $accounts, Carbon $start, Carbon $end); + public function listNoCategory(Carbon $start, Carbon $end); /** * Returns a collection of Categories appended with the amount of money that has been spent From 238ed3c788fa53327147e0ac052ba47dc06ea46d Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 08:25:38 +0100 Subject: [PATCH 15/62] Rename a method. --- app/Http/Controllers/ReportController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index cf33981d93..28ed6f1322 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -171,7 +171,7 @@ class ReportController extends Controller // list of users stuff: $budgets = app('FireflyIII\Repositories\Budget\BudgetRepositoryInterface')->getActiveBudgets(); - $categories = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface')->getCategories(); + $categories = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface')->listCategories(); // and some id's, joined: $accountIds = []; From 03babfe75c3eab6853becb09a48513d77d819497 Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 09:16:53 +0100 Subject: [PATCH 16/62] Removed for-loop in favour of "pluck()" aka: RTFM. --- app/Repositories/Account/AccountRepository.php | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index dcd9a867f1..98dd114014 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -266,16 +266,10 @@ class AccountRepository implements AccountRepositoryInterface */ public function getPiggyBankAccounts() { - $ids = []; - $start = clone Session::get('start', new Carbon); - $end = clone Session::get('end', new Carbon); - $accountIds = DB::table('piggy_banks')->distinct()->get(['piggy_banks.account_id']); - $accounts = new Collection; - - /** @var PiggyBank $id */ - foreach ($accountIds as $id) { - $ids[] = intval($id->account_id); - } + $start = clone Session::get('start', new Carbon); + $end = clone Session::get('end', new Carbon); + $ids = DB::table('piggy_banks')->distinct()->get(['piggy_banks.account_id'])->pluck('account_id')->toArray(); + $accounts = new Collection; $cache = new CacheProperties; $cache->addProperty($ids); From 638184cf668a6ddde15a26d8d97d0f5b6d96f5c9 Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 09:16:58 +0100 Subject: [PATCH 17/62] Removed for-loop in favour of "pluck()" aka: RTFM. --- app/Repositories/Bill/BillRepository.php | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index 1e08433502..7a5c11c985 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -7,7 +7,6 @@ use Carbon\Carbon; use DB; use FireflyIII\Models\Account; use FireflyIII\Models\Bill; -use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; @@ -66,13 +65,7 @@ class BillRepository implements BillRepositoryInterface { /** @var Collection $set */ $set = Auth::user()->bills()->orderBy('name', 'ASC')->get(); - - $ids = []; - /** @var Account $account */ - foreach ($accounts as $account) { - $ids[] = $account->id; - } - + $ids = $accounts->pluck('id')->toArray(); $set = $set->filter( function (Bill $bill) use ($ids) { // get transaction journals from or to any of the mentioned accounts. @@ -156,12 +149,8 @@ class BillRepository implements BillRepositoryInterface $set = DB::table('transactions')->where('amount', '>', 0)->where('amount', '>=', $bill->amount_min)->where('amount', '<=', $bill->amount_max)->get( ['transaction_journal_id'] ); - $ids = []; + $ids = $set->pluck('transaction_journal_id')->toArray(); - /** @var Transaction $entry */ - foreach ($set as $entry) { - $ids[] = intval($entry->transaction_journal_id); - } $journals = new Collection; if (count($ids) > 0) { $journals = Auth::user()->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->whereIn('transaction_journals.id', $ids)->get( From 9f87890ead2b9cb4112961432972185ef832427b Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 09:17:05 +0100 Subject: [PATCH 18/62] Removed for-loop in favour of "pluck()" aka: RTFM. --- app/Repositories/Budget/BudgetRepository.php | 25 ++++---------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index a828ede212..c5a3e857c4 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -284,11 +284,7 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn */ public function getBudgetsAndExpensesPerMonth(Collection $accounts, Carbon $start, Carbon $end) { - $ids = []; - /** @var Account $account */ - foreach ($accounts as $account) { - $ids[] = $account->id; - } + $ids = $accounts->pluck('id')->toArray(); /** @var Collection $set */ $set = Auth::user()->budgets() @@ -587,12 +583,7 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn */ public function getBudgetedPerYear(Collection $budgets, Carbon $start, Carbon $end) { - $budgetIds = []; - - /** @var Budget $budget */ - foreach ($budgets as $budget) { - $budgetIds[] = $budget->id; - } + $budgetIds = $budgets->pluck('id')->toArray(); $set = Auth::user()->budgets() ->leftJoin('budget_limits', 'budgets.id', '=', 'budget_limits.budget_id') @@ -626,16 +617,8 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn */ public function getBudgetsAndExpensesPerYear(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end) { - $ids = []; - /** @var Account $account */ - foreach ($accounts as $account) { - $ids[] = $account->id; - } - $budgetIds = []; - /** @var Budget $budget */ - foreach ($budgets as $budget) { - $budgetIds[] = $budget->id; - } + $ids = $accounts->pluck('id')->toArray(); + $budgetIds = $budgets->pluck('id')->toArray(); /** @var Collection $set */ $set = Auth::user()->budgets() From f99e46bf7533c278cf5258553b81909511016226 Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 09:17:14 +0100 Subject: [PATCH 19/62] Removed for-loop in favour of "pluck()" aka: RTFM. --- app/Repositories/Category/SingleCategoryRepository.php | 10 ++-------- app/Repositories/Shared/ComponentRepository.php | 6 +----- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php index 5c115c9ce1..ada1aa5bf6 100644 --- a/app/Repositories/Category/SingleCategoryRepository.php +++ b/app/Repositories/Category/SingleCategoryRepository.php @@ -110,10 +110,7 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate */ public function earnedInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end) { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } + $accountIds = $accounts->pluck('id')->toArray(); $sum = $category ->transactionjournals() @@ -237,10 +234,7 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate */ public function spentInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end) { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } + $accountIds = $accounts->pluck('id')->toArray(); $sum = $category diff --git a/app/Repositories/Shared/ComponentRepository.php b/app/Repositories/Shared/ComponentRepository.php index f9584ef72d..6731c904cb 100644 --- a/app/Repositories/Shared/ComponentRepository.php +++ b/app/Repositories/Shared/ComponentRepository.php @@ -39,11 +39,7 @@ class ComponentRepository return $cache->get(); // @codeCoverageIgnore } - $ids = []; - /** @var Account $account */ - foreach ($accounts as $account) { - $ids[] = $account->id; - } + $ids = $accounts->pluck('id')->toArray(); $entry = $object->transactionjournals() From 2904baf44ea566c51341bb0b75437342ca0b33af Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 09:17:29 +0100 Subject: [PATCH 20/62] From 1100+ queries to a steady 6. --- .../Controllers/Chart/CategoryController.php | 31 ++++++-- .../Category/CategoryRepository.php | 77 +++++++++++++++---- .../Category/CategoryRepositoryInterface.php | 17 +++- 3 files changed, 100 insertions(+), 25 deletions(-) diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 41a28b36b6..eb69f95549 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -141,8 +141,6 @@ class CategoryController extends Controller { /** @var CRI $repository */ $repository = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface'); - /** @var SCRI $singleRepository */ - $singleRepository = app('FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface'); // chart properties for cache: $cache = new CacheProperties(); @@ -167,7 +165,14 @@ class CategoryController extends Controller * earned: x */ $entries = new Collection; - // go by budget, not by year. + // go by category, not by year. + + // given a set of categories and accounts, it should not be difficult to get + // the exact array of data we need. + + // then get the data for "no category". + $set = $repository->listMultiYear($categories, $accounts, $start, $end); + /** @var Category $category */ foreach ($categories as $category) { $entry = ['name' => '', 'spent' => [], 'earned' => []]; @@ -175,22 +180,35 @@ class CategoryController extends Controller $currentStart = clone $start; while ($currentStart < $end) { // fix the date: + $year = $currentStart->year; $currentEnd = clone $currentStart; $currentEnd->endOfYear(); + // get data: if (is_null($category->id)) { $name = trans('firefly.noCategory'); $spent = $repository->sumSpentNoCategory($accounts, $currentStart, $currentEnd); $earned = $repository->sumEarnedNoCategory($accounts, $currentStart, $currentEnd); } else { + // get from set: + $entrySpent = $set->filter( + function (Category $cat) use ($year, $category) { + return ($cat->type == 'Withdrawal' && $cat->dateFormatted == $year && $cat->id == $category->id); + } + )->first(); + $entryEarned = $set->filter( + function (Category $cat) use ($year, $category) { + return ($cat->type == 'Deposit' && $cat->dateFormatted == $year && $cat->id == $category->id); + } + )->first(); + $name = $category->name; - $spent = $singleRepository->spentInPeriodForAccounts($category, $accounts, $currentStart, $currentEnd); - $earned = $singleRepository->earnedInPeriodForAccounts($category, $accounts, $currentStart, $currentEnd); + $spent = !is_null($entrySpent) ? $entrySpent->sum : 0; + $earned = !is_null($entryEarned) ? $entryEarned->sum : 0; } // save to array: - $year = $currentStart->year; $entry['name'] = $name; $entry['spent'][$year] = ($spent * -1); $entry['earned'][$year] = $earned; @@ -205,7 +223,6 @@ class CategoryController extends Controller $data = $this->generator->multiYear($entries); $cache->store($data); - return Response::json($data); } diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index 5e1deb4636..bd5e0e83b8 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -122,6 +122,62 @@ class CategoryRepository implements CategoryRepositoryInterface ->get(['transaction_journals.*']); } + /** + * This method returns a very special collection for each category: + * + * category, year, expense/earned, amount + * + * categories can be duplicated. + * + * @param Collection $categories + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function listMultiYear(Collection $categories, Collection $accounts, Carbon $start, Carbon $end) + { + /* + * select categories.id, DATE_FORMAT(transaction_journals.date,"%Y") as dateFormatted, transaction_types.type, SUM(amount) as sum from categories + +left join category_transaction_journal ON category_transaction_journal.category_id = categories.id +left join transaction_journals ON transaction_journals.id = category_transaction_journal.transaction_journal_id +left join transaction_types ON transaction_types.id = transaction_journals.transaction_type_id +left join transactions ON transactions.transaction_journal_id = transaction_journals.id + + +where +categories.user_id =1 +and transaction_types.type in ("Withdrawal","Deposit") +and transactions.account_id IN (2,4,6,10,11,610,725,879,1248) + +group by categories.id, transaction_types.type, dateFormatted + */ + $set = Auth::user()->categories() + ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id') + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'category_transaction_journal.transaction_journal_id') + ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->whereIn('transaction_types.type', [TransactionType::DEPOSIT, TransactionType::WITHDRAWAL]) + ->whereIn('transactions.account_id', $accounts->pluck('id')->toArray()) + ->whereIn('categories.id', $categories->pluck('id')->toArray()) + ->groupBy('categories.id') + ->groupBy('transaction_types.type') + ->groupBy('dateFormatted') + ->get( + [ + 'categories.*', + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y") as `dateFormatted`'), + 'transaction_types.type', + DB::Raw('SUM(`amount`) as `sum`') + ] + ); + + return $set; + + } + /** * Returns a collection of Categories appended with the amount of money that has been earned @@ -136,11 +192,6 @@ class CategoryRepository implements CategoryRepositoryInterface */ public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end) { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - $collection = Auth::user()->categories() ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id') @@ -156,8 +207,8 @@ class CategoryRepository implements CategoryRepositoryInterface $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0); } ) - ->whereIn('t_dest.account_id', $accountIds)// to these accounts (earned) - ->whereNotIn('t_src.account_id', $accountIds)//-- but not from these accounts + ->whereIn('t_dest.account_id', $accounts->pluck('id')->toArray())// to these accounts (earned) + ->whereNotIn('t_src.account_id', $accounts->pluck('id')->toArray())//-- but not from these accounts ->whereIn( 'transaction_types.type', [TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE] ) @@ -191,12 +242,7 @@ class CategoryRepository implements CategoryRepositoryInterface */ public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end) { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - - + $accountIds = $accounts->pluck('id')->toArray(); $collection = Auth::user()->categories() ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id') ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') @@ -275,10 +321,7 @@ class CategoryRepository implements CategoryRepositoryInterface */ protected function sumNoCategory(Collection $accounts, Carbon $start, Carbon $end, $group = Query::EARNED) { - $accountIds = []; - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } + $accountIds = $accounts->pluck('id')->toArray(); if ($group == Query::EARNED) { $types = [TransactionType::DEPOSIT]; } else { diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index 2bf6825beb..47bba21750 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -3,7 +3,6 @@ namespace FireflyIII\Repositories\Category; use Carbon\Carbon; -use FireflyIII\Sql\Query; use Illuminate\Support\Collection; /** @@ -45,6 +44,22 @@ interface CategoryRepositoryInterface */ public function listCategories(); + /** + * This method returns a very special collection for each category: + * + * category, year, expense/earned, amount + * + * categories can be duplicated. + * + * @param Collection $categories + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function listMultiYear(Collection $categories, Collection $accounts, Carbon $start, Carbon $end); + /** * Returns a list of transaction journals in the range (all types, all accounts) that have no category * associated to them. From 08703e282facf69a8627e636d8eb187a7dd41218 Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 09:30:06 +0100 Subject: [PATCH 21/62] Fix array. --- app/Repositories/Account/AccountRepository.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 98dd114014..90eb46cd13 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -266,9 +266,10 @@ class AccountRepository implements AccountRepositoryInterface */ public function getPiggyBankAccounts() { - $start = clone Session::get('start', new Carbon); - $end = clone Session::get('end', new Carbon); - $ids = DB::table('piggy_banks')->distinct()->get(['piggy_banks.account_id'])->pluck('account_id')->toArray(); + $start = clone Session::get('start', new Carbon); + $end = clone Session::get('end', new Carbon); + $collection = new Collection(DB::table('piggy_banks')->distinct()->get(['piggy_banks.account_id'])); + $ids = $collection->pluck('account_id')->toArray(); $accounts = new Collection; $cache = new CacheProperties; From d75614e9a7e9c9864863ebb4bcb50ffe9502e0fe Mon Sep 17 00:00:00 2001 From: James Cole Date: Wed, 30 Dec 2015 16:42:09 +0100 Subject: [PATCH 22/62] Optimised two charts, cleaned up some code. --- .../Controllers/Chart/CategoryController.php | 26 +-- .../Category/CategoryRepositoryInterface.php | 24 +-- .../Category/SingleCategoryRepository.php | 151 +++++++----------- .../SingleCategoryRepositoryInterface.php | 53 +++--- 4 files changed, 111 insertions(+), 143 deletions(-) diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index eb69f95549..bc37dc0517 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -244,16 +244,21 @@ class CategoryController extends Controller $cache->addProperty($end); $cache->addProperty($category->id); $cache->addProperty('category'); - $cache->addProperty('currentPeriod'); + $cache->addProperty('current-period'); if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore } $entries = new Collection; + // get amount earned in period, grouped by day. + $spentArray = $repository->spentPerDay($category, $start, $end); + $earnedArray = $repository->earnedPerDay($category, $start, $end); + // get amount spent in period, grouped by day. while ($start <= $end) { - $spent = $repository->spentOnDaySum($category, $start); - $earned = $repository->earnedOnDaySum($category, $start); + $str = $start->format('Y-m-d'); + $spent = isset($spentArray[$str]) ? $spentArray[$str] : 0; + $earned = isset($earnedArray[$str]) ? $earnedArray[$str] : 0; $date = Navigation::periodShow($start, '1D'); $entries->push([clone $start, $date, $spent, $earned]); $start->addDay(); @@ -263,8 +268,6 @@ class CategoryController extends Controller $cache->store($data); return Response::json($data); - - } /** @@ -295,12 +298,17 @@ class CategoryController extends Controller } $entries = new Collection; + // get amount earned in period, grouped by day. + $spentArray = $repository->spentPerDay($category, $start, $end); + $earnedArray = $repository->earnedPerDay($category, $start, $end); + // get amount spent in period, grouped by day. while ($start <= $end) { - $spent = $repository->spentOnDaySum($category, $start); - $earned = $repository->earnedOnDaySum($category, $start); - $theDate = Navigation::periodShow($start, '1D'); - $entries->push([clone $start, $theDate, $spent, $earned]); + $str = $start->format('Y-m-d'); + $spent = isset($spentArray[$str]) ? $spentArray[$str] : 0; + $earned = isset($earnedArray[$str]) ? $earnedArray[$str] : 0; + $date = Navigation::periodShow($start, '1D'); + $entries->push([clone $start, $date, $spent, $earned]); $start->addDay(); } diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index 47bba21750..dd96800255 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -84,18 +84,6 @@ interface CategoryRepositoryInterface */ public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end); - /** - * Returns the total amount of money related to transactions without any category connected to - * it. Returns either the spent amount. - * - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function sumSpentNoCategory(Collection $accounts, Carbon $start, Carbon $end); - /** * Returns the total amount of money related to transactions without any category connected to * it. Returns either the earned amount. @@ -108,4 +96,16 @@ interface CategoryRepositoryInterface */ public function sumEarnedNoCategory(Collection $accounts, Carbon $start, Carbon $end); + /** + * Returns the total amount of money related to transactions without any category connected to + * it. Returns either the spent amount. + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return string + */ + public function sumSpentNoCategory(Collection $accounts, Carbon $start, Carbon $end); + } diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php index ada1aa5bf6..eca6aafec8 100644 --- a/app/Repositories/Category/SingleCategoryRepository.php +++ b/app/Repositories/Category/SingleCategoryRepository.php @@ -2,12 +2,13 @@ namespace FireflyIII\Repositories\Category; +use Auth; use Carbon\Carbon; +use DB; use FireflyIII\Models\Category; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Shared\ComponentRepository; -use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; /** @@ -69,6 +70,10 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate } /** + * TODO this method is not optimal, and should be replaced. + * + * @deprecated + * * @param Category $category * @param \Carbon\Carbon $start * @param \Carbon\Carbon $end @@ -77,67 +82,47 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate */ public function earnedInPeriod(Category $category, Carbon $start, Carbon $end) { - $cache = new CacheProperties; // we must cache this. - $cache->addProperty($category->id); - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty('earnedInPeriod'); - - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $sum = $category->transactionjournals()->transactionTypes([TransactionType::DEPOSIT])->before($end)->after($start)->get(['transaction_journals.*']) ->sum( 'amount' ); - $cache->store($sum); - return $sum; } - /** - * Calculate how much is earned in this period. + * Returns an array with the following key:value pairs: * - * @param Category $category - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end + * yyyy-mm-dd: * - * @return string - */ - public function earnedInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end) - { - $accountIds = $accounts->pluck('id')->toArray(); - $sum - = $category - ->transactionjournals() - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->before($end) - ->whereIn('transactions.account_id', $accountIds) - ->transactionTypes([TransactionType::DEPOSIT]) - ->after($start) - ->get(['transaction_journals.*']) - ->sum('amount'); - - return $sum; - - } - - /** - * - * Corrected for tags. + * Where yyyy-mm-dd is the date and is the money earned using DEPOSITS in the $category + * from all the users $accounts. * * @param Category $category - * @param Carbon $date + * @param Carbon $start + * @param Carbon $end * - * @return float + * @return array */ - public function earnedOnDaySum(Category $category, Carbon $date) + public function earnedPerDay(Category $category, Carbon $start, Carbon $end) { - return $category->transactionjournals()->transactionTypes([TransactionType::DEPOSIT])->onDate($date)->get(['transaction_journals.*'])->sum('amount'); + /** @var Collection $query */ + $query = Auth::user()->transactionJournals() + ->transactionTypes([TransactionType::DEPOSIT]) + ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->where('transactions.amount', '>', 0) + ->before($end) + ->after($start) + ->where('category_transaction_journal.category_id', $category->id) + ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); + + $return = []; + foreach ($query->toArray() as $entry) { + $return[$entry['dateFormatted']] = $entry['sum']; + } + + return $return; } /** @@ -221,37 +206,11 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate return null; } - /** - * Calculates how much is spent in this period. + * TODO this method is not optimal, and should be replaced. * - * @param Category $category - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end + * @deprecated * - * @return string - */ - public function spentInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end) - { - $accountIds = $accounts->pluck('id')->toArray(); - - $sum - = $category - ->transactionjournals() - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->after($start) - ->before($end) - ->whereIn('transactions.account_id', $accountIds) - ->transactionTypes([TransactionType::WITHDRAWAL]) - ->get(['transaction_journals.*']) - ->sum('amount'); - - return $sum; - - } - - /** * @param Category $category * @param \Carbon\Carbon $start * @param \Carbon\Carbon $end @@ -260,38 +219,48 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate */ public function spentInPeriod(Category $category, Carbon $start, Carbon $end) { - $cache = new CacheProperties; // we must cache this. - $cache->addProperty($category->id); - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty('spentInPeriod'); - - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $sum = $category->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->before($end)->after($start)->get(['transaction_journals.*']) ->sum( 'amount' ); - $cache->store($sum); - return $sum; } /** - * Corrected for tags + * Returns an array with the following key:value pairs: + * + * yyyy-mm-dd: + * + * Where yyyy-mm-dd is the date and is the money spent using DEPOSITS in the $category + * from all the users accounts. * * @param Category $category - * @param Carbon $date + * @param Carbon $start + * @param Carbon $end * - * @return string + * @return array */ - public function spentOnDaySum(Category $category, Carbon $date) + public function spentPerDay(Category $category, Carbon $start, Carbon $end) { - return $category->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->onDate($date)->get(['transaction_journals.*'])->sum('amount'); + /** @var Collection $query */ + $query = Auth::user()->transactionJournals() + ->transactionTypes([TransactionType::WITHDRAWAL]) + ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->where('transactions.amount', '<', 0) + ->before($end) + ->after($start) + ->where('category_transaction_journal.category_id', $category->id) + ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); + + $return = []; + foreach ($query->toArray() as $entry) { + $return[$entry['dateFormatted']] = $entry['sum']; + } + + return $return; } /** diff --git a/app/Repositories/Category/SingleCategoryRepositoryInterface.php b/app/Repositories/Category/SingleCategoryRepositoryInterface.php index 4c5a4ffa2a..d2e233da30 100644 --- a/app/Repositories/Category/SingleCategoryRepositoryInterface.php +++ b/app/Repositories/Category/SingleCategoryRepositoryInterface.php @@ -50,6 +50,8 @@ interface SingleCategoryRepositoryInterface public function destroy(Category $category); /** + * @deprecated + * * @param Category $category * @param \Carbon\Carbon $start * @param \Carbon\Carbon $end @@ -58,29 +60,22 @@ interface SingleCategoryRepositoryInterface */ public function earnedInPeriod(Category $category, Carbon $start, Carbon $end); - /** - * Calculate how much is earned in this period. + * Returns an array with the following key:value pairs: * - * @param Category $category - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end + * yyyy-mm-dd: * - * @return string - */ - public function earnedInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end); - - /** - * - * Corrected for tags. + * Where yyyy-mm-dd is the date and is the money earned using DEPOSITS in the $category + * from all the users accounts. * * @param Category $category - * @param Carbon $date + * @param Carbon $start + * @param Carbon $end * - * @return float + * @return array */ - public function earnedOnDaySum(Category $category, Carbon $date); + public function earnedPerDay(Category $category, Carbon $start, Carbon $end); + /** * @param Category $category @@ -117,6 +112,8 @@ interface SingleCategoryRepositoryInterface public function getLatestActivity(Category $category); /** + * @deprecated + * * @param Category $category * @param \Carbon\Carbon $start * @param \Carbon\Carbon $end @@ -126,27 +123,21 @@ interface SingleCategoryRepositoryInterface public function spentInPeriod(Category $category, Carbon $start, Carbon $end); /** - * Calculates how much is spent in this period. + * Returns an array with the following key:value pairs: * - * @param Category $category - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end + * yyyy-mm-dd: * - * @return string - */ - public function spentInPeriodForAccounts(Category $category, Collection $accounts, Carbon $start, Carbon $end); - - /** - * - * Corrected for tags. + * Where yyyy-mm-dd is the date and is the money spent using WITHDRAWALS in the $category + * from all the users accounts. * * @param Category $category - * @param Carbon $date + * @param Carbon $start + * @param Carbon $end * - * @return float + * @return array */ - public function spentOnDaySum(Category $category, Carbon $date); + public function spentPerDay(Category $category, Carbon $start, Carbon $end); + /** * @param array $data From 1b3592d9596033e542098889002cf58d3b9745c9 Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 31 Dec 2015 07:49:19 +0100 Subject: [PATCH 23/62] Optimise chart. --- .../Controllers/Chart/CategoryController.php | 43 +++++++++++++++++-- .../Category/SingleCategoryRepository.php | 8 +--- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index bc37dc0517..2271330061 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -63,12 +63,18 @@ class CategoryController extends Controller if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore } + $spentArray = $repository->spentPerDay($category, $start, $end); + $earnedArray = $repository->earnedPerDay($category, $start, $end); + while ($start <= $end) { $currentEnd = Navigation::endOfPeriod($start, $range); - $spent = $repository->spentInPeriod($category, $start, $currentEnd); - $earned = $repository->earnedInPeriod($category, $start, $currentEnd); - $date = Navigation::periodShow($start, $range); + + // get the sum from $spentArray and $earnedArray: + $spent = $this->getSumOfRange($start, $currentEnd, $spentArray); + $earned = $this->getSumOfRange($start, $currentEnd, $earnedArray); + + $date = Navigation::periodShow($start, $range); $entries->push([clone $start, $date, $spent, $earned]); $start = Navigation::addPeriod($start, $range, 0); } @@ -85,6 +91,7 @@ class CategoryController extends Controller } + /** * Show this month's category overview. * @@ -251,9 +258,9 @@ class CategoryController extends Controller $entries = new Collection; // get amount earned in period, grouped by day. + // get amount spent in period, grouped by day. $spentArray = $repository->spentPerDay($category, $start, $end); $earnedArray = $repository->earnedPerDay($category, $start, $end); - // get amount spent in period, grouped by day. while ($start <= $end) { $str = $start->format('Y-m-d'); @@ -453,4 +460,32 @@ class CategoryController extends Controller return $data; } + /** + * Take the array as returned by SingleCategoryRepositoryInterface::spentPerDay and SingleCategoryRepositoryInterface::earnedByDay + * and sum up everything in the array in the given range. + * + * @param Carbon $start + * @param Carbon $end + * @param array $array + * + * @return string + */ + protected function getSumOfRange(Carbon $start, Carbon $end, array $array) + { + bcscale(2); + $sum = '0'; + $currentStart = clone $start; // to not mess with the original one + $currentEnd = clone $end; // to not mess with the original one + + while ($currentStart <= $currentEnd) { + $date = $currentStart->format('Y-m-d'); + if (isset($array[$date])) { + $sum = bcadd($sum, $array[$date]); + } + $currentStart->addDay(); + } + + return $sum; + } + } diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php index eca6aafec8..41b237a07f 100644 --- a/app/Repositories/Category/SingleCategoryRepository.php +++ b/app/Repositories/Category/SingleCategoryRepository.php @@ -107,14 +107,12 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate public function earnedPerDay(Category $category, Carbon $start, Carbon $end) { /** @var Collection $query */ - $query = Auth::user()->transactionJournals() + $query = $category->transactionJournals() ->transactionTypes([TransactionType::DEPOSIT]) - ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.amount', '>', 0) ->before($end) ->after($start) - ->where('category_transaction_journal.category_id', $category->id) ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); $return = []; @@ -245,14 +243,12 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate public function spentPerDay(Category $category, Carbon $start, Carbon $end) { /** @var Collection $query */ - $query = Auth::user()->transactionJournals() + $query = $category->transactionJournals() ->transactionTypes([TransactionType::WITHDRAWAL]) - ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.amount', '<', 0) ->before($end) ->after($start) - ->where('category_transaction_journal.category_id', $category->id) ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); $return = []; From cc810a5b6ffe9def2304d22505413e511cd3c182 Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 31 Dec 2015 07:54:11 +0100 Subject: [PATCH 24/62] Renamed a chart to be more consistent with the others. --- app/Http/routes.php | 2 +- public/js/piggy-banks.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/routes.php b/app/Http/routes.php index 21dec7d669..07439361ba 100644 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -422,7 +422,7 @@ Route::group( Route::get('/chart/category/{category}/all', ['uses' => 'Chart\CategoryController@all']); // piggy banks: - Route::get('/chart/piggyBank/{piggyBank}', ['uses' => 'Chart\PiggyBankController@history']); + Route::get('/chart/piggy-bank/{piggyBank}', ['uses' => 'Chart\PiggyBankController@history']); // reports: Route::get('/chart/report/in-out/{reportType}/{start_date}/{end_date}/{accountList}', ['uses' => 'Chart\ReportController@yearInOut']); diff --git a/public/js/piggy-banks.js b/public/js/piggy-banks.js index 4b8aa3ab6b..72789f59b2 100644 --- a/public/js/piggy-banks.js +++ b/public/js/piggy-banks.js @@ -15,7 +15,7 @@ $(function () { $('.removeMoney').on('click', removeMoney); if (typeof(lineChart) === 'function' && typeof(piggyBankID) !== 'undefined') { - lineChart('chart/piggyBank/' + piggyBankID, 'piggy-bank-history'); + lineChart('chart/piggy-bank/' + piggyBankID, 'piggy-bank-history'); } $('#sortable tbody').sortable( From aac5c2b13ca7d5ddb16d49577998974b49c83820 Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 31 Dec 2015 08:26:04 +0100 Subject: [PATCH 25/62] Optimised another chart. --- app/Helpers/Report/ReportQuery.php | 93 +++++++++++++++++++ app/Helpers/Report/ReportQueryInterface.php | 24 +++++ .../Controllers/Chart/ReportController.php | 47 ++++++---- 3 files changed, 148 insertions(+), 16 deletions(-) diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php index ae484d8095..f6a7119217 100644 --- a/app/Helpers/Report/ReportQuery.php +++ b/app/Helpers/Report/ReportQuery.php @@ -5,6 +5,7 @@ namespace FireflyIII\Helpers\Report; use Auth; use Carbon\Carbon; use Crypt; +use DB; use FireflyIII\Models\Account; use FireflyIII\Models\Budget; use FireflyIII\Models\TransactionJournal; @@ -101,6 +102,7 @@ class ReportQuery implements ReportQueryInterface return $query; } + /** * This method works the same way as ReportQueryInterface::incomeInPeriod does, but instead of returning results * will simply list the transaction journals only. This should allow any follow up counting to be accurate with @@ -231,4 +233,95 @@ class ReportQuery implements ReportQueryInterface return $data; } + + + /** + * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) + * grouped by month like so: "2015-01" => '123.45' + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function spentPerMonth(Collection $accounts, Carbon $start, Carbon $end) + { + $ids = $accounts->pluck('id')->toArray(); + $query = Auth::user()->transactionjournals() + ->leftJoin( + 'transactions AS t_from', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 't_from.transaction_journal_id')->where('t_from.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions AS t_to', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 't_to.transaction_journal_id')->where('t_to.amount', '>', 0); + } + ) + ->whereIn('t_from.account_id', $ids) + ->whereNotIn('t_to.account_id', $ids) + ->after($start) + ->before($end) + ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) + ->groupBy('dateFormatted') + ->get( + [ + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") AS `dateFormatted`'), + DB::Raw('SUM(`t_from`.`amount`) AS `sum`') + ] + ); + $array = []; + foreach ($query as $result) { + $array[$result->dateFormatted] = $result->sum; + } + + return $array; + + } + + /** + * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) + * grouped by month like so: "2015-01" => '123.45' + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function earnedPerMonth(Collection $accounts, Carbon $start, Carbon $end) + { + $ids = $accounts->pluck('id')->toArray(); + $query = Auth::user()->transactionjournals() + ->leftJoin( + 'transactions AS t_from', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 't_from.transaction_journal_id')->where('t_from.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions AS t_to', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 't_to.transaction_journal_id')->where('t_to.amount', '>', 0); + } + ) + ->whereIn('t_to.account_id', $ids) + ->whereNotIn('t_from.account_id', $ids) + ->after($start) + ->before($end) + ->transactionTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) + ->groupBy('dateFormatted') + ->get( + [ + DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") AS `dateFormatted`'), + DB::Raw('SUM(`t_from`.`amount`) AS `sum`') + ] + ); + $array = []; + foreach ($query as $result) { + $array[$result->dateFormatted] = $result->sum; + } + + return $array; + } + } diff --git a/app/Helpers/Report/ReportQueryInterface.php b/app/Helpers/Report/ReportQueryInterface.php index d7fa9cf085..ed9892534f 100644 --- a/app/Helpers/Report/ReportQueryInterface.php +++ b/app/Helpers/Report/ReportQueryInterface.php @@ -65,5 +65,29 @@ interface ReportQueryInterface */ public function spentNoBudget(Account $account, Carbon $start, Carbon $end); + /** + * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) + * grouped by month like so: "2015-01" => '123.45' + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function spentPerMonth(Collection $accounts, Carbon $start, Carbon $end); + + /** + * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) + * grouped by month like so: "2015-01" => '123.45' + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function earnedPerMonth(Collection $accounts, Carbon $start, Carbon $end); + } diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php index f289262064..08492fd4e1 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -55,20 +55,18 @@ class ReportController extends Controller return Response::json($cache->get()); // @codeCoverageIgnore } + // spent per month, and earned per month. For a specific set of accounts + // grouped by month + $spentArray = $query->spentPerMonth($accounts, $start, $end); + $earnedArray = $query->earnedPerMonth($accounts, $start, $end); - // per year? + // per year? put all months together. if ($start->diffInMonths($end) > 12) { - $entries = new Collection; while ($start < $end) { - $startOfYear = clone $start; - $startOfYear->startOfYear(); - $endOfYear = clone $startOfYear; - $endOfYear->endOfYear(); - // total income and total expenses: - $incomeSum = $query->incomeInPeriod($startOfYear, $endOfYear, $accounts)->sum('amount_positive'); - $expenseSum = $query->expenseInPeriod($startOfYear, $endOfYear, $accounts)->sum('amount_positive'); + $incomeSum = $this->pluckFromArray($start->year, $earnedArray); + $expenseSum = $this->pluckFromArray($start->year, $spentArray); $entries->push([clone $start, $incomeSum, $expenseSum]); $start->addYear(); @@ -77,16 +75,14 @@ class ReportController extends Controller $data = $this->generator->multiYearInOut($entries); $cache->store($data); } else { - // per month: + // per month? simply use each month. $entries = new Collection; while ($start < $end) { - $month = clone $start; - $month->endOfMonth(); // total income and total expenses: - $incomeSum = $query->incomeInPeriod($start, $month, $accounts)->sum('amount_positive'); - $expenseSum = $query->expenseInPeriod($start, $month, $accounts)->sum('amount_positive'); - + $date = $start->format('Y-m'); + $incomeSum = isset($earnedArray[$date]) ? $earnedArray[$date] : 0; + $expenseSum = isset($spentArray[$date]) ? $spentArray[$date] : 0; $entries->push([clone $start, $incomeSum, $expenseSum]); $start->addMonth(); @@ -96,7 +92,6 @@ class ReportController extends Controller $cache->store($data); } - return Response::json($data); } @@ -174,4 +169,24 @@ class ReportController extends Controller return Response::json($data); } + + /** + * @param int $year + * @param array $set + * + * @return string + */ + protected function pluckFromArray($year, array $set) + { + bcscale(2); + $sum = '0'; + foreach ($set as $date => $amount) { + if (substr($date, 0, 4) == $year) { + $sum = bcadd($sum, $amount); + } + } + + return $sum; + + } } From 25747fbcf202d3b58c76ad3120e1ce3eb767bcaf Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 31 Dec 2015 08:31:28 +0100 Subject: [PATCH 26/62] And optimised another chart. Amounts are slightly different. Will investigate --- app/Helpers/Report/ReportQuery.php | 2 +- app/Http/Controllers/Chart/ReportController.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php index f6a7119217..8015b2e150 100644 --- a/app/Helpers/Report/ReportQuery.php +++ b/app/Helpers/Report/ReportQuery.php @@ -313,7 +313,7 @@ class ReportQuery implements ReportQueryInterface ->get( [ DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") AS `dateFormatted`'), - DB::Raw('SUM(`t_from`.`amount`) AS `sum`') + DB::Raw('SUM(`t_to`.`amount`) AS `sum`') ] ); $array = []; diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php index 08492fd4e1..aaa03f3446 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -66,7 +66,7 @@ class ReportController extends Controller while ($start < $end) { $incomeSum = $this->pluckFromArray($start->year, $earnedArray); - $expenseSum = $this->pluckFromArray($start->year, $spentArray); + $expenseSum = $this->pluckFromArray($start->year, $spentArray) * -1; $entries->push([clone $start, $incomeSum, $expenseSum]); $start->addYear(); @@ -82,7 +82,7 @@ class ReportController extends Controller // total income and total expenses: $date = $start->format('Y-m'); $incomeSum = isset($earnedArray[$date]) ? $earnedArray[$date] : 0; - $expenseSum = isset($spentArray[$date]) ? $spentArray[$date] : 0; + $expenseSum = isset($spentArray[$date]) ? ($spentArray[$date]*-1) : 0; $entries->push([clone $start, $incomeSum, $expenseSum]); $start->addMonth(); From f98921da46b662d8283d8d39784a864f2e997507 Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 31 Dec 2015 08:36:01 +0100 Subject: [PATCH 27/62] Optimised summary chart. --- .../Controllers/Chart/ReportController.php | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php index aaa03f3446..ebd258c680 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -82,7 +82,7 @@ class ReportController extends Controller // total income and total expenses: $date = $start->format('Y-m'); $incomeSum = isset($earnedArray[$date]) ? $earnedArray[$date] : 0; - $expenseSum = isset($spentArray[$date]) ? ($spentArray[$date]*-1) : 0; + $expenseSum = isset($spentArray[$date]) ? ($spentArray[$date] * -1) : 0; $entries->push([clone $start, $incomeSum, $expenseSum]); $start->addMonth(); @@ -119,24 +119,22 @@ class ReportController extends Controller if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore } - - $income = '0'; - $expense = '0'; - $count = 0; + // spent per month, and earned per month. For a specific set of accounts + // grouped by month + $spentArray = $query->spentPerMonth($accounts, $start, $end); + $earnedArray = $query->earnedPerMonth($accounts, $start, $end); + $income = '0'; + $expense = '0'; + $count = 0; bcscale(2); if ($start->diffInMonths($end) > 12) { // per year while ($start < $end) { - $startOfYear = clone $start; - $startOfYear->startOfYear(); - $endOfYear = clone $startOfYear; - $endOfYear->endOfYear(); - // total income and total expenses: - $currentIncome = $query->incomeInPeriod($startOfYear, $endOfYear, $accounts)->sum('amount_positive'); - $currentExpense = $query->expenseInPeriod($startOfYear, $endOfYear, $accounts)->sum('amount_positive'); + $currentIncome = $this->pluckFromArray($start->year, $earnedArray); + $currentExpense = $this->pluckFromArray($start->year, $spentArray) * -1; $income = bcadd($income, $currentIncome); $expense = bcadd($expense, $currentExpense); @@ -149,11 +147,9 @@ class ReportController extends Controller } else { // per month! while ($start < $end) { - $month = clone $start; - $month->endOfMonth(); - // total income and total expenses: - $currentIncome = $query->incomeInPeriod($start, $month, $accounts)->sum('amount_positive'); - $currentExpense = $query->expenseInPeriod($start, $month, $accounts)->sum('amount_positive'); + $date = $start->format('Y-m'); + $currentIncome = isset($earnedArray[$date]) ? $earnedArray[$date] : 0; + $currentExpense = isset($spentArray[$date]) ? ($spentArray[$date] * -1) : 0; $income = bcadd($income, $currentIncome); $expense = bcadd($expense, $currentExpense); From a6594358d8e30b35a6913c739a140af584ce5aed Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 31 Dec 2015 17:20:54 +0100 Subject: [PATCH 28/62] Use a lot less queries --- app/Http/Controllers/AccountController.php | 30 +++++++++---------- app/Http/Controllers/CategoryController.php | 12 ++++++-- .../Controllers/Chart/CategoryController.php | 26 ---------------- app/Http/Controllers/Controller.php | 29 ++++++++++++++++++ app/Support/Navigation.php | 10 +++---- 5 files changed, 58 insertions(+), 49 deletions(-) diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php index 11d207773d..d80f2a021b 100644 --- a/app/Http/Controllers/AccountController.php +++ b/app/Http/Controllers/AccountController.php @@ -56,8 +56,8 @@ class AccountController extends Controller } /** - * @param ARI $repository - * @param Account $account + * @param ARI $repository + * @param Account $account * * @return \Illuminate\View\View */ @@ -77,8 +77,8 @@ class AccountController extends Controller } /** - * @param ARI $repository - * @param Account $account + * @param ARI $repository + * @param Account $account * * @return \Illuminate\Http\RedirectResponse */ @@ -98,8 +98,8 @@ class AccountController extends Controller } /** - * @param ARI $repository - * @param Account $account + * @param ARI $repository + * @param Account $account * * @return \Illuminate\View\View */ @@ -143,7 +143,7 @@ class AccountController extends Controller } /** - * @param ARI $repository + * @param ARI $repository * @param $what * * @return \Illuminate\View\View @@ -184,8 +184,8 @@ class AccountController extends Controller } /** - * @param ARI $repository - * @param Account $account + * @param ARI $repository + * @param Account $account * * @return \Illuminate\View\View */ @@ -195,7 +195,7 @@ class AccountController extends Controller $subTitleIcon = Config::get('firefly.subTitlesByIdentifier.' . $account->accountType->type); $what = Config::get('firefly.shortNamesByFullName.' . $account->accountType->type); $journals = $repository->getJournals($account, $page); - $subTitle = trans('firefly.details_for_' . $what, ['name' => $account->name]); + $subTitle = trans('firefly.details_for_' . $what, ['name' => $account->name]); $journals->setPath('accounts/show/' . $account->id); @@ -203,8 +203,8 @@ class AccountController extends Controller } /** - * @param AccountFormRequest $request - * @param ARI $repository + * @param AccountFormRequest $request + * @param ARI $repository * * @return \Illuminate\Http\RedirectResponse */ @@ -242,9 +242,9 @@ class AccountController extends Controller } /** - * @param AccountFormRequest $request - * @param ARI $repository - * @param Account $account + * @param AccountFormRequest $request + * @param ARI $repository + * @param Account $account * * @return \Illuminate\Http\RedirectResponse */ diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php index fe7a1ebeae..d564789c21 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryController.php @@ -202,6 +202,12 @@ class CategoryController extends Controller $cache->addProperty($end); $cache->addProperty('category-show'); $cache->addProperty($category->id); + + // get all spent and earned data: + // get amount earned in period, grouped by day. + $spentArray = $repository->spentPerDay($category, $start, $end); + $earnedArray = $repository->earnedPerDay($category, $start, $end); + if ($cache->has()) { $entries = $cache->get(); } else { @@ -210,9 +216,9 @@ class CategoryController extends Controller $end = Navigation::startOfPeriod($end, $range); $currentEnd = Navigation::endOfPeriod($end, $range); - // here do something. - $spent = $repository->spentInPeriod($category, $end, $currentEnd); - $earned = $repository->earnedInPeriod($category, $end, $currentEnd); + // get data from spentArray: + $spent = $this->getSumOfRange($end, $currentEnd, $spentArray); + $earned = $this->getSumOfRange($end, $currentEnd, $earnedArray); $dateStr = $end->format('Y-m-d'); $dateName = Navigation::periodShow($end, $range); $entries->push([$dateStr, $dateName, $spent, $earned]); diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 2271330061..0b75b0b328 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -460,32 +460,6 @@ class CategoryController extends Controller return $data; } - /** - * Take the array as returned by SingleCategoryRepositoryInterface::spentPerDay and SingleCategoryRepositoryInterface::earnedByDay - * and sum up everything in the array in the given range. - * - * @param Carbon $start - * @param Carbon $end - * @param array $array - * - * @return string - */ - protected function getSumOfRange(Carbon $start, Carbon $end, array $array) - { - bcscale(2); - $sum = '0'; - $currentStart = clone $start; // to not mess with the original one - $currentEnd = clone $end; // to not mess with the original one - while ($currentStart <= $currentEnd) { - $date = $currentStart->format('Y-m-d'); - if (isset($array[$date])) { - $sum = bcadd($sum, $array[$date]); - } - $currentStart->addDay(); - } - - return $sum; - } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 465c38c441..55d0bc1765 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -1,6 +1,7 @@ format('Y-m-d'); + if (isset($array[$date])) { + $sum = bcadd($sum, $array[$date]); + } + $currentStart->addDay(); + } + + return $sum; + } } diff --git a/app/Support/Navigation.php b/app/Support/Navigation.php index 50e0faf2b3..25d8f93298 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -100,11 +100,11 @@ class Navigation /** * - * @param Carbon $theCurrentEnd + * @param \Carbon\Carbon $theCurrentEnd * @param $repeatFreq - * @param Carbon $maxDate + * @param \Carbon\Carbon $maxDate * - * @return Carbon + * @return \Carbon\Carbon */ public function endOfX(Carbon $theCurrentEnd, $repeatFreq, Carbon $maxDate = null) { @@ -218,11 +218,11 @@ class Navigation } /** - * @param Carbon $theDate + * @param \Carbon\Carbon $theDate * @param $repeatFreq * @param int $subtract * - * @return Carbon + * @return \Carbon\Carbon * @throws FireflyException */ public function subtractPeriod(Carbon $theDate, $repeatFreq, $subtract = 1) From 3dcdacc3b801f90e97a7098f52793a17d879008c Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 31 Dec 2015 17:46:34 +0100 Subject: [PATCH 29/62] Cleared lots of queries. In some cases, from 1400 back to 300. And those 300 have a different cause which is next. --- app/Http/Controllers/BudgetController.php | 38 +++++++++-- app/Repositories/Budget/BudgetRepository.php | 65 +++++++++++++++++- .../Budget/BudgetRepositoryInterface.php | 32 +++++++++ resources/twig/budgets/show.twig | 68 +++++++++---------- 4 files changed, 159 insertions(+), 44 deletions(-) diff --git a/app/Http/Controllers/BudgetController.php b/app/Http/Controllers/BudgetController.php index 1cf1e15225..fb07d200b3 100644 --- a/app/Http/Controllers/BudgetController.php +++ b/app/Http/Controllers/BudgetController.php @@ -8,6 +8,7 @@ use FireflyIII\Models\Budget; use FireflyIII\Models\LimitRepetition; use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; +use Illuminate\Support\Collection; use Input; use Navigation; use Preferences; @@ -132,9 +133,9 @@ class BudgetController extends Controller } /** - * @param BudgetRepositoryInterface $repository + * @param BudgetRepositoryInterface $repository * - * @param ARI $accountRepository + * @param ARI $accountRepository * * @return \Illuminate\View\View */ @@ -232,13 +233,38 @@ class BudgetController extends Controller $journals = $repository->getJournals($budget, $repetition); if (is_null($repetition->id)) { - $limits = $repository->getBudgetLimits($budget); - $subTitle = e($budget->name); + $start = $repository->firstActivity($budget); + $end = new Carbon; + $set = $budget->limitrepetitions()->orderBy('startdate','DESC')->get(); + //$set = $repository->getBudgetLimits($budget); + //$subTitle = e($budget->name); } else { - $limits = [$repetition->budgetLimit]; - $subTitle = trans('firefly.budget_in_month', ['name' => $budget->name, 'month' => $repetition->startdate->formatLocalized($this->monthFormat)]); + $start = $repetition->startdate; + $end = $repetition->enddate; + $set = new Collection([$repetition]); + // $spentArray = $repository->spentPerDay($budget, $start, $end); + // $budgetLimit = $repetition->budgetLimit; + // $budgetLimit->spent = $this->getSumOfRange($start, $end, $spentArray); // bit weird but it works. + // $limits = new Collection([$budgetLimit]); + //$subTitle = trans('firefly.budget_in_month', ['name' => $budget->name, 'month' => $repetition->startdate->formatLocalized($this->monthFormat)]); } + $spentArray = $repository->spentPerDay($budget, $start, $end); + $limits = new Collection(); + + /** @var LimitRepetition $entry */ + foreach ($set as $entry) { + $entry->spent = $this->getSumOfRange($entry->startdate, $entry->enddate, $spentArray); + $limits->push($entry); + } + + // loop limits and set the amount spent for each limit. + // /** @var BudgetLimit $budgetLimit */ + // foreach ($set as $budgetLimit) { + // $start = $budgetLimit->startdate; + // $end = $budgetLimit->lim + // } + $journals->setPath('/budgets/show/' . $budget->id); return view('budgets.show', compact('limits', 'budget', 'repetition', 'journals', 'subTitle')); diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index c5a3e857c4..cfcbf75359 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -5,7 +5,6 @@ namespace FireflyIII\Repositories\Budget; use Auth; use Carbon\Carbon; use DB; -use FireflyIII\Models\Account; use FireflyIII\Models\Budget; use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\LimitRepetition; @@ -185,6 +184,33 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn } + /** + * @param Budget $budget + * + * @return Carbon + */ + public function firstActivity(Budget $budget) + { + $first = $budget->transactionjournals()->orderBy('date', 'ASC')->first(); + if ($first) { + return $first->date; + } + + return new Carbon; + } + + /** + * Get a collection of all the limit repetitions belonging to this $budget. + * + * @param Budget $budget + * + * @return Collection + */ + public function getBudgetReps(Budget $budget) { + $set = $budget->limitrepetitions()->count(); + var_dump($set); + } + /** * @param Budget $budget * @param Carbon $start @@ -213,6 +239,41 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn return $budget->budgetLimits()->orderBy('startdate', 'DESC')->get(); } + + /** + * Returns an array with the following key:value pairs: + * + * yyyy-mm-dd: + * + * Where yyyy-mm-dd is the date and is the money spent using DEPOSITS in the $budget + * from all the users accounts. + * + * @param Budget $budget + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function spentPerDay(Budget $budget, Carbon $start, Carbon $end) + { + /** @var Collection $query */ + $query = $budget->transactionJournals() + ->transactionTypes([TransactionType::WITHDRAWAL]) + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->where('transactions.amount', '<', 0) + ->before($end) + ->after($start) + ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); + + $return = []; + foreach ($query->toArray() as $entry) { + $return[$entry['dateFormatted']] = $entry['sum']; + } + + return $return; + } + + /** * @return Collection */ @@ -617,7 +678,7 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn */ public function getBudgetsAndExpensesPerYear(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end) { - $ids = $accounts->pluck('id')->toArray(); + $ids = $accounts->pluck('id')->toArray(); $budgetIds = $budgets->pluck('id')->toArray(); /** @var Collection $set */ diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index c1109188f7..c228df2ce3 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -32,6 +32,22 @@ interface BudgetRepositoryInterface */ public function getExpensesPerDay(Budget $budget, Carbon $start, Carbon $end); + /** + * @param Budget $budget + * + * @return Carbon + */ + public function firstActivity(Budget $budget); + + /** + * Get a collection of all the limit repetitions belonging to this $budget. + * + * @param Budget $budget + * + * @return Collection + */ + public function getBudgetReps(Budget $budget); + /** * Returns the expenses for this budget grouped per month, with the date * in "date" (a string, not a Carbon) and the amount in "dailyAmount". @@ -44,6 +60,22 @@ interface BudgetRepositoryInterface */ public function getExpensesPerMonth(Budget $budget, Carbon $start, Carbon $end); + /** + * Returns an array with the following key:value pairs: + * + * yyyy-mm-dd: + * + * Where yyyy-mm-dd is the date and is the money spent using WITHDRAWALS in the $budget + * from all the users accounts. + * + * @param Budget $budget + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function spentPerDay(Budget $budget, Carbon $start, Carbon $end); + /** * @param Budget $budget * diff --git a/resources/twig/budgets/show.twig b/resources/twig/budgets/show.twig index 173b9a1d4e..666b874300 100644 --- a/resources/twig/budgets/show.twig +++ b/resources/twig/budgets/show.twig @@ -44,47 +44,43 @@ {% endif %} {% for limit in limits %} - {% for rep in limit.limitRepetitions %} - {% set spentInRep = spentInRepetition(rep) %} -
- -
-
-
- {{ 'amount'|_ }}: {{ rep.amount|formatAmount }} -
-
- {{ 'spent'|_ }}: {{ spentInRep|formatAmount }} -
+
+ +
+
+
+ {{ 'amount'|_ }}: {{ limit.amount|formatAmount }}
-
-
- {% set overspent = rep.amount + spentInRep < 0 %} +
+ {{ 'spent'|_ }}: {{ limit.spent|formatAmount }} +
+
+
+
+ {% set overspent = limit.amount + limit.spent < 0 %} - {% if overspent %} - {% set pct = (spentInRep != 0 ? (rep.amount / (spentInRep*-1))*100 : 0) %} -
-
-
-
- {% else %} - {% set amount = rep.amount %} - {% set pct = (amount != 0 ? (((spentInRep*-1) / amount)*100) : 0) %} -
-
-
- {% endif %} -
+ {% if overspent %} + {% set pct = (limit.spent != 0 ? (limit.amount / (limit.spent*-1))*100 : 0) %} +
+
+
+
+ {% else %} + {% set pct = (limit.amount != 0 ? (((limit.spent*-1) / limit.amount)*100) : 0) %} +
+
+
+ {% endif %}
- {% endfor %} +
{% endfor %} {% if limits|length == 1 %} From 068fc32cb2da2602dc15703971b1d82eca8f993f Mon Sep 17 00:00:00 2001 From: James Cole Date: Thu, 31 Dec 2015 20:12:49 +0100 Subject: [PATCH 30/62] Some query cleaning up. --- app/Helpers/Collection/Expense.php | 5 +- app/Helpers/Collection/Income.php | 7 +- app/Helpers/Report/ReportHelper.php | 110 +++++++++++++++-- app/Helpers/Report/ReportQuery.php | 126 ++++++++++---------- app/Helpers/Report/ReportQueryInterface.php | 24 ++-- app/Http/Controllers/ReportController.php | 6 +- 6 files changed, 184 insertions(+), 94 deletions(-) diff --git a/app/Helpers/Collection/Expense.php b/app/Helpers/Collection/Expense.php index a703ee7a15..ce489c5118 100644 --- a/app/Helpers/Collection/Expense.php +++ b/app/Helpers/Collection/Expense.php @@ -2,6 +2,7 @@ namespace FireflyIII\Helpers\Collection; +use Crypt; use FireflyIII\Models\TransactionJournal; use Illuminate\Support\Collection; use stdClass; @@ -36,7 +37,7 @@ class Expense bcscale(2); $accountId = $entry->account_id; - $amount = strval(round($entry->amount, 2)); + $amount = strval(round($entry->journalAmount, 2)); if (bccomp('0', $amount) === -1) { $amount = bcmul($amount, '-1'); } @@ -44,7 +45,7 @@ class Expense if (!$this->expenses->has($accountId)) { $newObject = new stdClass; $newObject->amount = $amount; - $newObject->name = $entry->name; + $newObject->name = Crypt::decrypt($entry->account_name); $newObject->count = 1; $newObject->id = $accountId; $this->expenses->put($accountId, $newObject); diff --git a/app/Helpers/Collection/Income.php b/app/Helpers/Collection/Income.php index 9d1389dfcb..6a66de8fef 100644 --- a/app/Helpers/Collection/Income.php +++ b/app/Helpers/Collection/Income.php @@ -2,6 +2,7 @@ namespace FireflyIII\Helpers\Collection; +use Crypt; use FireflyIII\Models\TransactionJournal; use Illuminate\Support\Collection; use stdClass; @@ -38,15 +39,15 @@ class Income $accountId = $entry->account_id; if (!$this->incomes->has($accountId)) { $newObject = new stdClass; - $newObject->amount = strval(round($entry->amount_positive, 2)); - $newObject->name = $entry->name; + $newObject->amount = strval(round($entry->journalAmount, 2)); + $newObject->name = Crypt::decrypt($entry->account_name); $newObject->count = 1; $newObject->id = $accountId; $this->incomes->put($accountId, $newObject); } else { bcscale(2); $existing = $this->incomes->get($accountId); - $existing->amount = bcadd($existing->amount, $entry->amount_positive); + $existing->amount = bcadd($existing->amount, $entry->journalAmount); $existing->count++; $this->incomes->put($accountId, $existing); } diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 7dc00d2fd3..00f58a310a 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -2,7 +2,9 @@ namespace FireflyIII\Helpers\Report; +use Auth; use Carbon\Carbon; +use DB; use FireflyIII\Helpers\Collection\Account as AccountCollection; use FireflyIII\Helpers\Collection\Balance; use FireflyIII\Helpers\Collection\BalanceEntry; @@ -19,8 +21,9 @@ use FireflyIII\Models\Account; use FireflyIII\Models\Bill; use FireflyIII\Models\Budget as BudgetModel; use FireflyIII\Models\LimitRepetition; +use FireflyIII\Models\TransactionType; +use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; -use Steam; /** * Class ReportHelper @@ -127,21 +130,59 @@ class ReportHelper implements ReportHelperInterface $startAmount = '0'; $endAmount = '0'; $diff = '0'; + $ids = $accounts->pluck('id')->toArray(); + + $yesterday = clone $start; + $yesterday->subDay(); + bcscale(2); + // get balances for start. + $startSet = Account::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id') + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->whereIn('accounts.id', $ids) + ->whereNull('transaction_journals.deleted_at') + ->whereNull('transactions.deleted_at') + ->where('transaction_journals.date', '<=', $yesterday->format('Y-m-d')) + ->groupBy('accounts.id') + ->get(['accounts.id', DB::Raw('SUM(`transactions`.`amount`) as `balance`')]); + + // and for end: + $endSet = Account::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id') + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->whereIn('accounts.id', $ids) + ->whereNull('transaction_journals.deleted_at') + ->whereNull('transactions.deleted_at') + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->groupBy('accounts.id') + ->get(['accounts.id', DB::Raw('SUM(`transactions`.`amount`) as `balance`')]); + + $accounts->each( - function (Account $account) use ($start, $end) { + function (Account $account) use ($startSet, $endSet) { /** * The balance for today always incorporates transactions * made on today. So to get todays "start" balance, we sub one * day. */ - $yesterday = clone $start; - $yesterday->subDay(); + // + $currentStart = $startSet->filter( + function (Account $entry) use ($account) { + return $account->id == $entry->id; + } + ); + if ($currentStart->first()) { + $account->startBalance = $currentStart->first()->balance; + } - /** @noinspection PhpParamsInspection */ - $account->startBalance = Steam::balance($account, $yesterday); - $account->endBalance = Steam::balance($account, $end); + $currentEnd = $endSet->filter( + function (Account $entry) use ($account) { + return $account->id == $entry->id; + } + ); + if ($currentEnd->first()) { + $account->endBalance = $currentEnd->first()->balance; + } } ); @@ -174,9 +215,32 @@ class ReportHelper implements ReportHelperInterface public function getIncomeReport($start, $end, Collection $accounts) { $object = new Income; - $set = $this->query->incomeInPeriod($start, $end, $accounts); + + /* + * TODO move to ReportQuery class. + */ + $ids = $accounts->pluck('id')->toArray(); + $set = Auth::user()->transactionjournals() + ->leftJoin( + 'transactions as t_from', function (JoinClause $join) { + $join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions as t_to', function (JoinClause $join) { + $join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0); + } + ) + ->leftJoin('accounts', 't_from.account_id', '=', 'accounts.id') + ->transactionTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) + ->before($end) + ->after($start) + ->whereIn('t_to.account_id', $ids) + ->whereNotIn('t_from.account_id', $ids) + ->get(['transaction_journals.*', 't_to.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']); + foreach ($set as $entry) { - $object->addToTotal($entry->amount_positive); + $object->addToTotal($entry->journalAmount); $object->addOrCreateIncome($entry); } @@ -195,9 +259,33 @@ class ReportHelper implements ReportHelperInterface public function getExpenseReport($start, $end, Collection $accounts) { $object = new Expense; - $set = $this->query->expenseInPeriod($start, $end, $accounts); + + + /* + * TODO move to ReportQuery class. + */ + $ids = $accounts->pluck('id')->toArray(); + $set = Auth::user()->transactionjournals() + ->leftJoin( + 'transactions as t_from', function (JoinClause $join) { + $join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions as t_to', function (JoinClause $join) { + $join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0); + } + ) + ->leftJoin('accounts', 't_to.account_id', '=', 'accounts.id') + ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) + ->before($end) + ->after($start) + ->whereIn('t_from.account_id', $ids) + ->whereNotIn('t_to.account_id', $ids) + ->get(['transaction_journals.*', 't_from.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']); + foreach ($set as $entry) { - $object->addToTotal($entry->amount); // can be positive, if it's a transfer + $object->addToTotal($entry->journalAmount); // can be positive, if it's a transfer $object->addOrCreateExpense($entry); } diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php index 8015b2e150..de29c6ed29 100644 --- a/app/Helpers/Report/ReportQuery.php +++ b/app/Helpers/Report/ReportQuery.php @@ -103,69 +103,69 @@ class ReportQuery implements ReportQueryInterface } - /** - * This method works the same way as ReportQueryInterface::incomeInPeriod does, but instead of returning results - * will simply list the transaction journals only. This should allow any follow up counting to be accurate with - * regards to tags. It will only get the incomes to the specified accounts. - * - * @param Carbon $start - * @param Carbon $end - * @param Collection $accounts - * - * @return Collection - */ - public function incomeInPeriod(Carbon $start, Carbon $end, Collection $accounts) - { - $query = $this->queryJournalsWithTransactions($start, $end); - - $ids = []; - /** @var Account $account */ - foreach ($accounts as $account) { - $ids[] = $account->id; - } - - // OR is a deposit - // OR any transfer TO the accounts in $accounts, not FROM any of the accounts in $accounts. - $query->where( - function (Builder $query) use ($ids) { - $query->where( - function (Builder $q) { - $q->where('transaction_types.type', TransactionType::DEPOSIT); - } - ); - $query->orWhere( - function (Builder $q) use ($ids) { - $q->where('transaction_types.type', TransactionType::TRANSFER); - $q->whereNotIn('ac_from.id', $ids); - $q->whereIn('ac_to.id', $ids); - } - ); - } - ); - - // only include selected accounts. - $query->whereIn('ac_to.id', $ids); - $query->orderBy('transaction_journals.date'); - - // get everything - $data = $query->get( - ['transaction_journals.*', - 'transaction_types.type', 'ac_from.name as name', - 't_from.amount as from_amount', - 't_to.amount as to_amount', - 'ac_from.id as account_id', 'ac_from.encrypted as account_encrypted'] - ); - - $data->each( - function (TransactionJournal $journal) { - if (intval($journal->account_encrypted) == 1) { - $journal->name = Crypt::decrypt($journal->name); - } - } - ); - - return $data; - } +// /** +// * This method works the same way as ReportQueryInterface::incomeInPeriod does, but instead of returning results +// * will simply list the transaction journals only. This should allow any follow up counting to be accurate with +// * regards to tags. It will only get the incomes to the specified accounts. +// * +// * @param Carbon $start +// * @param Carbon $end +// * @param Collection $accounts +// * +// * @return Collection +// */ +// public function incomeInPeriod(Carbon $start, Carbon $end, Collection $accounts) +// { +// $query = $this->queryJournalsWithTransactions($start, $end); +// +// $ids = []; +// /** @var Account $account */ +// foreach ($accounts as $account) { +// $ids[] = $account->id; +// } +// +// // OR is a deposit +// // OR any transfer TO the accounts in $accounts, not FROM any of the accounts in $accounts. +// $query->where( +// function (Builder $query) use ($ids) { +// $query->where( +// function (Builder $q) { +// $q->where('transaction_types.type', TransactionType::DEPOSIT); +// } +// ); +// $query->orWhere( +// function (Builder $q) use ($ids) { +// $q->where('transaction_types.type', TransactionType::TRANSFER); +// $q->whereNotIn('ac_from.id', $ids); +// $q->whereIn('ac_to.id', $ids); +// } +// ); +// } +// ); +// +// // only include selected accounts. +// $query->whereIn('ac_to.id', $ids); +// $query->orderBy('transaction_journals.date'); +// +// // get everything +// $data = $query->get( +// ['transaction_journals.*', +// 'transaction_types.type', 'ac_from.name as name', +// 't_from.amount as from_amount', +// 't_to.amount as to_amount', +// 'ac_from.id as account_id', 'ac_from.encrypted as account_encrypted'] +// ); +// +// $data->each( +// function (TransactionJournal $journal) { +// if (intval($journal->account_encrypted) == 1) { +// $journal->name = Crypt::decrypt($journal->name); +// } +// } +// ); +// +// return $data; +// } /** * See ReportQueryInterface::incomeInPeriod diff --git a/app/Helpers/Report/ReportQueryInterface.php b/app/Helpers/Report/ReportQueryInterface.php index ed9892534f..90eb200b6e 100644 --- a/app/Helpers/Report/ReportQueryInterface.php +++ b/app/Helpers/Report/ReportQueryInterface.php @@ -31,18 +31,18 @@ interface ReportQueryInterface */ public function expenseInPeriod(Carbon $start, Carbon $end, Collection $accounts); - /** - * This method works the same way as ReportQueryInterface::incomeInPeriod does, but instead of returning results - * will simply list the transaction journals only. This should allow any follow up counting to be accurate with - * regards to tags. It will only get the incomes to the specified accounts. - * - * @param Carbon $start - * @param Carbon $end - * @param Collection $accounts - * - * @return Collection - */ - public function incomeInPeriod(Carbon $start, Carbon $end, Collection $accounts); +// /** +// * This method works the same way as ReportQueryInterface::incomeInPeriod does, but instead of returning results +// * will simply list the transaction journals only. This should allow any follow up counting to be accurate with +// * regards to tags. It will only get the incomes to the specified accounts. +// * +// * @param Carbon $start +// * @param Carbon $end +// * @param Collection $accounts +// * +// * @return Collection +// */ +// public function incomeInPeriod(Carbon $start, Carbon $end, Collection $accounts); /** * Covers tags as well. diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index 28ed6f1322..d43661064d 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -125,9 +125,9 @@ class ReportController extends Controller $expenseTopLength = 8; // get report stuff! - $accountReport = $this->helper->getAccountReport($start, $end, $accounts); - $incomes = $this->helper->getIncomeReport($start, $end, $accounts); - $expenses = $this->helper->getExpenseReport($start, $end, $accounts); + $accountReport = $this->helper->getAccountReport($start, $end, $accounts); // done + $incomes = $this->helper->getIncomeReport($start, $end, $accounts); // done + $expenses = $this->helper->getExpenseReport($start, $end, $accounts); // done $budgets = $this->helper->getBudgetReport($start, $end, $accounts); $categories = $this->helper->getCategoryReport($start, $end, $accounts); $balance = $this->helper->getBalanceReport($start, $end, $accounts); From 70c922cdc5c9d9dd282888a14a1c9f4e1c1d2d26 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 11:32:08 +0100 Subject: [PATCH 31/62] Code cleanup. --- app/Helpers/Report/ReportHelper.php | 52 +---- app/Helpers/Report/ReportQuery.php | 240 ++++++-------------- app/Helpers/Report/ReportQueryInterface.php | 35 ++- app/Http/Controllers/JsonController.php | 12 +- 4 files changed, 92 insertions(+), 247 deletions(-) diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 00f58a310a..3714350691 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -2,7 +2,6 @@ namespace FireflyIII\Helpers\Report; -use Auth; use Carbon\Carbon; use DB; use FireflyIII\Helpers\Collection\Account as AccountCollection; @@ -21,8 +20,6 @@ use FireflyIII\Models\Account; use FireflyIII\Models\Bill; use FireflyIII\Models\Budget as BudgetModel; use FireflyIII\Models\LimitRepetition; -use FireflyIII\Models\TransactionType; -use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; /** @@ -215,29 +212,7 @@ class ReportHelper implements ReportHelperInterface public function getIncomeReport($start, $end, Collection $accounts) { $object = new Income; - - /* - * TODO move to ReportQuery class. - */ - $ids = $accounts->pluck('id')->toArray(); - $set = Auth::user()->transactionjournals() - ->leftJoin( - 'transactions as t_from', function (JoinClause $join) { - $join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0); - } - ) - ->leftJoin( - 'transactions as t_to', function (JoinClause $join) { - $join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0); - } - ) - ->leftJoin('accounts', 't_from.account_id', '=', 'accounts.id') - ->transactionTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) - ->before($end) - ->after($start) - ->whereIn('t_to.account_id', $ids) - ->whereNotIn('t_from.account_id', $ids) - ->get(['transaction_journals.*', 't_to.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']); + $set = $this->query->income($accounts, $start, $end); foreach ($set as $entry) { $object->addToTotal($entry->journalAmount); @@ -259,30 +234,7 @@ class ReportHelper implements ReportHelperInterface public function getExpenseReport($start, $end, Collection $accounts) { $object = new Expense; - - - /* - * TODO move to ReportQuery class. - */ - $ids = $accounts->pluck('id')->toArray(); - $set = Auth::user()->transactionjournals() - ->leftJoin( - 'transactions as t_from', function (JoinClause $join) { - $join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0); - } - ) - ->leftJoin( - 'transactions as t_to', function (JoinClause $join) { - $join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0); - } - ) - ->leftJoin('accounts', 't_to.account_id', '=', 'accounts.id') - ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) - ->before($end) - ->after($start) - ->whereIn('t_from.account_id', $ids) - ->whereNotIn('t_to.account_id', $ids) - ->get(['transaction_journals.*', 't_from.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']); + $set = $this->query->expense($accounts, $start, $end); foreach ($set as $entry) { $object->addToTotal($entry->journalAmount); // can be positive, if it's a transfer diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php index de29c6ed29..1807541a32 100644 --- a/app/Helpers/Report/ReportQuery.php +++ b/app/Helpers/Report/ReportQuery.php @@ -4,7 +4,6 @@ namespace FireflyIII\Helpers\Report; use Auth; use Carbon\Carbon; -use Crypt; use DB; use FireflyIII\Models\Account; use FireflyIII\Models\Budget; @@ -65,176 +64,6 @@ class ReportQuery implements ReportQueryInterface ->whereNull('budget_transaction_journal.budget_id')->get(['transaction_journals.*'])->sum('amount'); } - /** - * @param Carbon $start - * @param Carbon $end - * - * @return Builder - */ - protected function queryJournalsWithTransactions(Carbon $start, Carbon $end) - { - $query = TransactionJournal:: - leftJoin( - 'transactions as t_from', function (JoinClause $join) { - $join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0); - } - ) - ->leftJoin('accounts as ac_from', 't_from.account_id', '=', 'ac_from.id') - ->leftJoin( - 'account_meta as acm_from', function (JoinClause $join) { - $join->on('ac_from.id', '=', 'acm_from.account_id')->where('acm_from.name', '=', 'accountRole'); - } - ) - ->leftJoin( - 'transactions as t_to', function (JoinClause $join) { - $join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0); - } - ) - ->leftJoin('accounts as ac_to', 't_to.account_id', '=', 'ac_to.id') - ->leftJoin( - 'account_meta as acm_to', function (JoinClause $join) { - $join->on('ac_to.id', '=', 'acm_to.account_id')->where('acm_to.name', '=', 'accountRole'); - } - ) - ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id'); - $query->before($end)->after($start)->where('transaction_journals.user_id', Auth::user()->id); - - return $query; - } - - -// /** -// * This method works the same way as ReportQueryInterface::incomeInPeriod does, but instead of returning results -// * will simply list the transaction journals only. This should allow any follow up counting to be accurate with -// * regards to tags. It will only get the incomes to the specified accounts. -// * -// * @param Carbon $start -// * @param Carbon $end -// * @param Collection $accounts -// * -// * @return Collection -// */ -// public function incomeInPeriod(Carbon $start, Carbon $end, Collection $accounts) -// { -// $query = $this->queryJournalsWithTransactions($start, $end); -// -// $ids = []; -// /** @var Account $account */ -// foreach ($accounts as $account) { -// $ids[] = $account->id; -// } -// -// // OR is a deposit -// // OR any transfer TO the accounts in $accounts, not FROM any of the accounts in $accounts. -// $query->where( -// function (Builder $query) use ($ids) { -// $query->where( -// function (Builder $q) { -// $q->where('transaction_types.type', TransactionType::DEPOSIT); -// } -// ); -// $query->orWhere( -// function (Builder $q) use ($ids) { -// $q->where('transaction_types.type', TransactionType::TRANSFER); -// $q->whereNotIn('ac_from.id', $ids); -// $q->whereIn('ac_to.id', $ids); -// } -// ); -// } -// ); -// -// // only include selected accounts. -// $query->whereIn('ac_to.id', $ids); -// $query->orderBy('transaction_journals.date'); -// -// // get everything -// $data = $query->get( -// ['transaction_journals.*', -// 'transaction_types.type', 'ac_from.name as name', -// 't_from.amount as from_amount', -// 't_to.amount as to_amount', -// 'ac_from.id as account_id', 'ac_from.encrypted as account_encrypted'] -// ); -// -// $data->each( -// function (TransactionJournal $journal) { -// if (intval($journal->account_encrypted) == 1) { -// $journal->name = Crypt::decrypt($journal->name); -// } -// } -// ); -// -// return $data; -// } - - /** - * See ReportQueryInterface::incomeInPeriod - * - * This method returns all "expense" journals in a certain period, which are both transfers to a shared account - * and "ordinary" withdrawals. The query used is almost equal to ReportQueryInterface::journalsByRevenueAccount but it does - * not group and returns different fields. - * - * @param Carbon $start - * @param Carbon $end - * @param Collection $accounts - * - * @return Collection - * - */ - public function expenseInPeriod(Carbon $start, Carbon $end, Collection $accounts) - { - $ids = []; - - /** @var Account $account */ - foreach ($accounts as $account) { - $ids[] = $account->id; - } - - $query = $this->queryJournalsWithTransactions($start, $end); - - // withdrawals from any account are an expense. - // transfers away, from an account in the list, to an account not in the list, are an expense. - - $query->where( - function (Builder $query) use ($ids) { - $query->where( - function (Builder $q) { - $q->where('transaction_types.type', TransactionType::WITHDRAWAL); - } - ); - $query->orWhere( - function (Builder $q) use ($ids) { - $q->where('transaction_types.type', TransactionType::TRANSFER); - $q->whereIn('ac_from.id', $ids); - $q->whereNotIn('ac_to.id', $ids); - } - ); - } - ); - - // expense goes from the selected accounts: - $query->whereIn('ac_from.id', $ids); - - $query->orderBy('transaction_journals.date'); - $data = $query->get( // get everything - ['transaction_journals.*', 'transaction_types.type', - 't_from.amount as from_amount', - 't_to.amount as to_amount', - 'ac_to.name as name', 'ac_to.id as account_id', 'ac_to.encrypted as account_encrypted'] - ); - - $data->each( - function (TransactionJournal $journal) { - if (intval($journal->account_encrypted) == 1) { - $journal->name = Crypt::decrypt($journal->name); - } - } - ); - - return $data; - } - - /** * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) * grouped by month like so: "2015-01" => '123.45' @@ -324,4 +153,73 @@ class ReportQuery implements ReportQueryInterface return $array; } + /** + * This method returns all the "in" transaction journals for the given account and given period. The amount + * is stored in "journalAmount". + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function income(Collection $accounts, Carbon $start, Carbon $end) + { + $ids = $accounts->pluck('id')->toArray(); + $set = Auth::user()->transactionjournals() + ->leftJoin( + 'transactions as t_from', function (JoinClause $join) { + $join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions as t_to', function (JoinClause $join) { + $join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0); + } + ) + ->leftJoin('accounts', 't_from.account_id', '=', 'accounts.id') + ->transactionTypes([TransactionType::DEPOSIT, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) + ->before($end) + ->after($start) + ->whereIn('t_to.account_id', $ids) + ->whereNotIn('t_from.account_id', $ids) + ->get(['transaction_journals.*', 't_to.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']); + + return $set; + } + + /** + * This method returns all the "out" transaction journals for the given account and given period. The amount + * is stored in "journalAmount". + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function expense(Collection $accounts, Carbon $start, Carbon $end) + { + $ids = $accounts->pluck('id')->toArray(); + $set = Auth::user()->transactionjournals() + ->leftJoin( + 'transactions as t_from', function (JoinClause $join) { + $join->on('t_from.transaction_journal_id', '=', 'transaction_journals.id')->where('t_from.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions as t_to', function (JoinClause $join) { + $join->on('t_to.transaction_journal_id', '=', 'transaction_journals.id')->where('t_to.amount', '>', 0); + } + ) + ->leftJoin('accounts', 't_to.account_id', '=', 'accounts.id') + ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) + ->before($end) + ->after($start) + ->whereIn('t_from.account_id', $ids) + ->whereNotIn('t_to.account_id', $ids) + ->get(['transaction_journals.*', 't_from.amount as journalAmount', 'accounts.id as account_id', 'accounts.name as account_name']); + + return $set; + } } diff --git a/app/Helpers/Report/ReportQueryInterface.php b/app/Helpers/Report/ReportQueryInterface.php index 90eb200b6e..bd244a448b 100644 --- a/app/Helpers/Report/ReportQueryInterface.php +++ b/app/Helpers/Report/ReportQueryInterface.php @@ -16,33 +16,28 @@ interface ReportQueryInterface { /** - * See ReportQueryInterface::incomeInPeriod - * - * This method returns all "expense" journals in a certain period, which are both transfers to a shared account - * and "ordinary" withdrawals. The query used is almost equal to ReportQueryInterface::journalsByRevenueAccount but it does - * not group and returns different fields. + * This method returns all the "in" transaction journals for the given account and given period. The amount + * is stored in "journalAmount". * + * @param Collection $accounts * @param Carbon $start * @param Carbon $end - * @param Collection $accounts * * @return Collection - * */ - public function expenseInPeriod(Carbon $start, Carbon $end, Collection $accounts); + public function income(Collection $accounts, Carbon $start, Carbon $end); -// /** -// * This method works the same way as ReportQueryInterface::incomeInPeriod does, but instead of returning results -// * will simply list the transaction journals only. This should allow any follow up counting to be accurate with -// * regards to tags. It will only get the incomes to the specified accounts. -// * -// * @param Carbon $start -// * @param Carbon $end -// * @param Collection $accounts -// * -// * @return Collection -// */ -// public function incomeInPeriod(Carbon $start, Carbon $end, Collection $accounts); + /** + * This method returns all the "out" transaction journals for the given account and given period. The amount + * is stored in "journalAmount". + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function expense(Collection $accounts, Carbon $start, Carbon $end); /** * Covers tags as well. diff --git a/app/Http/Controllers/JsonController.php b/app/Http/Controllers/JsonController.php index 7005084b4b..bc1b25539b 100644 --- a/app/Http/Controllers/JsonController.php +++ b/app/Http/Controllers/JsonController.php @@ -111,9 +111,9 @@ class JsonController extends Controller } /** - * @param ReportQueryInterface $reportQuery + * @param ReportQueryInterface $reportQuery * - * @param ARI $accountRepository + * @param ARI $accountRepository * * @return \Symfony\Component\HttpFoundation\Response */ @@ -131,7 +131,7 @@ class JsonController extends Controller return Response::json($cache->get()); // @codeCoverageIgnore } $accounts = $accountRepository->getAccounts(['Default account', 'Asset account', 'Cash account']); - $amount = $reportQuery->incomeInPeriod($start, $end, $accounts)->sum('to_amount'); + $amount = $reportQuery->income($accounts, $start, $end)->sum('journalAmount'); $data = ['box' => 'in', 'amount' => Amount::format($amount, false), 'amount_raw' => $amount]; $cache->store($data); @@ -140,9 +140,9 @@ class JsonController extends Controller } /** - * @param ReportQueryInterface $reportQuery + * @param ReportQueryInterface $reportQuery * - * @param ARI $accountRepository + * @param ARI $accountRepository * * @return \Symfony\Component\HttpFoundation\Response */ @@ -162,7 +162,7 @@ class JsonController extends Controller return Response::json($cache->get()); // @codeCoverageIgnore } - $amount = $reportQuery->expenseInPeriod($start, $end, $accounts)->sum('to_amount'); + $amount = $reportQuery->expense($accounts, $start, $end)->sum('journalAmount'); $data = ['box' => 'out', 'amount' => Amount::format($amount, false), 'amount_raw' => $amount]; $cache->store($data); From b415b6b043d9dd4f892a5bbbf31b79e1dd734a1c Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 12:41:00 +0100 Subject: [PATCH 32/62] Some code cleanup. --- app/Helpers/Report/ReportQuery.php | 2 -- app/Helpers/Report/ReportQueryInterface.php | 8 +++--- app/Http/Controllers/AccountController.php | 2 +- app/Http/Controllers/BudgetController.php | 4 +-- .../Controllers/Chart/BudgetController.php | 4 +-- .../Controllers/Chart/CategoryController.php | 1 - app/Http/Controllers/NewUserController.php | 6 ++--- app/Http/Controllers/PiggyBankController.php | 10 ++++---- .../Controllers/TransactionController.php | 8 +++--- .../Account/AccountRepository.php | 2 +- app/Repositories/Budget/BudgetRepository.php | 3 ++- .../Category/SingleCategoryRepository.php | 25 +++++++++---------- .../Shared/ComponentRepository.php | 1 - app/Sql/Query.php | 2 +- 14 files changed, 37 insertions(+), 41 deletions(-) diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php index 1807541a32..bec2475577 100644 --- a/app/Helpers/Report/ReportQuery.php +++ b/app/Helpers/Report/ReportQuery.php @@ -7,9 +7,7 @@ use Carbon\Carbon; use DB; use FireflyIII\Models\Account; use FireflyIII\Models\Budget; -use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; -use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; diff --git a/app/Helpers/Report/ReportQueryInterface.php b/app/Helpers/Report/ReportQueryInterface.php index bd244a448b..45d910d46c 100644 --- a/app/Helpers/Report/ReportQueryInterface.php +++ b/app/Helpers/Report/ReportQueryInterface.php @@ -65,8 +65,8 @@ interface ReportQueryInterface * grouped by month like so: "2015-01" => '123.45' * * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end + * @param Carbon $start + * @param Carbon $end * * @return array */ @@ -77,8 +77,8 @@ interface ReportQueryInterface * grouped by month like so: "2015-01" => '123.45' * * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end + * @param Carbon $start + * @param Carbon $end * * @return array */ diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php index d80f2a021b..44f7e7e396 100644 --- a/app/Http/Controllers/AccountController.php +++ b/app/Http/Controllers/AccountController.php @@ -195,7 +195,7 @@ class AccountController extends Controller $subTitleIcon = Config::get('firefly.subTitlesByIdentifier.' . $account->accountType->type); $what = Config::get('firefly.shortNamesByFullName.' . $account->accountType->type); $journals = $repository->getJournals($account, $page); - $subTitle = trans('firefly.details_for_' . $what, ['name' => $account->name]); + $subTitle = trans('firefly.details_for_' . $what, ['name' => $account->name]); $journals->setPath('accounts/show/' . $account->id); diff --git a/app/Http/Controllers/BudgetController.php b/app/Http/Controllers/BudgetController.php index fb07d200b3..e680e5e2c5 100644 --- a/app/Http/Controllers/BudgetController.php +++ b/app/Http/Controllers/BudgetController.php @@ -234,8 +234,8 @@ class BudgetController extends Controller if (is_null($repetition->id)) { $start = $repository->firstActivity($budget); - $end = new Carbon; - $set = $budget->limitrepetitions()->orderBy('startdate','DESC')->get(); + $end = new Carbon; + $set = $budget->limitrepetitions()->orderBy('startdate', 'DESC')->get(); //$set = $repository->getBudgetLimits($budget); //$subTitle = e($budget->name); } else { diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index 64ccd5c591..39d3c4dffa 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -227,9 +227,9 @@ class BudgetController extends Controller /** * Shows a budget list with spent/left/overspent. * - * @param BudgetRepositoryInterface $repository + * @param BudgetRepositoryInterface $repository * - * @param ARI $accountRepository + * @param ARI $accountRepository * * @return \Symfony\Component\HttpFoundation\Response */ diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 0b75b0b328..d2adca7078 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -461,5 +461,4 @@ class CategoryController extends Controller } - } diff --git a/app/Http/Controllers/NewUserController.php b/app/Http/Controllers/NewUserController.php index 384223dc1b..440c5c74d0 100644 --- a/app/Http/Controllers/NewUserController.php +++ b/app/Http/Controllers/NewUserController.php @@ -6,7 +6,7 @@ use Config; use FireflyIII\Http\Requests\NewUserFormRequest; use FireflyIII\Models\AccountMeta; use FireflyIII\Repositories\Account\AccountRepositoryInterface as ARI; -use Preferences ; +use Preferences; use Session; use View; @@ -42,8 +42,8 @@ class NewUserController extends Controller } /** - * @param NewUserFormRequest $request - * @param ARI $repository + * @param NewUserFormRequest $request + * @param ARI $repository * * @return \Illuminate\Http\RedirectResponse */ diff --git a/app/Http/Controllers/PiggyBankController.php b/app/Http/Controllers/PiggyBankController.php index 40c43481a8..8b431fdd72 100644 --- a/app/Http/Controllers/PiggyBankController.php +++ b/app/Http/Controllers/PiggyBankController.php @@ -40,8 +40,8 @@ class PiggyBankController extends Controller /** * Add money to piggy bank * - * @param ARI $repository - * @param PiggyBank $piggyBank + * @param ARI $repository + * @param PiggyBank $piggyBank * * @return $this */ @@ -116,8 +116,8 @@ class PiggyBankController extends Controller } /** - * @param ARI $repository - * @param PiggyBank $piggyBank + * @param ARI $repository + * @param PiggyBank $piggyBank * * @return View */ @@ -219,7 +219,7 @@ class PiggyBankController extends Controller /** * @param PiggyBankRepositoryInterface $repository - * @param ARI $accounts + * @param ARI $accounts * @param PiggyBank $piggyBank * * @return \Illuminate\Http\RedirectResponse diff --git a/app/Http/Controllers/TransactionController.php b/app/Http/Controllers/TransactionController.php index 1ed7e5a78a..60712a986e 100644 --- a/app/Http/Controllers/TransactionController.php +++ b/app/Http/Controllers/TransactionController.php @@ -43,8 +43,8 @@ class TransactionController extends Controller } /** - * @param ARI $repository - * @param string $what + * @param ARI $repository + * @param string $what * * @return \Illuminate\View\View */ @@ -133,8 +133,8 @@ class TransactionController extends Controller /** * Shows the view to edit a transaction. * - * @param ARI $repository - * @param TransactionJournal $journal + * @param ARI $repository + * @param TransactionJournal $journal * * @return $this */ diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 90eb46cd13..10d2a1bab2 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -270,7 +270,7 @@ class AccountRepository implements AccountRepositoryInterface $end = clone Session::get('end', new Carbon); $collection = new Collection(DB::table('piggy_banks')->distinct()->get(['piggy_banks.account_id'])); $ids = $collection->pluck('account_id')->toArray(); - $accounts = new Collection; + $accounts = new Collection; $cache = new CacheProperties; $cache->addProperty($ids); diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index cfcbf75359..830bbb9167 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -206,7 +206,8 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn * * @return Collection */ - public function getBudgetReps(Budget $budget) { + public function getBudgetReps(Budget $budget) + { $set = $budget->limitrepetitions()->count(); var_dump($set); } diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php index 41b237a07f..1f56c180d2 100644 --- a/app/Repositories/Category/SingleCategoryRepository.php +++ b/app/Repositories/Category/SingleCategoryRepository.php @@ -2,7 +2,6 @@ namespace FireflyIII\Repositories\Category; -use Auth; use Carbon\Carbon; use DB; use FireflyIII\Models\Category; @@ -108,12 +107,12 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate { /** @var Collection $query */ $query = $category->transactionJournals() - ->transactionTypes([TransactionType::DEPOSIT]) - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->where('transactions.amount', '>', 0) - ->before($end) - ->after($start) - ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); + ->transactionTypes([TransactionType::DEPOSIT]) + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->where('transactions.amount', '>', 0) + ->before($end) + ->after($start) + ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); $return = []; foreach ($query->toArray() as $entry) { @@ -244,12 +243,12 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate { /** @var Collection $query */ $query = $category->transactionJournals() - ->transactionTypes([TransactionType::WITHDRAWAL]) - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->where('transactions.amount', '<', 0) - ->before($end) - ->after($start) - ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); + ->transactionTypes([TransactionType::WITHDRAWAL]) + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->where('transactions.amount', '<', 0) + ->before($end) + ->after($start) + ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); $return = []; foreach ($query->toArray() as $entry) { diff --git a/app/Repositories/Shared/ComponentRepository.php b/app/Repositories/Shared/ComponentRepository.php index 6731c904cb..7c976e8784 100644 --- a/app/Repositories/Shared/ComponentRepository.php +++ b/app/Repositories/Shared/ComponentRepository.php @@ -4,7 +4,6 @@ namespace FireflyIII\Repositories\Shared; use Carbon\Carbon; use DB; -use FireflyIII\Models\Account; use FireflyIII\Models\TransactionType; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; diff --git a/app/Sql/Query.php b/app/Sql/Query.php index 9f31ad83fe..b0989a82d7 100644 --- a/app/Sql/Query.php +++ b/app/Sql/Query.php @@ -11,7 +11,7 @@ namespace FireflyIII\Sql; */ class Query { - const SPENT = 1; + const SPENT = 1; const EARNED = 2; } \ No newline at end of file From 54ede8aa18a51636ff3a641c2613228009f72bf4 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 13:54:23 +0100 Subject: [PATCH 33/62] Code cleanup. --- app/Helpers/Report/ReportHelper.php | 48 ++++++-- app/Repositories/Budget/BudgetRepository.php | 105 ++++++++++++++++-- .../Budget/BudgetRepositoryInterface.php | 54 +++++++-- 3 files changed, 184 insertions(+), 23 deletions(-) diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 3714350691..63981f4b35 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -255,18 +255,24 @@ class ReportHelper implements ReportHelperInterface { $object = new BudgetCollection; /** @var \FireflyIII\Repositories\Budget\BudgetRepositoryInterface $repository */ - $repository = app('FireflyIII\Repositories\Budget\BudgetRepositoryInterface'); - $set = $repository->getBudgets(); - + $repository = app('FireflyIII\Repositories\Budget\BudgetRepositoryInterface'); + $set = $repository->getBudgets(); + $allRepetitions = $repository->getAllBudgetLimitRepetitions($start, $end); + $allTotalSpent = $repository->spentAllPerDayForAccounts($accounts, $start, $end); bcscale(2); foreach ($set as $budget) { - $repetitions = $repository->getBudgetLimitRepetitions($budget, $start, $end); + $repetitions = $allRepetitions->filter( + function (LimitRepetition $rep) use ($budget) { + return $rep->budget_id == $budget->id; + } + ); + $totalSpent = isset($allTotalSpent[$budget->id]) ? $allTotalSpent[$budget->id] : []; // no repetition(s) for this budget: if ($repetitions->count() == 0) { - $spent = $repository->balanceInPeriod($budget, $start, $end, $accounts); + $spent = array_sum($totalSpent); $budgetLine = new BudgetLine; $budgetLine->setBudget($budget); $budgetLine->setOverspent($spent); @@ -281,7 +287,7 @@ class ReportHelper implements ReportHelperInterface $budgetLine = new BudgetLine; $budgetLine->setBudget($budget); $budgetLine->setRepetition($repetition); - $expenses = $repository->balanceInPeriod($budget, $start, $end, $accounts); + $expenses = $this->getSumOfRange($start, $end, $totalSpent); // 200 en -100 is 100, vergeleken met 0 === 1 // 200 en -200 is 0, vergeleken met 0 === 0 @@ -454,4 +460,32 @@ class ReportHelper implements ReportHelperInterface return $collection; } -} + + /** + * Take the array as returned by SingleCategoryRepositoryInterface::spentPerDay and SingleCategoryRepositoryInterface::earnedByDay + * and sum up everything in the array in the given range. + * + * @param Carbon $start + * @param Carbon $end + * @param array $array + * + * @return string + */ + protected function getSumOfRange(Carbon $start, Carbon $end, array $array) + { + bcscale(2); + $sum = '0'; + $currentStart = clone $start; // to not mess with the original one + $currentEnd = clone $end; // to not mess with the original one + + while ($currentStart <= $currentEnd) { + $date = $currentStart->format('Y-m-d'); + if (isset($array[$date])) { + $sum = bcadd($sum, $array[$date]); + } + $currentStart->addDay(); + } + + return $sum; + } +} \ No newline at end of file diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 830bbb9167..3d4f9fc2bf 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -200,18 +200,24 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn } /** - * Get a collection of all the limit repetitions belonging to this $budget. - * - * @param Budget $budget + * @param Carbon $start + * @param Carbon $end * * @return Collection */ - public function getBudgetReps(Budget $budget) + public function getAllBudgetLimitRepetitions(Carbon $start, Carbon $end) { - $set = $budget->limitrepetitions()->count(); - var_dump($set); + /** @var Collection $repetitions */ + return LimitRepetition:: + leftJoin('budget_limits', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id') + ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') + ->where('limit_repetitions.startdate', '<=', $end->format('Y-m-d 00:00:00')) + ->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d 00:00:00')) + ->where('budgets.user_id', Auth::user()->id) + ->get(['limit_repetitions.*', 'budget_limits.budget_id']); } + /** * @param Budget $budget * @param Carbon $start @@ -264,7 +270,43 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn ->where('transactions.amount', '<', 0) ->before($end) ->after($start) - ->groupBy('date')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); + ->groupBy('dateFormatted')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); + + $return = []; + foreach ($query->toArray() as $entry) { + $return[$entry['dateFormatted']] = $entry['sum']; + } + + return $return; + } + + /** + * Returns an array with the following key:value pairs: + * + * yyyy-mm-dd: + * + * Where yyyy-mm-dd is the date and is the money spent using DEPOSITS in the $budget + * from all the users accounts. + * + * @param Budget $budget + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function spentPerDayForAccounts(Budget $budget, Collection $accounts, Carbon $start, Carbon $end) + { + $ids = $accounts->pluck('id')->toArray(); + /** @var Collection $query */ + $query = $budget->transactionJournals() + ->transactionTypes([TransactionType::WITHDRAWAL]) + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->whereIn('transactions.account_id', $ids) + ->where('transactions.amount', '<', 0) + ->before($end) + ->after($start) + ->groupBy('dateFormatted')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); $return = []; foreach ($query->toArray() as $entry) { @@ -726,4 +768,53 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn return $return; } + + /** + * Returns an array with the following key:value pairs: + * + * yyyy-mm-dd: + * + * That array contains: + * + * budgetid: + * + * Where yyyy-mm-dd is the date and is the money spent using WITHDRAWALS in the $budget + * from the given users accounts.. + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function spentAllPerDayForAccounts(Collection $accounts, Carbon $start, Carbon $end) + { + $ids = $accounts->pluck('id')->toArray(); + /** @var Collection $query */ + $query = Auth::user()->transactionJournals() + ->transactionTypes([TransactionType::WITHDRAWAL]) + ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('budget_transaction_journal', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id') + ->whereIn('transactions.account_id', $ids) + ->where('transactions.amount', '<', 0) + ->before($end) + ->after($start) + ->groupBy('budget_id') + ->groupBy('dateFormatted') + ->get( + ['transaction_journals.date as dateFormatted', 'budget_transaction_journal.budget_id', + DB::Raw('SUM(`transactions`.`amount`) AS `sum`')] + ); + + $return = []; + foreach ($query->toArray() as $entry) { + $budgetId = $entry['budget_id']; + if (!isset($return[$budgetId])) { + $return[$budgetId] = []; + } + $return[$budgetId][$entry['dateFormatted']] = $entry['sum']; + } + + return $return; + } } diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index c228df2ce3..a06b661749 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -39,15 +39,6 @@ interface BudgetRepositoryInterface */ public function firstActivity(Budget $budget); - /** - * Get a collection of all the limit repetitions belonging to this $budget. - * - * @param Budget $budget - * - * @return Collection - */ - public function getBudgetReps(Budget $budget); - /** * Returns the expenses for this budget grouped per month, with the date * in "date" (a string, not a Carbon) and the amount in "dailyAmount". @@ -76,6 +67,43 @@ interface BudgetRepositoryInterface */ public function spentPerDay(Budget $budget, Carbon $start, Carbon $end); + /** + * Returns an array with the following key:value pairs: + * + * yyyy-mm-dd: + * + * Where yyyy-mm-dd is the date and is the money spent using WITHDRAWALS in the $budget + * from the given users accounts.. + * + * @param Budget $budget + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function spentPerDayForAccounts(Budget $budget, Collection $accounts, Carbon $start, Carbon $end); + + /** + * Returns an array with the following key:value pairs: + * + * yyyy-mm-dd: + * + * That array contains: + * + * budgetid: + * + * Where yyyy-mm-dd is the date and is the money spent using WITHDRAWALS in the $budget + * from the given users accounts.. + * + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return array + */ + public function spentAllPerDayForAccounts(Collection $accounts, Carbon $start, Carbon $end); + /** * @param Budget $budget * @@ -143,6 +171,14 @@ interface BudgetRepositoryInterface */ public function getBudgetLimitRepetitions(Budget $budget, Carbon $start, Carbon $end); + /** + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getAllBudgetLimitRepetitions(Carbon $start, Carbon $end); + /** * @param Budget $budget * From 59731878f647ff9ab1ec17ff70ab31c44153ec39 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 19:46:12 +0100 Subject: [PATCH 34/62] Month report optimised. --- app/Helpers/Collection/BalanceLine.php | 21 +------ app/Helpers/Report/ReportHelper.php | 60 +++++++++++++------ app/Http/Controllers/ReportController.php | 23 ++++--- app/Repositories/Budget/BudgetRepository.php | 52 ++++++++++++++++ .../Budget/BudgetRepositoryInterface.php | 19 ++++++ app/Repositories/Tag/TagRepository.php | 45 ++++++++++++++ .../Tag/TagRepositoryInterface.php | 9 ++- 7 files changed, 177 insertions(+), 52 deletions(-) diff --git a/app/Helpers/Collection/BalanceLine.php b/app/Helpers/Collection/BalanceLine.php index a5e48efae1..ff0d17fc3b 100644 --- a/app/Helpers/Collection/BalanceLine.php +++ b/app/Helpers/Collection/BalanceLine.php @@ -26,9 +26,6 @@ class BalanceLine /** @var BudgetModel */ protected $budget; - /** @var LimitRepetition */ - protected $repetition; - protected $role = self::ROLE_DEFAULTROLE; /** @@ -110,7 +107,7 @@ class BalanceLine */ public function leftOfRepetition() { - $start = $this->getRepetition() ? $this->getRepetition()->amount : 0; + $start = isset($this->budget->amount) ? $this->budget->amount : 0; /** @var BalanceEntry $balanceEntry */ foreach ($this->getBalanceEntries() as $balanceEntry) { $start += $balanceEntry->getSpent(); @@ -119,22 +116,6 @@ class BalanceLine return $start; } - /** - * @return LimitRepetition - */ - public function getRepetition() - { - return $this->repetition; - } - - /** - * @param LimitRepetition $repetition - */ - public function setRepetition($repetition) - { - $this->repetition = $repetition; - } - /** * @return Collection */ diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 63981f4b35..46dbebb137 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -20,6 +20,8 @@ use FireflyIII\Models\Account; use FireflyIII\Models\Bill; use FireflyIII\Models\Budget as BudgetModel; use FireflyIII\Models\LimitRepetition; +use FireflyIII\Models\Tag; +use FireflyIII\Models\TransactionJournal; use Illuminate\Support\Collection; /** @@ -62,13 +64,8 @@ class ReportHelper implements ReportHelperInterface /** @var \FireflyIII\Repositories\Category\CategoryRepositoryInterface $repository */ $repository = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface'); - /** @var \FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface $singleRepository */ - $singleRepository = app('FireflyIII\Repositories\Category\SingleCategoryRepositoryInterface'); - - $set = $repository->listCategories(); + $set = $repository->spentForAccountsPerMonth($accounts, $start, $end); foreach ($set as $category) { - $spent = $singleRepository->balanceInPeriod($category, $start, $end, $accounts); - $category->spent = $spent; $object->addCategory($category); } @@ -332,13 +329,18 @@ class ReportHelper implements ReportHelperInterface */ public function getBalanceReport(Carbon $start, Carbon $end, Collection $accounts) { - $repository = app('FireflyIII\Repositories\Budget\BudgetRepositoryInterface'); + /** @var \FireflyIII\Repositories\Budget\BudgetRepositoryInterface $repository */ + $repository = app('FireflyIII\Repositories\Budget\BudgetRepositoryInterface'); + + /** @var \FireflyIII\Repositories\Tag\TagRepositoryInterface $tagRepository */ $tagRepository = app('FireflyIII\Repositories\Tag\TagRepositoryInterface'); - $balance = new Balance; + + $balance = new Balance; // build a balance header: - $header = new BalanceHeader; - $budgets = $repository->getBudgets(); + $header = new BalanceHeader; + $budgets = $repository->getBudgetsAndLimitsInRange($start, $end); + $spentData = $repository->spentPerBudgetPerAccount($budgets, $accounts, $start, $end); foreach ($accounts as $account) { $header->addAccount($account); } @@ -348,18 +350,22 @@ class ReportHelper implements ReportHelperInterface $line = new BalanceLine; $line->setBudget($budget); - // get budget amount for current period: - $rep = $repository->getCurrentRepetition($budget, $start, $end); - // could be null? - $line->setRepetition($rep); - // loop accounts: foreach ($accounts as $account) { $balanceEntry = new BalanceEntry; $balanceEntry->setAccount($account); // get spent: - $spent = $this->query->spentInBudget($account, $budget, $start, $end); // I think shared is irrelevant. + $entry = $spentData->filter( + function (TransactionJournal $model) use ($budget, $account) { + return $model->account_id == $account->id && $model->budget_id == $budget->id; + } + ); + $spent = 0; + if (!is_null($entry->first())) { + $spent = $entry->first()->spent; + } + //$spent = $this->query->spentInBudget($account, $budget, $start, $end); // I think shared is irrelevant. $balanceEntry->setSpent($spent); $line->addBalanceEntry($balanceEntry); @@ -374,13 +380,31 @@ class ReportHelper implements ReportHelperInterface $empty = new BalanceLine; $tags = new BalanceLine; $diffLine = new BalanceLine; + $tagsLeft = $tagRepository->allCoveredByBalancingActs($accounts, $start, $end); $tags->setRole(BalanceLine::ROLE_TAGROLE); $diffLine->setRole(BalanceLine::ROLE_DIFFROLE); foreach ($accounts as $account) { - $spent = $this->query->spentNoBudget($account, $start, $end); - $left = $tagRepository->coveredByBalancingActs($account, $start, $end); + //$spent = $this->query->spentNoBudget($account, $start, $end); + $entry = $spentData->filter( + function (TransactionJournal $model) use ($budget, $account) { + return $model->account_id == $account->id && is_null($model->budget_id); + } + ); + $spent = 0; + if (!is_null($entry->first())) { + $spent = $entry->first()->spent; + } + $leftEntry = $tagsLeft->filter( + function (Tag $tag) use ($account) { + return $tag->account_id == $account->id; + } + ); + $left = 0; + if (!is_null($leftEntry->first())) { + $left = $leftEntry->first()->sum; + } bcscale(2); $diff = bcadd($spent, $left); diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index d43661064d..33b7f87022 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -125,21 +125,18 @@ class ReportController extends Controller $expenseTopLength = 8; // get report stuff! - $accountReport = $this->helper->getAccountReport($start, $end, $accounts); // done - $incomes = $this->helper->getIncomeReport($start, $end, $accounts); // done - $expenses = $this->helper->getExpenseReport($start, $end, $accounts); // done - $budgets = $this->helper->getBudgetReport($start, $end, $accounts); - $categories = $this->helper->getCategoryReport($start, $end, $accounts); - $balance = $this->helper->getBalanceReport($start, $end, $accounts); - $bills = $this->helper->getBillReport($start, $end, $accounts); + $accountReport = $this->helper->getAccountReport($start, $end, $accounts); // done (+2) + $incomes = $this->helper->getIncomeReport($start, $end, $accounts); // done (+3) + $expenses = $this->helper->getExpenseReport($start, $end, $accounts); // done (+1) + $budgets = $this->helper->getBudgetReport($start, $end, $accounts); // done (+5) + $categories = $this->helper->getCategoryReport($start, $end, $accounts); // done (+1) (20) + $balance = $this->helper->getBalanceReport($start, $end, $accounts); // +566 + // $bills = $this->helper->getBillReport($start, $end, $accounts); + + $bills = []; // and some id's, joined: - $accountIds = []; - /** @var Account $account */ - foreach ($accounts as $account) { - $accountIds[] = $account->id; - } - $accountIds = join(',', $accountIds); + $accountIds = join(',', $accounts->pluck('id')->toArray()); // continue! return view( diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 3d4f9fc2bf..fa0db398ba 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -817,4 +817,56 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn return $return; } + + /** + * Returns a list of expenses (in the field "spent", grouped per budget per account. + * + * @param Collection $budgets + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function spentPerBudgetPerAccount(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end) + { + + $accountIds = $accounts->pluck('id')->toArray(); + $budgetIds = $budgets->pluck('id')->toArray(); + $set = Auth::user()->transactionjournals() + ->leftJoin( + 'transactions AS t_from', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 't_from.transaction_journal_id')->where('t_from.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions AS t_to', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 't_to.transaction_journal_id')->where('t_to.amount', '>', 0); + } + ) + ->leftJoin('budget_transaction_journal', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id') + ->whereIn('t_from.account_id', $accountIds) + ->whereNotIn('t_to.account_id', $accountIds) + ->where( + function (Builder $q) use ($budgetIds) { + $q->whereIn('budget_transaction_journal.budget_id', $budgetIds); + $q->orWhereNull('budget_transaction_journal.budget_id'); + } + ) + ->after($start) + ->before($end) + ->groupBy('t_from.account_id') + ->groupBy('budget_transaction_journal.budget_id') + ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) + ->get( + [ + 't_from.account_id', + 'budget_transaction_journal.budget_id', + DB::Raw('SUM(`t_from`.`amount`) AS `spent`') + ] + ); + + return $set; + + } } diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index a06b661749..3ba1b8c1d8 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -15,6 +15,10 @@ use Illuminate\Support\Collection; */ interface BudgetRepositoryInterface { + + + + /** * @return void */ @@ -51,6 +55,19 @@ interface BudgetRepositoryInterface */ public function getExpensesPerMonth(Budget $budget, Carbon $start, Carbon $end); + + /** + * Returns a list of expenses (in the field "spent", grouped per budget per account. + * + * @param Collection $budgets + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function spentPerBudgetPerAccount(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end); + /** * Returns an array with the following key:value pairs: * @@ -84,6 +101,8 @@ interface BudgetRepositoryInterface */ public function spentPerDayForAccounts(Budget $budget, Collection $accounts, Carbon $start, Carbon $end); + + /** * Returns an array with the following key:value pairs: * diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index 446aa85755..59832ff3e4 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -5,11 +5,13 @@ namespace FireflyIII\Repositories\Tag; use Auth; use Carbon\Carbon; +use DB; use FireflyIII\Models\Account; use FireflyIII\Models\Tag; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\Support\CacheProperties; +use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; /** @@ -94,6 +96,49 @@ class TagRepository implements TagRepositoryInterface return $amount; } + + /** + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function allCoveredByBalancingActs(Collection $accounts, Carbon $start, Carbon $end) + { + $ids = $accounts->pluck('id')->toArray(); + $set = Auth::user()->tags() + ->leftJoin('tag_transaction_journal', 'tag_transaction_journal.tag_id', '=', 'tags.id') + ->leftJoin('transaction_journals', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') + ->leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id') + ->leftJoin( + 'transactions AS t_from', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 't_from.transaction_journal_id')->where('t_from.amount', '<', 0); + } + ) + ->leftJoin( + 'transactions AS t_to', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 't_to.transaction_journal_id')->where('t_to.amount', '>', 0); + } + ) + ->where('tags.tagMode', 'balancingAct') + ->where('transaction_types.type', TransactionType::TRANSFER) + ->where('transaction_journals.date', '>=', $start->format('Y-m-d')) + ->where('transaction_journals.date', '<=', $end->format('Y-m-d')) + ->whereNull('transaction_journals.deleted_at') + ->whereIn('t_from.account_id', $ids) + ->whereIn('t_to.account_id', $ids) + ->groupBy('t_to.account_id') + ->get( + [ + 't_to.account_id', + DB::Raw('SUM(`t_to`.`amount`) as `sum`') + ] + ); + + return $set; + } + /** * @param Tag $tag * diff --git a/app/Repositories/Tag/TagRepositoryInterface.php b/app/Repositories/Tag/TagRepositoryInterface.php index 75c6a4df96..35f5c0f83c 100644 --- a/app/Repositories/Tag/TagRepositoryInterface.php +++ b/app/Repositories/Tag/TagRepositoryInterface.php @@ -16,7 +16,14 @@ use Illuminate\Support\Collection; */ interface TagRepositoryInterface { - + /** + * @param Collection $accounts + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function allCoveredByBalancingActs(Collection $accounts, Carbon $start, Carbon $end); /** * @param TransactionJournal $journal From 94810e371a9912a7a63b25afdaf4467b576482ac Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 19:52:55 +0100 Subject: [PATCH 35/62] Enable bill report. --- app/Http/Controllers/ReportController.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index 33b7f87022..874b254664 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -131,9 +131,7 @@ class ReportController extends Controller $budgets = $this->helper->getBudgetReport($start, $end, $accounts); // done (+5) $categories = $this->helper->getCategoryReport($start, $end, $accounts); // done (+1) (20) $balance = $this->helper->getBalanceReport($start, $end, $accounts); // +566 - // $bills = $this->helper->getBillReport($start, $end, $accounts); - - $bills = []; + $bills = $this->helper->getBillReport($start, $end, $accounts); // and some id's, joined: $accountIds = join(',', $accounts->pluck('id')->toArray()); From 2f131dc1708422c2e63c2d14315247fb37aeb86a Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 19:55:00 +0100 Subject: [PATCH 36/62] Method no longer used. --- app/Repositories/Budget/BudgetRepository.php | 37 ------------------- .../Budget/BudgetRepositoryInterface.php | 19 ---------- 2 files changed, 56 deletions(-) diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index fa0db398ba..71886abeca 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -280,43 +280,6 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn return $return; } - /** - * Returns an array with the following key:value pairs: - * - * yyyy-mm-dd: - * - * Where yyyy-mm-dd is the date and is the money spent using DEPOSITS in the $budget - * from all the users accounts. - * - * @param Budget $budget - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return array - */ - public function spentPerDayForAccounts(Budget $budget, Collection $accounts, Carbon $start, Carbon $end) - { - $ids = $accounts->pluck('id')->toArray(); - /** @var Collection $query */ - $query = $budget->transactionJournals() - ->transactionTypes([TransactionType::WITHDRAWAL]) - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->whereIn('transactions.account_id', $ids) - ->where('transactions.amount', '<', 0) - ->before($end) - ->after($start) - ->groupBy('dateFormatted')->get(['transaction_journals.date as dateFormatted', DB::Raw('SUM(`transactions`.`amount`) AS `sum`')]); - - $return = []; - foreach ($query->toArray() as $entry) { - $return[$entry['dateFormatted']] = $entry['sum']; - } - - return $return; - } - - /** * @return Collection */ diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 3ba1b8c1d8..890ebf785a 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -84,25 +84,6 @@ interface BudgetRepositoryInterface */ public function spentPerDay(Budget $budget, Carbon $start, Carbon $end); - /** - * Returns an array with the following key:value pairs: - * - * yyyy-mm-dd: - * - * Where yyyy-mm-dd is the date and is the money spent using WITHDRAWALS in the $budget - * from the given users accounts.. - * - * @param Budget $budget - * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end - * - * @return array - */ - public function spentPerDayForAccounts(Budget $budget, Collection $accounts, Carbon $start, Carbon $end); - - - /** * Returns an array with the following key:value pairs: * From 2d177e660ec0a70857c8f661bb9abd02c6cc7b50 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 19:55:47 +0100 Subject: [PATCH 37/62] Method no longer used. --- app/Repositories/Budget/BudgetRepository.php | 14 -------------- .../Budget/BudgetRepositoryInterface.php | 10 ---------- 2 files changed, 24 deletions(-) diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 71886abeca..08874dc336 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -109,20 +109,6 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn return true; } - /** - * @param Budget $budget - * @param Carbon $date - * - * @return float - */ - public function expensesOnDay(Budget $budget, Carbon $date) - { - bcscale(2); - $sum = $budget->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->onDate($date)->get(['transaction_journals.*'])->sum('amount'); - - return $sum; - } - /** * @return Collection */ diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 890ebf785a..0aae1ada98 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -136,16 +136,6 @@ interface BudgetRepositoryInterface */ public function getBudgetsAndExpensesPerYear(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end); - /** - * Takes tags into account. - * - * @param Budget $budget - * @param Carbon $date - * - * @return float - */ - public function expensesOnDay(Budget $budget, Carbon $date); - /** * @return Collection */ From d16fb30a62c432b0588f51d058e987d72ce77b6c Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 19:56:23 +0100 Subject: [PATCH 38/62] Method no longer used. --- app/Repositories/Budget/BudgetRepository.php | 19 ------------------- .../Budget/BudgetRepositoryInterface.php | 9 --------- 2 files changed, 28 deletions(-) diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 08874dc336..8e45a05653 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -203,25 +203,6 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn ->get(['limit_repetitions.*', 'budget_limits.budget_id']); } - - /** - * @param Budget $budget - * @param Carbon $start - * @param Carbon $end - * - * @return Collection - */ - public function getBudgetLimitRepetitions(Budget $budget, Carbon $start, Carbon $end) - { - /** @var Collection $repetitions */ - return LimitRepetition:: - leftJoin('budget_limits', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id') - ->where('limit_repetitions.startdate', '<=', $end->format('Y-m-d 00:00:00')) - ->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d 00:00:00')) - ->where('budget_limits.budget_id', $budget->id) - ->get(['limit_repetitions.*']); - } - /** * @param Budget $budget * diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 0aae1ada98..af0eedc769 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -152,15 +152,6 @@ interface BudgetRepositoryInterface */ public function getBudgetedPerYear(Collection $budgets, Carbon $start, Carbon $end); - /** - * @param Budget $budget - * @param Carbon $start - * @param Carbon $end - * - * @return Collection - */ - public function getBudgetLimitRepetitions(Budget $budget, Carbon $start, Carbon $end); - /** * @param Carbon $start * @param Carbon $end From 7a4a78628d1221c85f2124704baddd5872e89344 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 19:57:23 +0100 Subject: [PATCH 39/62] Method no longer used. --- app/Http/Controllers/BudgetController.php | 28 ++++++------------- app/Repositories/Budget/BudgetRepository.php | 11 -------- .../Budget/BudgetRepositoryInterface.php | 7 ----- 3 files changed, 8 insertions(+), 38 deletions(-) diff --git a/app/Http/Controllers/BudgetController.php b/app/Http/Controllers/BudgetController.php index e680e5e2c5..00587db566 100644 --- a/app/Http/Controllers/BudgetController.php +++ b/app/Http/Controllers/BudgetController.php @@ -233,20 +233,15 @@ class BudgetController extends Controller $journals = $repository->getJournals($budget, $repetition); if (is_null($repetition->id)) { - $start = $repository->firstActivity($budget); - $end = new Carbon; - $set = $budget->limitrepetitions()->orderBy('startdate', 'DESC')->get(); - //$set = $repository->getBudgetLimits($budget); - //$subTitle = e($budget->name); + $start = $repository->firstActivity($budget); + $end = new Carbon; + $set = $budget->limitrepetitions()->orderBy('startdate', 'DESC')->get(); + $subTitle = e($budget->name); } else { - $start = $repetition->startdate; - $end = $repetition->enddate; - $set = new Collection([$repetition]); - // $spentArray = $repository->spentPerDay($budget, $start, $end); - // $budgetLimit = $repetition->budgetLimit; - // $budgetLimit->spent = $this->getSumOfRange($start, $end, $spentArray); // bit weird but it works. - // $limits = new Collection([$budgetLimit]); - //$subTitle = trans('firefly.budget_in_month', ['name' => $budget->name, 'month' => $repetition->startdate->formatLocalized($this->monthFormat)]); + $start = $repetition->startdate; + $end = $repetition->enddate; + $set = new Collection([$repetition]); + $subTitle = trans('firefly.budget_in_month', ['name' => $budget->name, 'month' => $repetition->startdate->formatLocalized($this->monthFormat)]); } $spentArray = $repository->spentPerDay($budget, $start, $end); @@ -258,13 +253,6 @@ class BudgetController extends Controller $limits->push($entry); } - // loop limits and set the amount spent for each limit. - // /** @var BudgetLimit $budgetLimit */ - // foreach ($set as $budgetLimit) { - // $start = $budgetLimit->startdate; - // $end = $budgetLimit->lim - // } - $journals->setPath('/budgets/show/' . $budget->id); return view('budgets.show', compact('limits', 'budget', 'repetition', 'journals', 'subTitle')); diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 8e45a05653..ca8723bc5f 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -203,17 +203,6 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn ->get(['limit_repetitions.*', 'budget_limits.budget_id']); } - /** - * @param Budget $budget - * - * @return Collection - */ - public function getBudgetLimits(Budget $budget) - { - return $budget->budgetLimits()->orderBy('startdate', 'DESC')->get(); - } - - /** * Returns an array with the following key:value pairs: * diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index af0eedc769..1bec454037 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -160,13 +160,6 @@ interface BudgetRepositoryInterface */ public function getAllBudgetLimitRepetitions(Carbon $start, Carbon $end); - /** - * @param Budget $budget - * - * @return Collection - */ - public function getBudgetLimits(Budget $budget); - /** * @return Collection */ From fc5b315af05de4a27a9edadc24c734bb7097f3d9 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 19:58:05 +0100 Subject: [PATCH 40/62] Method no longer used. --- app/Repositories/Budget/BudgetRepository.php | 17 ----------------- .../Budget/BudgetRepositoryInterface.php | 9 --------- 2 files changed, 26 deletions(-) diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index ca8723bc5f..c64a63f3c8 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -416,23 +416,6 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn return $paginator; } - /** - * @deprecated - * - * @param Budget $budget - * - * @return Carbon - */ - public function getLastBudgetLimitDate(Budget $budget) - { - $limit = $budget->budgetlimits()->orderBy('startdate', 'DESC')->first(); - if ($limit) { - return $limit->startdate; - } - - return Carbon::now()->startOfYear(); - } - /** * @deprecated * diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 1bec454037..bcc478c969 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -208,15 +208,6 @@ interface BudgetRepositoryInterface */ public function getJournals(Budget $budget, LimitRepetition $repetition = null, $take = 50); - /** - * @deprecated - * - * @param Budget $budget - * - * @return Carbon - */ - public function getLastBudgetLimitDate(Budget $budget); - /** * @deprecated * From efc9bc71a7fcb1cc3ea273a18634f3ff7db3207a Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 19:58:31 +0100 Subject: [PATCH 41/62] Method no longer used. --- app/Repositories/Budget/BudgetRepository.php | 22 ------------------- .../Budget/BudgetRepositoryInterface.php | 10 --------- 2 files changed, 32 deletions(-) diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index c64a63f3c8..6aca1f3cbb 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -416,28 +416,6 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn return $paginator; } - /** - * @deprecated - * - * @param Budget $budget - * @param Carbon $date - * - * @return float|null - */ - public function getLimitAmountOnDate(Budget $budget, Carbon $date) - { - $repetition = LimitRepetition::leftJoin('budget_limits', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id') - ->where('limit_repetitions.startdate', $date->format('Y-m-d 00:00:00')) - ->where('budget_limits.budget_id', $budget->id) - ->first(['limit_repetitions.*']); - - if ($repetition) { - return $repetition->amount; - } - - return null; - } - /** * @param Carbon $start * @param Carbon $end diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index bcc478c969..0411da4d77 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -208,16 +208,6 @@ interface BudgetRepositoryInterface */ public function getJournals(Budget $budget, LimitRepetition $repetition = null, $take = 50); - /** - * @deprecated - * - * @param Budget $budget - * @param Carbon $date - * - * @return float - */ - public function getLimitAmountOnDate(Budget $budget, Carbon $date); - /** * @param Carbon $start * @param Carbon $end From 1a7b1ce499344d2da4e82ce5165916686995a0c8 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 20:00:20 +0100 Subject: [PATCH 42/62] Method no longer used. --- .../Category/SingleCategoryRepository.php | 14 -------------- .../Category/SingleCategoryRepositoryInterface.php | 12 ------------ 2 files changed, 26 deletions(-) diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php index 1f56c180d2..5c3bf5481c 100644 --- a/app/Repositories/Category/SingleCategoryRepository.php +++ b/app/Repositories/Category/SingleCategoryRepository.php @@ -18,20 +18,6 @@ use Illuminate\Support\Collection; class SingleCategoryRepository extends ComponentRepository implements SingleCategoryRepositoryInterface { - /** - * @param Category $category - * @param Carbon $start - * @param Carbon $end - * @param Collection $accounts - * - * @return string - */ - public function balanceInPeriod(Category $category, Carbon $start, Carbon $end, Collection $accounts) - { - return $this->commonBalanceInPeriod($category, $start, $end, $accounts); - } - - /** * @param Category $category * diff --git a/app/Repositories/Category/SingleCategoryRepositoryInterface.php b/app/Repositories/Category/SingleCategoryRepositoryInterface.php index d2e233da30..4b4a5e2f4e 100644 --- a/app/Repositories/Category/SingleCategoryRepositoryInterface.php +++ b/app/Repositories/Category/SingleCategoryRepositoryInterface.php @@ -13,18 +13,6 @@ use Illuminate\Support\Collection; */ interface SingleCategoryRepositoryInterface { - /** - * Corrected for tags and list of accounts. - * - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * @param Collection $accounts - * - * @return string - */ - public function balanceInPeriod(Category $category, Carbon $start, Carbon $end, Collection $accounts); - /** * @param Category $category * From bf16c9a42bb4f18afd86037603559a2e63775bbc Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 20:01:07 +0100 Subject: [PATCH 43/62] Method no longer used. --- .../Category/SingleCategoryRepository.php | 21 ------------------- .../SingleCategoryRepositoryInterface.php | 11 ---------- 2 files changed, 32 deletions(-) diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php index 5c3bf5481c..8393eb8689 100644 --- a/app/Repositories/Category/SingleCategoryRepository.php +++ b/app/Repositories/Category/SingleCategoryRepository.php @@ -54,27 +54,6 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate return true; } - /** - * TODO this method is not optimal, and should be replaced. - * - * @deprecated - * - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * - * @return string - */ - public function earnedInPeriod(Category $category, Carbon $start, Carbon $end) - { - $sum = $category->transactionjournals()->transactionTypes([TransactionType::DEPOSIT])->before($end)->after($start)->get(['transaction_journals.*']) - ->sum( - 'amount' - ); - - return $sum; - } - /** * Returns an array with the following key:value pairs: * diff --git a/app/Repositories/Category/SingleCategoryRepositoryInterface.php b/app/Repositories/Category/SingleCategoryRepositoryInterface.php index 4b4a5e2f4e..ccad049bad 100644 --- a/app/Repositories/Category/SingleCategoryRepositoryInterface.php +++ b/app/Repositories/Category/SingleCategoryRepositoryInterface.php @@ -37,17 +37,6 @@ interface SingleCategoryRepositoryInterface */ public function destroy(Category $category); - /** - * @deprecated - * - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * - * @return string - */ - public function earnedInPeriod(Category $category, Carbon $start, Carbon $end); - /** * Returns an array with the following key:value pairs: * From 7d1de0da174d2790699117457b9735d3a4849685 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 20:02:01 +0100 Subject: [PATCH 44/62] Method no longer used. --- .../Category/SingleCategoryRepository.php | 22 ------------------- .../SingleCategoryRepositoryInterface.php | 11 ---------- 2 files changed, 33 deletions(-) diff --git a/app/Repositories/Category/SingleCategoryRepository.php b/app/Repositories/Category/SingleCategoryRepository.php index 8393eb8689..320c78e7f0 100644 --- a/app/Repositories/Category/SingleCategoryRepository.php +++ b/app/Repositories/Category/SingleCategoryRepository.php @@ -168,28 +168,6 @@ class SingleCategoryRepository extends ComponentRepository implements SingleCate return null; } - /** - * TODO this method is not optimal, and should be replaced. - * - * @deprecated - * - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * - * @return string - */ - public function spentInPeriod(Category $category, Carbon $start, Carbon $end) - { - $sum = $category->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->before($end)->after($start)->get(['transaction_journals.*']) - ->sum( - 'amount' - ); - - return $sum; - } - - /** * Returns an array with the following key:value pairs: * diff --git a/app/Repositories/Category/SingleCategoryRepositoryInterface.php b/app/Repositories/Category/SingleCategoryRepositoryInterface.php index ccad049bad..6e6b4b76c2 100644 --- a/app/Repositories/Category/SingleCategoryRepositoryInterface.php +++ b/app/Repositories/Category/SingleCategoryRepositoryInterface.php @@ -88,17 +88,6 @@ interface SingleCategoryRepositoryInterface */ public function getLatestActivity(Category $category); - /** - * @deprecated - * - * @param Category $category - * @param \Carbon\Carbon $start - * @param \Carbon\Carbon $end - * - * @return string - */ - public function spentInPeriod(Category $category, Carbon $start, Carbon $end); - /** * Returns an array with the following key:value pairs: * From bb4e2be9eba1356e80094b72a2dddf4fc64b1cda Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 20:04:44 +0100 Subject: [PATCH 45/62] Method no longer used. --- app/Helpers/Report/ReportHelper.php | 2 -- app/Helpers/Report/ReportQuery.php | 23 --------------------- app/Helpers/Report/ReportQueryInterface.php | 12 ----------- 3 files changed, 37 deletions(-) diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 46dbebb137..27b94e9cb4 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -365,8 +365,6 @@ class ReportHelper implements ReportHelperInterface if (!is_null($entry->first())) { $spent = $entry->first()->spent; } - //$spent = $this->query->spentInBudget($account, $budget, $start, $end); // I think shared is irrelevant. - $balanceEntry->setSpent($spent); $line->addBalanceEntry($balanceEntry); } diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php index bec2475577..638b3d0129 100644 --- a/app/Helpers/Report/ReportQuery.php +++ b/app/Helpers/Report/ReportQuery.php @@ -18,29 +18,6 @@ use Illuminate\Support\Collection; */ class ReportQuery implements ReportQueryInterface { - /** - * Covers tags - * - * @param Account $account - * @param Budget $budget - * @param Carbon $start - * @param Carbon $end - * - * @return float - */ - public function spentInBudget(Account $account, Budget $budget, Carbon $start, Carbon $end) - { - - return Auth::user()->transactionjournals() - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') - ->transactionTypes([TransactionType::WITHDRAWAL]) - ->where('transactions.account_id', $account->id) - ->before($end) - ->after($start) - ->where('budget_transaction_journal.budget_id', $budget->id) - ->get(['transaction_journals.*'])->sum('amount'); - } /** * @param Account $account diff --git a/app/Helpers/Report/ReportQueryInterface.php b/app/Helpers/Report/ReportQueryInterface.php index 45d910d46c..182b35d8bd 100644 --- a/app/Helpers/Report/ReportQueryInterface.php +++ b/app/Helpers/Report/ReportQueryInterface.php @@ -39,18 +39,6 @@ interface ReportQueryInterface */ public function expense(Collection $accounts, Carbon $start, Carbon $end); - /** - * Covers tags as well. - * - * @param Account $account - * @param Budget $budget - * @param Carbon $start - * @param Carbon $end - * - * @return float - */ - public function spentInBudget(Account $account, Budget $budget, Carbon $start, Carbon $end); - /** * @param Account $account * @param Carbon $start From 64dbb14241417ab967c27ea4567298f377a26ece Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 20:05:14 +0100 Subject: [PATCH 46/62] Method no longer used. --- app/Helpers/Report/ReportHelper.php | 1 - app/Helpers/Report/ReportQuery.php | 20 -------------------- app/Helpers/Report/ReportQueryInterface.php | 9 --------- 3 files changed, 30 deletions(-) diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 27b94e9cb4..c677a1bfac 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -384,7 +384,6 @@ class ReportHelper implements ReportHelperInterface $diffLine->setRole(BalanceLine::ROLE_DIFFROLE); foreach ($accounts as $account) { - //$spent = $this->query->spentNoBudget($account, $start, $end); $entry = $spentData->filter( function (TransactionJournal $model) use ($budget, $account) { return $model->account_id == $account->id && is_null($model->budget_id); diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php index 638b3d0129..208c4e8ff2 100644 --- a/app/Helpers/Report/ReportQuery.php +++ b/app/Helpers/Report/ReportQuery.php @@ -19,26 +19,6 @@ use Illuminate\Support\Collection; class ReportQuery implements ReportQueryInterface { - /** - * @param Account $account - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function spentNoBudget(Account $account, Carbon $start, Carbon $end) - { - return - Auth::user()->transactionjournals() - ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') - ->transactionTypes([TransactionType::WITHDRAWAL]) - ->where('transactions.account_id', $account->id) - ->before($end) - ->after($start) - ->whereNull('budget_transaction_journal.budget_id')->get(['transaction_journals.*'])->sum('amount'); - } - /** * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) * grouped by month like so: "2015-01" => '123.45' diff --git a/app/Helpers/Report/ReportQueryInterface.php b/app/Helpers/Report/ReportQueryInterface.php index 182b35d8bd..8bb0c43762 100644 --- a/app/Helpers/Report/ReportQueryInterface.php +++ b/app/Helpers/Report/ReportQueryInterface.php @@ -39,15 +39,6 @@ interface ReportQueryInterface */ public function expense(Collection $accounts, Carbon $start, Carbon $end); - /** - * @param Account $account - * @param Carbon $start - * @param Carbon $end - * - * @return string - */ - public function spentNoBudget(Account $account, Carbon $start, Carbon $end); - /** * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) * grouped by month like so: "2015-01" => '123.45' From 27cabb398e667a7efe4d9ba9ad068610ff9bf628 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 21:07:15 +0100 Subject: [PATCH 47/62] More queries filtered. --- app/Helpers/Report/ReportHelper.php | 20 +++--- app/Repositories/Bill/BillRepository.php | 62 +++++++++++++++---- .../Bill/BillRepositoryInterface.php | 13 ++++ 3 files changed, 73 insertions(+), 22 deletions(-) diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index c677a1bfac..b96ef459af 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -451,6 +451,7 @@ class ReportHelper implements ReportHelperInterface /** @var \FireflyIII\Repositories\Bill\BillRepositoryInterface $repository */ $repository = app('FireflyIII\Repositories\Bill\BillRepositoryInterface'); $bills = $repository->getBillsForAccounts($accounts); + $journals = $repository->getAllJournalsInRange($bills, $start, $end); $collection = new BillCollection; /** @var Bill $bill */ @@ -463,16 +464,17 @@ class ReportHelper implements ReportHelperInterface // is hit in period? bcscale(2); - $set = $repository->getJournalsInRange($bill, $start, $end); - if ($set->count() == 0) { - $billLine->setHit(false); - } else { - $billLine->setHit(true); - $amount = '0'; - foreach ($set as $entry) { - $amount = bcadd($amount, $entry->amount); + + $entry = $journals->filter( + function (TransactionJournal $journal) use ($bill) { + return $journal->bill_id == $bill->id; } - $billLine->setAmount($amount); + ); + if (!is_null($entry->first())) { + $billLine->setAmount($entry->first()->journalAmount); + $billLine->setHit(true); + } else { + $billLine->setHit(false); } $collection->addBill($billLine); diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index 7a5c11c985..54bba39d9f 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -35,6 +35,40 @@ class BillRepository implements BillRepositoryInterface return $bill->delete(); } + /** + * Returns all journals connected to these bills in the given range. Amount paid + * is stored in "journalAmount" as a negative number. + * + * @param Collection $bills + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getAllJournalsInRange(Collection $bills, Carbon $start, Carbon $end) + { + $ids = $bills->pluck('id')->toArray(); + + $set = Auth::user()->transactionjournals() + ->leftJoin( + 'transactions', function (JoinClause $join) { + $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0); + } + ) + ->whereIn('bill_id', $ids) + ->before($end) + ->after($start) + ->groupBy('transaction_journals.bill_id') + ->get( + [ + 'transaction_journals.bill_id', + DB::Raw('SUM(`transactions`.`amount`) as `journalAmount`') + ] + ); + + return $set; + } + /** * @return Collection @@ -63,20 +97,22 @@ class BillRepository implements BillRepositoryInterface */ public function getBillsForAccounts(Collection $accounts) { - /** @var Collection $set */ - $set = Auth::user()->bills()->orderBy('name', 'ASC')->get(); $ids = $accounts->pluck('id')->toArray(); - $set = $set->filter( - function (Bill $bill) use ($ids) { - // get transaction journals from or to any of the mentioned accounts. - // when zero, return null. - $journals = $bill->transactionjournals()->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->whereIn('transactions.account_id', $ids)->count(); - - return ($journals > 0); - - } - ); + $set = Auth::user()->bills() + ->leftJoin( + 'transaction_journals', function (JoinClause $join) { + $join->on('transaction_journals.bill_id', '=', 'bills.id')->whereNull('transaction_journals.deleted_at'); + } + ) + ->leftJoin( + 'transactions', function (JoinClause $join) { + $join->on('transaction_journals.id', '=', 'transactions.transaction_journal_id')->where('transactions.amount', '<', 0); + } + ) + ->whereIn('transactions.account_id', $ids) + ->whereNull('transaction_journals.deleted_at') + ->groupBy('bills.id') + ->get(['bills.*']); $set = $set->sortBy( function (Bill $bill) { diff --git a/app/Repositories/Bill/BillRepositoryInterface.php b/app/Repositories/Bill/BillRepositoryInterface.php index d171aedcdb..0cf52754bf 100644 --- a/app/Repositories/Bill/BillRepositoryInterface.php +++ b/app/Repositories/Bill/BillRepositoryInterface.php @@ -59,6 +59,19 @@ interface BillRepositoryInterface */ public function destroy(Bill $bill); + /** + * Returns all journals connected to these bills in the given range. Amount paid + * is stored in "journalAmount" as a negative number. + * + * @param Collection $bills + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + */ + public function getAllJournalsInRange(Collection $bills, Carbon $start, Carbon $end); + + /** * @return Collection */ From 5eb0e18cae9260317cdd5502e4259ffc237624d2 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 21:15:03 +0100 Subject: [PATCH 48/62] Cleaning up --- app/Helpers/Collection/BalanceLine.php | 63 +++++++++---------- app/Helpers/Report/ReportQuery.php | 2 - app/Helpers/Report/ReportQueryInterface.php | 20 +++--- .../Budget/BudgetRepositoryInterface.php | 6 +- resources/twig/emails/registered-html.twig | 1 + 5 files changed, 43 insertions(+), 49 deletions(-) diff --git a/app/Helpers/Collection/BalanceLine.php b/app/Helpers/Collection/BalanceLine.php index ff0d17fc3b..0800010c42 100644 --- a/app/Helpers/Collection/BalanceLine.php +++ b/app/Helpers/Collection/BalanceLine.php @@ -3,7 +3,6 @@ namespace FireflyIII\Helpers\Collection; use FireflyIII\Models\Budget as BudgetModel; -use FireflyIII\Models\LimitRepetition; use Illuminate\Support\Collection; /** @@ -45,24 +44,19 @@ class BalanceLine } /** - * @return string + * @return Collection */ - public function getTitle() + public function getBalanceEntries() { - if ($this->getBudget() instanceof BudgetModel) { - return $this->getBudget()->name; - } - if ($this->getRole() == self::ROLE_DEFAULTROLE) { - return trans('firefly.noBudget'); - } - if ($this->getRole() == self::ROLE_TAGROLE) { - return trans('firefly.coveredWithTags'); - } - if ($this->getRole() == self::ROLE_DIFFROLE) { - return trans('firefly.leftUnbalanced'); - } + return $this->balanceEntries; + } - return ''; + /** + * @param Collection $balanceEntries + */ + public function setBalanceEntries($balanceEntries) + { + $this->balanceEntries = $balanceEntries; } /** @@ -97,6 +91,27 @@ class BalanceLine $this->role = $role; } + /** + * @return string + */ + public function getTitle() + { + if ($this->getBudget() instanceof BudgetModel) { + return $this->getBudget()->name; + } + if ($this->getRole() == self::ROLE_DEFAULTROLE) { + return trans('firefly.noBudget'); + } + if ($this->getRole() == self::ROLE_TAGROLE) { + return trans('firefly.coveredWithTags'); + } + if ($this->getRole() == self::ROLE_DIFFROLE) { + return trans('firefly.leftUnbalanced'); + } + + return ''; + } + /** * If a BalanceLine has a budget/repetition, each BalanceEntry in this BalanceLine * should have a "spent" value, which is the amount of money that has been spent @@ -115,20 +130,4 @@ class BalanceLine return $start; } - - /** - * @return Collection - */ - public function getBalanceEntries() - { - return $this->balanceEntries; - } - - /** - * @param Collection $balanceEntries - */ - public function setBalanceEntries($balanceEntries) - { - $this->balanceEntries = $balanceEntries; - } } diff --git a/app/Helpers/Report/ReportQuery.php b/app/Helpers/Report/ReportQuery.php index 208c4e8ff2..24fa89dc7d 100644 --- a/app/Helpers/Report/ReportQuery.php +++ b/app/Helpers/Report/ReportQuery.php @@ -5,8 +5,6 @@ namespace FireflyIII\Helpers\Report; use Auth; use Carbon\Carbon; use DB; -use FireflyIII\Models\Account; -use FireflyIII\Models\Budget; use FireflyIII\Models\TransactionType; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; diff --git a/app/Helpers/Report/ReportQueryInterface.php b/app/Helpers/Report/ReportQueryInterface.php index 8bb0c43762..0656ec2115 100644 --- a/app/Helpers/Report/ReportQueryInterface.php +++ b/app/Helpers/Report/ReportQueryInterface.php @@ -3,8 +3,6 @@ namespace FireflyIII\Helpers\Report; use Carbon\Carbon; -use FireflyIII\Models\Account; -use FireflyIII\Models\Budget; use Illuminate\Support\Collection; /** @@ -16,16 +14,16 @@ interface ReportQueryInterface { /** - * This method returns all the "in" transaction journals for the given account and given period. The amount - * is stored in "journalAmount". + * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) + * grouped by month like so: "2015-01" => '123.45' * * @param Collection $accounts * @param Carbon $start * @param Carbon $end * - * @return Collection + * @return array */ - public function income(Collection $accounts, Carbon $start, Carbon $end); + public function earnedPerMonth(Collection $accounts, Carbon $start, Carbon $end); /** * This method returns all the "out" transaction journals for the given account and given period. The amount @@ -40,16 +38,16 @@ interface ReportQueryInterface public function expense(Collection $accounts, Carbon $start, Carbon $end); /** - * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) - * grouped by month like so: "2015-01" => '123.45' + * This method returns all the "in" transaction journals for the given account and given period. The amount + * is stored in "journalAmount". * * @param Collection $accounts * @param Carbon $start * @param Carbon $end * - * @return array + * @return Collection */ - public function spentPerMonth(Collection $accounts, Carbon $start, Carbon $end); + public function income(Collection $accounts, Carbon $start, Carbon $end); /** * Returns an array of the amount of money spent in the given accounts (on withdrawals, opening balances and transfers) @@ -61,7 +59,7 @@ interface ReportQueryInterface * * @return array */ - public function earnedPerMonth(Collection $accounts, Carbon $start, Carbon $end); + public function spentPerMonth(Collection $accounts, Carbon $start, Carbon $end); } diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 0411da4d77..c9c9d8bc40 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -17,8 +17,6 @@ interface BudgetRepositoryInterface { - - /** * @return void */ @@ -97,8 +95,8 @@ interface BudgetRepositoryInterface * from the given users accounts.. * * @param Collection $accounts - * @param Carbon $start - * @param Carbon $end + * @param Carbon $start + * @param Carbon $end * * @return array */ diff --git a/resources/twig/emails/registered-html.twig b/resources/twig/emails/registered-html.twig index d05f6901d0..532322e75a 100644 --- a/resources/twig/emails/registered-html.twig +++ b/resources/twig/emails/registered-html.twig @@ -61,6 +61,7 @@ + From e892c9a8246b4cb001bf065fee803d694cedb433 Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 1 Jan 2016 21:49:27 +0100 Subject: [PATCH 49/62] Followed up on some inspections. --- .../Controllers/Chart/AccountController.php | 1 + .../Controllers/Chart/ReportController.php | 2 + app/Http/Controllers/CsvController.php | 2 +- app/Http/Controllers/PiggyBankController.php | 2 +- app/Http/Middleware/Authenticate.php | 5 +- app/Http/breadcrumbs.php | 4 +- app/Models/Account.php | 63 +++++------- app/Models/AccountMeta.php | 24 ++--- app/Models/AccountType.php | 22 ++--- app/Models/Attachment.php | 54 ++++------ app/Models/Bill.php | 58 ++++------- app/Models/Budget.php | 36 +++---- app/Models/BudgetLimit.php | 33 +++---- app/Models/Category.php | 33 +++---- app/Models/Component.php | 25 ++--- app/Models/LimitRepetition.php | 27 ++--- app/Models/Permission.php | 25 ++--- app/Models/PiggyBank.php | 53 ++++------ app/Models/PiggyBankEvent.php | 29 +++--- app/Models/PiggyBankRepetition.php | 31 +++--- app/Models/Preference.php | 31 +++--- app/Models/Role.php | 27 +++-- app/Models/Tag.php | 46 ++++----- app/Models/Transaction.php | 38 +++---- app/Models/TransactionCurrency.php | 28 +++--- app/Models/TransactionGroup.php | 28 +++--- app/Models/TransactionJournal.php | 99 ++++++++----------- app/Models/TransactionRelation.php | 21 ---- app/Models/TransactionType.php | 22 ++--- app/Repositories/Budget/BudgetRepository.php | 4 +- app/Support/Steam.php | 6 +- app/User.php | 66 ++++++++----- 32 files changed, 374 insertions(+), 571 deletions(-) delete mode 100644 app/Models/TransactionRelation.php diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php index 92cd33233a..dc6fe0cf13 100644 --- a/app/Http/Controllers/Chart/AccountController.php +++ b/app/Http/Controllers/Chart/AccountController.php @@ -53,6 +53,7 @@ class AccountController extends Controller $cache->addProperty('all'); $cache->addProperty('accounts'); $cache->addProperty('default'); + $cache->addProperty($reportType); $cache->addProperty($accounts); if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php index ebd258c680..1c2a68651a 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -49,6 +49,7 @@ class ReportController extends Controller $cache = new CacheProperties; $cache->addProperty('yearInOut'); $cache->addProperty($start); + $cache->addProperty($reportType); $cache->addProperty($accounts); $cache->addProperty($end); if ($cache->has()) { @@ -115,6 +116,7 @@ class ReportController extends Controller $cache->addProperty('yearInOutSummarized'); $cache->addProperty($start); $cache->addProperty($end); + $cache->addProperty($reportType); $cache->addProperty($accounts); if ($cache->has()) { return Response::json($cache->get()); // @codeCoverageIgnore diff --git a/app/Http/Controllers/CsvController.php b/app/Http/Controllers/CsvController.php index f2cac49ff6..bde7d5b7e0 100644 --- a/app/Http/Controllers/CsvController.php +++ b/app/Http/Controllers/CsvController.php @@ -146,7 +146,7 @@ class CsvController extends Controller * * STEP ONE * - * @param AccountRepositoryInterface $repository + * @param ARI $repository * * @return \Illuminate\View\View */ diff --git a/app/Http/Controllers/PiggyBankController.php b/app/Http/Controllers/PiggyBankController.php index 8b431fdd72..6c33fccc8c 100644 --- a/app/Http/Controllers/PiggyBankController.php +++ b/app/Http/Controllers/PiggyBankController.php @@ -157,7 +157,7 @@ class PiggyBankController extends Controller } /** - * @param AccountRepositoryInterface $repository + * @param ARI $repository * @param PiggyBankRepositoryInterface $piggyRepository * * @return View diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index a11d1d9e99..5cc1d665de 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -54,8 +54,9 @@ class Authenticate return redirect()->guest('auth/login'); } } - - if ($this->auth->user() instanceof User && intval($this->auth->user()->blocked) == 1) { + /** @var User $user */ + $user = $this->auth->user(); + if ($user instanceof User && intval($user->blocked) == 1) { Auth::logout(); return redirect()->route('index'); diff --git a/app/Http/breadcrumbs.php b/app/Http/breadcrumbs.php index e429509482..f4c6487c1d 100644 --- a/app/Http/breadcrumbs.php +++ b/app/Http/breadcrumbs.php @@ -355,9 +355,9 @@ Breadcrumbs::register( $breadcrumbs->parent('reports.index'); $monthFormat = trans('config.month_and_day'); - $title = trans('firefly.report_default', ['start' => $start->formatLocalized($monthFormat), 'end' => $end->formatLocalized($monthFormat)]); + $title = trans('firefly.report_' . $reportType, ['start' => $start->formatLocalized($monthFormat), 'end' => $end->formatLocalized($monthFormat)]); - $breadcrumbs->push($title, route('reports.report', ['url' => 'abcde'])); + $breadcrumbs->push($title, route('reports.report', [$reportType, $start->format('Ymd'), $end->format('Ymd'), join(',', $accountIds)])); } ); diff --git a/app/Models/Account.php b/app/Models/Account.php index b3967b1da4..683310dbfc 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -1,53 +1,38 @@ pluck('id')->toArray(); $budgetIds = $budgets->pluck('id')->toArray(); $set = Auth::user()->transactionjournals() @@ -740,8 +739,7 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn ->transactionTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]) ->get( [ - 't_from.account_id', - 'budget_transaction_journal.budget_id', + 't_from.account_id', 'budget_transaction_journal.budget_id', DB::Raw('SUM(`t_from`.`amount`) AS `spent`') ] ); diff --git a/app/Support/Steam.php b/app/Support/Steam.php index de77081704..4a2a733355 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -77,9 +77,9 @@ class Steam * * [yyyy-mm-dd] => 123,2 * - * @param Account $account - * @param Carbon $start - * @param Carbon $end + * @param \FireflyIII\Models\Account $account + * @param \Carbon\Carbon $start + * @param \Carbon\Carbon $end * * @return array */ diff --git a/app/User.php b/app/User.php index 2fd0ae8fdf..d1924bbccc 100644 --- a/app/User.php +++ b/app/User.php @@ -1,43 +1,55 @@ Date: Fri, 1 Jan 2016 21:59:19 +0100 Subject: [PATCH 50/62] Fix broken route. --- app/Http/breadcrumbs.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/breadcrumbs.php b/app/Http/breadcrumbs.php index f4c6487c1d..cf3de22751 100644 --- a/app/Http/breadcrumbs.php +++ b/app/Http/breadcrumbs.php @@ -357,7 +357,7 @@ Breadcrumbs::register( $monthFormat = trans('config.month_and_day'); $title = trans('firefly.report_' . $reportType, ['start' => $start->formatLocalized($monthFormat), 'end' => $end->formatLocalized($monthFormat)]); - $breadcrumbs->push($title, route('reports.report', [$reportType, $start->format('Ymd'), $end->format('Ymd'), join(',', $accountIds)])); + $breadcrumbs->push($title, route('reports.report', [$reportType, $start->format('Ymd'), $end->format('Ymd'), $accountIds])); } ); From eb7c79ad275122a0a6032704612ce9d3ad0519bf Mon Sep 17 00:00:00 2001 From: James Cole Date: Sat, 2 Jan 2016 09:47:01 +0100 Subject: [PATCH 51/62] Can be written to. --- app/Models/PiggyBankEvent.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Models/PiggyBankEvent.php b/app/Models/PiggyBankEvent.php index a67d81d9d2..e373ab93a1 100644 --- a/app/Models/PiggyBankEvent.php +++ b/app/Models/PiggyBankEvent.php @@ -13,7 +13,7 @@ use Illuminate\Database\Eloquent\Model; * @property integer $transaction_journal_id * @property Carbon $date * @property float $amount - * @property-read PiggyBank $piggyBank + * @property PiggyBank $piggyBank * @property-read TransactionJournal $transactionJournal */ class PiggyBankEvent extends Model From 265dd372126ebe1608e639968ba31ccd5c056d8c Mon Sep 17 00:00:00 2001 From: James Cole Date: Sat, 2 Jan 2016 16:31:14 +0100 Subject: [PATCH 52/62] Cleanup and add various warnings. --- .../Events/ConnectJournalToPiggyBank.php | 2 -- app/Http/Controllers/BudgetController.php | 1 - app/Http/Controllers/PiggyBankController.php | 1 - app/Http/Middleware/Range.php | 1 - app/Http/Requests/JournalFormRequest.php | 1 - app/Models/Account.php | 1 - app/Models/Category.php | 1 - app/Models/Tag.php | 2 -- app/Providers/ConfigServiceProvider.php | 1 - app/Providers/FireflyServiceProvider.php | 2 +- app/Providers/RouteServiceProvider.php | 2 ++ app/Repositories/Account/AccountRepository.php | 2 -- app/Repositories/Tag/TagRepository.php | 2 -- app/Support/ExpandedForm.php | 1 - app/Support/Twig/General.php | 1 - app/Validation/FireflyValidator.php | 17 ++++++++++++++--- 16 files changed, 17 insertions(+), 21 deletions(-) diff --git a/app/Handlers/Events/ConnectJournalToPiggyBank.php b/app/Handlers/Events/ConnectJournalToPiggyBank.php index d4c9cef764..4b599a9dec 100644 --- a/app/Handlers/Events/ConnectJournalToPiggyBank.php +++ b/app/Handlers/Events/ConnectJournalToPiggyBank.php @@ -28,8 +28,6 @@ class ConnectJournalToPiggyBank /** * Handle the event when journal is saved. * - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * * @param JournalCreated $event * * @return boolean diff --git a/app/Http/Controllers/BudgetController.php b/app/Http/Controllers/BudgetController.php index 00587db566..144cd44693 100644 --- a/app/Http/Controllers/BudgetController.php +++ b/app/Http/Controllers/BudgetController.php @@ -21,7 +21,6 @@ use View; * Class BudgetController * * @package FireflyIII\Http\Controllers - * @SuppressWarnings(PHPMD.TooManyMethods) */ class BudgetController extends Controller { diff --git a/app/Http/Controllers/PiggyBankController.php b/app/Http/Controllers/PiggyBankController.php index 6c33fccc8c..92ceb4cb88 100644 --- a/app/Http/Controllers/PiggyBankController.php +++ b/app/Http/Controllers/PiggyBankController.php @@ -18,7 +18,6 @@ use View; /** * - * @SuppressWarnings(PHPMD.TooManyMethods) * * Class PiggyBankController * diff --git a/app/Http/Middleware/Range.php b/app/Http/Middleware/Range.php index ac2017b182..27ef9622d5 100644 --- a/app/Http/Middleware/Range.php +++ b/app/Http/Middleware/Range.php @@ -42,7 +42,6 @@ class Range * * @param \Illuminate\Http\Request $request * @param \Closure $theNext - * @SuppressWarnings(PHPMD.CyclomaticComplexity) * * @return mixed */ diff --git a/app/Http/Requests/JournalFormRequest.php b/app/Http/Requests/JournalFormRequest.php index 141bb78f3e..b3377b4a47 100644 --- a/app/Http/Requests/JournalFormRequest.php +++ b/app/Http/Requests/JournalFormRequest.php @@ -51,7 +51,6 @@ class JournalFormRequest extends Request /** * @return array * @throws Exception - * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function rules() { diff --git a/app/Models/Account.php b/app/Models/Account.php index 683310dbfc..91f75cb286 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -50,7 +50,6 @@ class Account extends Model /** * @param array $fields - * @SuppressWarnings(PHPMD.CyclomaticComplexity) * * @return Account|null */ diff --git a/app/Models/Category.php b/app/Models/Category.php index fca9c789a9..4ddb31a7a7 100644 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -29,7 +29,6 @@ class Category extends Model /** * @param array $fields - * @SuppressWarnings(PHPMD.CyclomaticComplexity) * * @return Category */ diff --git a/app/Models/Tag.php b/app/Models/Tag.php index e1ffe69155..d1bd328143 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -44,8 +44,6 @@ class Tag extends Model /** * @param array $fields - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * @SuppressWarnings(PHPMD.NPathComplexity) * * @return Tag|null */ diff --git a/app/Providers/ConfigServiceProvider.php b/app/Providers/ConfigServiceProvider.php index 53d1e50b0b..7ee3b11047 100644 --- a/app/Providers/ConfigServiceProvider.php +++ b/app/Providers/ConfigServiceProvider.php @@ -19,7 +19,6 @@ class ConfigServiceProvider extends ServiceProvider * to overwrite any "vendor" or package configuration that you may want to * modify before the application handles the incoming request / command. * - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * * @return void */ diff --git a/app/Providers/FireflyServiceProvider.php b/app/Providers/FireflyServiceProvider.php index d04d6c2d9c..81df15ccac 100644 --- a/app/Providers/FireflyServiceProvider.php +++ b/app/Providers/FireflyServiceProvider.php @@ -47,7 +47,7 @@ class FireflyServiceProvider extends ServiceProvider } /** - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + * */ public function register() { diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 4e40f5bec8..f946ad464e 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -39,6 +39,8 @@ class RouteServiceProvider extends ServiceProvider * * @param \Illuminate\Routing\Router $router * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * * @return void */ public function map(Router $router) diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 10d2a1bab2..dd18c01265 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -24,7 +24,6 @@ use Steam; /** - * @SuppressWarnings(PHPMD.TooManyMethods) * * Class AccountRepository * @@ -609,7 +608,6 @@ class AccountRepository implements AccountRepositoryInterface * @param Account $account * @param array $data * - * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function updateMetadata(Account $account, array $data) { diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index 59832ff3e4..59085824ad 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -24,7 +24,6 @@ class TagRepository implements TagRepositoryInterface /** - * @SuppressWarnings(PHPMD.CyclomaticComplexity) // it's five. * * @param TransactionJournal $journal * @param Tag $tag @@ -33,7 +32,6 @@ class TagRepository implements TagRepositoryInterface */ public function connect(TransactionJournal $journal, Tag $tag) { - /* * Already connected: */ diff --git a/app/Support/ExpandedForm.php b/app/Support/ExpandedForm.php index 59e3db0fb5..d9153dc098 100644 --- a/app/Support/ExpandedForm.php +++ b/app/Support/ExpandedForm.php @@ -15,7 +15,6 @@ use Session; * * @package FireflyIII\Support * - * @SuppressWarnings(PHPMD.TooManyMethods) */ class ExpandedForm { diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index bf2a1c725a..4534c3f86b 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -24,7 +24,6 @@ class General extends Twig_Extension /** - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @return array */ public function getFilters() diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php index 1cd7aa0cf6..6d0d056296 100644 --- a/app/Validation/FireflyValidator.php +++ b/app/Validation/FireflyValidator.php @@ -28,7 +28,6 @@ class FireflyValidator extends Validator * @param array $rules * @param array $messages * @param array $customAttributes - * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct(TranslatorInterface $translator, array $data, array $rules, array $messages = [], array $customAttributes = []) { @@ -40,10 +39,12 @@ class FireflyValidator extends Validator * @param $value * @param $parameters * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * * @return bool */ - public function validateBelongsToUser($attribute, $value, $parameters) - { + public function validateBelongsToUser($attribute, $value, $parameters + ) { $count = DB::table($parameters[0])->where('user_id', Auth::user()->id)->where('id', $value)->count(); if ($count == 1) { @@ -58,6 +59,8 @@ class FireflyValidator extends Validator * @param $attribute * @param $value * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * * @return bool */ public function validateIban($attribute, $value) @@ -87,6 +90,8 @@ class FireflyValidator extends Validator * @param $value * @param $parameters * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * * @return bool */ public function validateUniqueAccountForUser($attribute, $value, $parameters) @@ -232,6 +237,8 @@ class FireflyValidator extends Validator * @param $value * @param $parameters * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * * @return bool */ public function validateUniqueForUser($attribute, $value, $parameters) @@ -261,6 +268,8 @@ class FireflyValidator extends Validator * @param $value * @param $parameters * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * * @return bool */ public function validateUniqueObjectForUser($attribute, $value, $parameters) @@ -291,6 +300,8 @@ class FireflyValidator extends Validator * @param $value * @param $parameters * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + * * @return bool */ public function validateUniquePiggyBankForUser($attribute, $value, $parameters) From 294df4a2b386f516d55e416bc845d6c3ada92ff6 Mon Sep 17 00:00:00 2001 From: James Cole Date: Sat, 2 Jan 2016 16:32:08 +0100 Subject: [PATCH 53/62] Simplified some code. --- .../ChartJsCategoryChartGenerator.php | 6 +- .../Controllers/Chart/CategoryController.php | 23 ++-- app/Http/Controllers/CronController.php | 92 ++++++++----- .../Category/CategoryRepository.php | 125 +++++------------- .../Category/CategoryRepositoryInterface.php | 10 -- 5 files changed, 106 insertions(+), 150 deletions(-) diff --git a/app/Generator/Chart/Category/ChartJsCategoryChartGenerator.php b/app/Generator/Chart/Category/ChartJsCategoryChartGenerator.php index 8a2ed404c0..8bb0402d25 100644 --- a/app/Generator/Chart/Category/ChartJsCategoryChartGenerator.php +++ b/app/Generator/Chart/Category/ChartJsCategoryChartGenerator.php @@ -100,9 +100,9 @@ class ChartJsCategoryChartGenerator implements CategoryChartGenerator ], ]; foreach ($entries as $entry) { - if ($entry['sum'] != 0) { - $data['labels'][] = $entry['name']; - $data['datasets'][0]['data'][] = round(($entry['sum'] * -1), 2); + if ($entry->spent != 0) { + $data['labels'][] = $entry->name; + $data['datasets'][0]['data'][] = round(($entry->spent * -1), 2); } } diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index d2adca7078..2314d61c74 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -14,6 +14,7 @@ use Navigation; use Preferences; use Response; use Session; +use stdClass; /** * Class CategoryController @@ -115,19 +116,17 @@ class CategoryController extends Controller return Response::json($cache->get()); // @codeCoverageIgnore } - $array = $repository->getCategoriesAndExpenses($start, $end); - // sort by callback: - uasort( - $array, - function ($left, $right) { - if ($left['sum'] == $right['sum']) { - return 0; - } + // get data for categories (and "no category"): + $set = $repository->spentForAccountsPerMonth(new Collection, $start, $end); + $outside = $repository->sumSpentNoCategory(new Collection, $start, $end); - return ($left['sum'] < $right['sum']) ? -1 : 1; - } - ); - $set = new Collection($array); + // this is a "fake" entry for the "no category" entry. + $entry = new stdClass(); + $entry->name = trans('firefly.no_category'); + $entry->spent = $outside; + $set->push($entry); + + $set = $set->sortBy('spent'); $data = $this->generator->frontpage($set); $cache->store($data); diff --git a/app/Http/Controllers/CronController.php b/app/Http/Controllers/CronController.php index a10531c1ae..a2ecd13e04 100644 --- a/app/Http/Controllers/CronController.php +++ b/app/Http/Controllers/CronController.php @@ -11,6 +11,34 @@ use FireflyIII\User; */ class CronController extends Controller { + /** @var array */ + protected $set = []; + + /** @var array */ + protected $parameters = []; + + + /** + * CronController constructor. + */ + public function __construct() + { + parent::__construct(); + $this->set = [ + 'blocks' => 'https://api.sendgrid.com/api/blocks.get.json', + 'bounces' => 'https://api.sendgrid.com/api/bounces.get.json', + 'invalids' => 'https://api.sendgrid.com/api/invalidemails.get.json', + + ]; + $this->parameters = [ + 'api_user' => env('SENDGRID_USERNAME'), + 'api_key' => env('SENDGRID_PASSWORD'), + 'date' => 1, + 'days' => 7 + ]; + + } + /** * Firefly doesn't have anything that should be in the a cron job, except maybe this one, and it's fairly exceptional. @@ -25,44 +53,11 @@ class CronController extends Controller if (strlen(env('SENDGRID_USERNAME')) > 0 && strlen(env('SENDGRID_PASSWORD')) > 0) { - $set = [ - 'blocks' => 'https://api.sendgrid.com/api/blocks.get.json', - 'bounces' => 'https://api.sendgrid.com/api/bounces.get.json', - 'invalids' => 'https://api.sendgrid.com/api/invalidemails.get.json', - - ]; echo '
';
-            foreach ($set as $name => $URL) {
+            foreach ($this->set as $name => $url) {
+                $data = json_decode(file_get_contents($url . '?' . http_build_query($this->parameters)));
+                $this->processResult($name, $data);
 
-
-                $parameters = [
-                    'api_user' => env('SENDGRID_USERNAME'),
-                    'api_key'  => env('SENDGRID_PASSWORD'),
-                    'date'     => 1,
-                    'days'     => 7
-                ];
-                $fullURL    = $URL . '?' . http_build_query($parameters);
-                $data       = json_decode(file_get_contents($fullURL));
-
-                /*
-                 * Loop the result, if any.
-                 */
-                if (is_array($data)) {
-                    echo 'Found ' . count($data) . ' entries in the SendGrid ' . $name . ' list.' . "\n";
-                    foreach ($data as $entry) {
-                        $address = $entry->email;
-                        $user    = User::where('email', $address)->where('blocked', 0)->first();
-                        if (!is_null($user)) {
-                            echo 'Found a user: ' . $address . ', who is now blocked.' . "\n";
-                            $user->blocked      = 1;
-                            $user->blocked_code = 'bounced';
-                            $user->password     = 'bounced';
-                            $user->save();
-                        } else {
-                            echo 'Found no user: ' . $address . ', did nothing.' . "\n";
-                        }
-                    }
-                }
             }
             echo 'Done!' . "\n";
         } else {
@@ -71,4 +66,29 @@ class CronController extends Controller
 
     }
 
+    /**
+     * @param string $name
+     * @param array  $data
+     */
+    protected function processResult($name, array $data)
+    {
+        if (is_array($data)) {
+            echo 'Found ' . count($data) . ' entries in the SendGrid ' . $name . ' list.' . "\n";
+            foreach ($data as $entry) {
+                $address = $entry->email;
+                $user    = User::where('email', $address)->where('blocked', 0)->first();
+                if (!is_null($user)) {
+                    echo 'Found a user: ' . $address . ', who is now blocked.' . "\n";
+                    $user->blocked      = 1;
+                    $user->blocked_code = 'bounced';
+                    $user->password     = 'bounced';
+                    $user->save();
+                } else {
+                    echo 'Found no user: ' . $address . ', did nothing.' . "\n";
+                }
+            }
+
+        }
+    }
+
 }
diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php
index bd5e0e83b8..534188bace 100644
--- a/app/Repositories/Category/CategoryRepository.php
+++ b/app/Repositories/Category/CategoryRepository.php
@@ -19,68 +19,6 @@ use Illuminate\Support\Collection;
 class CategoryRepository implements CategoryRepositoryInterface
 {
 
-    /**
-     * TODO REMOVE ME
-     *
-     * @param Carbon $start
-     * @param Carbon $end
-     *
-     * @return array
-     */
-    public function getCategoriesAndExpenses(Carbon $start, Carbon $end)
-    {
-        $set   = Auth::user()->categories()
-                     ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id')
-                     ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
-                     ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
-                     ->leftJoin(
-                         'transactions', function (JoinClause $join) {
-                         $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0);
-                     }
-                     )
-                     ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
-                     ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
-                     ->whereIn('transaction_types.type', [TransactionType::WITHDRAWAL])
-                     ->whereNull('transaction_journals.deleted_at')
-                     ->groupBy('categories.id')
-                     ->orderBy('totalAmount')
-                     ->get(
-                         [
-                             'categories.*',
-                             DB::Raw('SUM(`transactions`.`amount`) as `totalAmount`')
-                         ]
-                     );
-        $array = [];
-        /** @var Category $entry */
-        foreach ($set as $entry) {
-            $id         = $entry->id;
-            $array[$id] = ['name' => $entry->name, 'sum' => $entry->totalAmount];
-        }
-
-        // without category:
-        // TODO REMOVE ME
-        $single     = Auth::user()->transactionjournals()
-                          ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
-                          ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
-                          ->leftJoin(
-                              'transactions', function (JoinClause $join) {
-                              $join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0);
-                          }
-                          )
-                          ->whereNull('category_transaction_journal.id')
-                          ->whereNull('transaction_journals.deleted_at')
-                          ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
-                          ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
-                          ->whereIn('transaction_types.type', [TransactionType::WITHDRAWAL])
-                          ->whereNull('transaction_journals.deleted_at')
-                          ->first([DB::Raw('SUM(transactions.amount) as `totalAmount`')]);
-        $noCategory = is_null($single->totalAmount) ? '0' : $single->totalAmount;
-        $array[0]   = ['name' => trans('firefly.no_category'), 'sum' => $noCategory];
-
-        return $array;
-
-    }
-
     /**
      * Returns a list of all the categories belonging to a user.
      *
@@ -232,7 +170,7 @@ group by categories.id, transaction_types.type, dateFormatted
     /**
      * Returns a collection of Categories appended with the amount of money that has been spent
      * in these categories, based on the $accounts involved, in period X, grouped per month.
-     * The amount earned in category X in period X is saved in field "spent".
+     * The amount spent in category X in period X is saved in field "spent".
      *
      * @param $accounts
      * @param $start
@@ -243,7 +181,7 @@ group by categories.id, transaction_types.type, dateFormatted
     public function spentForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end)
     {
         $accountIds = $accounts->pluck('id')->toArray();
-        $collection = Auth::user()->categories()
+        $query      = Auth::user()->categories()
                           ->leftJoin('category_transaction_journal', 'category_transaction_journal.category_id', '=', 'categories.id')
                           ->leftJoin('transaction_journals', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
                           ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
@@ -257,22 +195,26 @@ group by categories.id, transaction_types.type, dateFormatted
                               $join->on('t_dest.transaction_journal_id', '=', 'transaction_journals.id')->where('t_dest.amount', '>', 0);
                           }
                           )
-                          ->whereIn('t_src.account_id', $accountIds)// from these accounts (spent)
-                          ->whereNotIn('t_dest.account_id', $accountIds)//-- but not from these accounts (spent internally)
                           ->whereIn(
-                'transaction_types.type', [TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]
-            )// spent on these things.
+                              'transaction_types.type', [TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::OPENING_BALANCE]
+                          )// spent on these things.
                           ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
                           ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
                           ->groupBy('categories.id')
-                          ->groupBy('dateFormatted')
-                          ->get(
-                              [
-                                  'categories.*',
-                                  DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") as `dateFormatted`'),
-                                  DB::Raw('SUM(`t_src`.`amount`) AS `spent`')
-                              ]
-                          );
+                          ->groupBy('dateFormatted');
+
+        if (count($accountIds) > 0) {
+            $query->whereIn('t_src.account_id', $accountIds)// from these accounts (spent)
+                  ->whereNotIn('t_dest.account_id', $accountIds);//-- but not from these accounts (spent internally)
+        }
+
+        $collection = $query->get(
+            [
+                'categories.*',
+                DB::Raw('DATE_FORMAT(`transaction_journals`.`date`,"%Y-%m") as `dateFormatted`'),
+                DB::Raw('SUM(`t_src`.`amount`) AS `spent`')
+            ]
+        );
 
         return $collection;
     }
@@ -329,19 +271,24 @@ group by categories.id, transaction_types.type, dateFormatted
         }
 
         // is withdrawal or transfer AND account_from is in the list of $accounts
-        $single = Auth::user()
-                      ->transactionjournals()
-                      ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
-                      ->whereNull('category_transaction_journal.id')
-                      ->before($end)
-                      ->after($start)
-                      ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
-                      ->whereIn('transactions.account_id', $accountIds)
-                      ->transactionTypes($types)
-                      ->first(
-                          [
-                              DB::Raw('SUM(`transactions`.`amount`) as `sum`)')]
-                      );
+        $query = Auth::user()
+                     ->transactionjournals()
+                     ->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
+                     ->whereNull('category_transaction_journal.id')
+                     ->before($end)
+                     ->after($start)
+                     ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
+                     ->transactionTypes($types);
+        if (count($accountIds) > 0) {
+            $query->whereIn('transactions.account_id', $accountIds);
+        }
+
+
+        $single = $query->first(
+            [
+                DB::Raw('SUM(`transactions`.`amount`) as `sum`')
+            ]
+        );
         if (!is_null($single)) {
             return $single->sum;
         }
diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php
index dd96800255..7de84fe660 100644
--- a/app/Repositories/Category/CategoryRepositoryInterface.php
+++ b/app/Repositories/Category/CategoryRepositoryInterface.php
@@ -27,16 +27,6 @@ interface CategoryRepositoryInterface
      */
     public function earnedForAccountsPerMonth(Collection $accounts, Carbon $start, Carbon $end);
 
-    /**
-     * Corrected for tags.
-     *
-     * @param Carbon $start
-     * @param Carbon $end
-     *
-     * @return array
-     */
-    public function getCategoriesAndExpenses(Carbon $start, Carbon $end);
-
     /**
      * Returns a list of all the categories belonging to a user.
      *

From 3888b8cceb2c315b0a4261d964ce2e32974b33f1 Mon Sep 17 00:00:00 2001
From: James Cole 
Date: Sat, 2 Jan 2016 16:57:31 +0100
Subject: [PATCH 54/62] Code cleanup according to PHPStorm.

---
 .../Chart/Bill/ChartJsBillChartGenerator.php  |  11 +-
 .../Budget/ChartJsBudgetChartGenerator.php    |  20 +-
 app/Http/Controllers/AccountController.php    |  37 ++--
 .../Controllers/Chart/ReportController.php    | 180 ++++++++++++------
 .../Account/AccountRepositoryInterface.php    |   2 +-
 app/Support/Steam.php                         |   2 +-
 app/Validation/FireflyValidator.php           |   4 +-
 7 files changed, 157 insertions(+), 99 deletions(-)

diff --git a/app/Generator/Chart/Bill/ChartJsBillChartGenerator.php b/app/Generator/Chart/Bill/ChartJsBillChartGenerator.php
index 52f3b540e7..879a1f8d84 100644
--- a/app/Generator/Chart/Bill/ChartJsBillChartGenerator.php
+++ b/app/Generator/Chart/Bill/ChartJsBillChartGenerator.php
@@ -49,19 +49,12 @@ class ChartJsBillChartGenerator implements BillChartGenerator
      */
     public function single(Bill $bill, Collection $entries)
     {
-        // language:
-        $format = trans('config.month');
-
-        $data = [
+        $format       = trans('config.month');
+        $data         = [
             'count'    => 3,
             'labels'   => [],
             'datasets' => [],
         ];
-
-        // dataset: max amount
-        // dataset: min amount
-        // dataset: actual amount
-
         $minAmount    = [];
         $maxAmount    = [];
         $actualAmount = [];
diff --git a/app/Generator/Chart/Budget/ChartJsBudgetChartGenerator.php b/app/Generator/Chart/Budget/ChartJsBudgetChartGenerator.php
index 6af66916ff..77678b93e9 100644
--- a/app/Generator/Chart/Budget/ChartJsBudgetChartGenerator.php
+++ b/app/Generator/Chart/Budget/ChartJsBudgetChartGenerator.php
@@ -68,24 +68,24 @@ class ChartJsBudgetChartGenerator implements BudgetChartGenerator
      */
     public function frontpage(Collection $entries)
     {
-        $data = [
+        $data      = [
             'count'    => 0,
             'labels'   => [],
             'datasets' => [],
         ];
-        // dataset: left
-        // dataset: spent
-        // dataset: overspent
         $left      = [];
         $spent     = [];
         $overspent = [];
-        foreach ($entries as $entry) {
-            if ($entry[1] != 0 || $entry[2] != 0 || $entry[3] != 0) {
-                $data['labels'][] = $entry[0];
-                $left[]           = round($entry[1], 2);
-                $spent[]          = round($entry[2] * -1, 2); // spent is coming in negative, must be positive
-                $overspent[]      = round($entry[3] * -1, 2); // same
+        $filtered  = $entries->filter(
+            function ($entry) {
+                return ($entry[1] != 0 || $entry[2] != 0 || $entry[3] != 0);
             }
+        );
+        foreach ($filtered as $entry) {
+            $data['labels'][] = $entry[0];
+            $left[]           = round($entry[1], 2);
+            $spent[]          = round($entry[2] * -1, 2); // spent is coming in negative, must be positive
+            $overspent[]      = round($entry[3] * -1, 2); // same
         }
 
         $data['datasets'][] = [
diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php
index 44f7e7e396..e018002bfc 100644
--- a/app/Http/Controllers/AccountController.php
+++ b/app/Http/Controllers/AccountController.php
@@ -154,29 +154,20 @@ class AccountController extends Controller
         $subTitleIcon = Config::get('firefly.subIconsByIdentifier.' . $what);
         $types        = Config::get('firefly.accountTypesByIdentifier.' . $what);
         $accounts     = $repository->getAccounts($types);
-        // last activity:
-        /**
-         * HERE WE ARE
-         */
-        $start = clone Session::get('start', Carbon::now()->startOfMonth());
-        $end   = clone Session::get('end', Carbon::now()->endOfMonth());
+        $start        = clone Session::get('start', Carbon::now()->startOfMonth());
+        $end          = clone Session::get('end', Carbon::now()->endOfMonth());
         $start->subDay();
 
-        // start balances:
-        $ids = [];
-        foreach ($accounts as $account) {
-            $ids[] = $account->id;
-        }
-
+        $ids           = $accounts->pluck('id')->toArray();
         $startBalances = Steam::balancesById($ids, $start);
         $endBalances   = Steam::balancesById($ids, $end);
         $activities    = Steam::getLastActivities($ids);
 
         $accounts->each(
             function (Account $account) use ($activities, $startBalances, $endBalances) {
-                $account->lastActivityDate = isset($activities[$account->id]) ? $activities[$account->id] : null;
-                $account->startBalance     = isset($startBalances[$account->id]) ? $startBalances[$account->id] : null;
-                $account->endBalance       = isset($endBalances[$account->id]) ? $endBalances[$account->id] : null;
+                $account->lastActivityDate = $this->isInArray($activities, $account->id);
+                $account->startBalance     = $this->isInArray($startBalances, $account->id);
+                $account->endBalance       = $this->isInArray($endBalances, $account->id);
             }
         );
 
@@ -283,4 +274,20 @@ class AccountController extends Controller
 
     }
 
+
+    /**
+     * @param array $array
+     * @param       $entryId
+     *
+     * @return null|mixed
+     */
+    protected function isInArray(array $array, $entryId)
+    {
+        if (isset($array[$entryId])) {
+            return $array[$entryId];
+        }
+
+        return null;
+    }
+
 }
diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php
index 1c2a68651a..545fe46d7a 100644
--- a/app/Http/Controllers/Chart/ReportController.php
+++ b/app/Http/Controllers/Chart/ReportController.php
@@ -61,38 +61,16 @@ class ReportController extends Controller
         $spentArray  = $query->spentPerMonth($accounts, $start, $end);
         $earnedArray = $query->earnedPerMonth($accounts, $start, $end);
 
-        // per year? put all months together.
         if ($start->diffInMonths($end) > 12) {
-            $entries = new Collection;
-            while ($start < $end) {
-
-                $incomeSum  = $this->pluckFromArray($start->year, $earnedArray);
-                $expenseSum = $this->pluckFromArray($start->year, $spentArray) * -1;
-
-                $entries->push([clone $start, $incomeSum, $expenseSum]);
-                $start->addYear();
-            }
-
-            $data = $this->generator->multiYearInOut($entries);
-            $cache->store($data);
+            // data = method X
+            $data = $this->multiYearInOut($earnedArray, $spentArray, $start, $end);
         } else {
-            // per month? simply use each month.
-
-            $entries = new Collection;
-            while ($start < $end) {
-                // total income and total expenses:
-                $date       = $start->format('Y-m');
-                $incomeSum  = isset($earnedArray[$date]) ? $earnedArray[$date] : 0;
-                $expenseSum = isset($spentArray[$date]) ? ($spentArray[$date] * -1) : 0;
-
-                $entries->push([clone $start, $incomeSum, $expenseSum]);
-                $start->addMonth();
-            }
-
-            $data = $this->generator->yearInOut($entries);
-            $cache->store($data);
+            // data = method Y
+            $data = $this->singleYearInOut($earnedArray, $spentArray, $start, $end);
         }
 
+        $cache->store($data);
+
         return Response::json($data);
 
     }
@@ -125,47 +103,127 @@ class ReportController extends Controller
         // grouped by month
         $spentArray  = $query->spentPerMonth($accounts, $start, $end);
         $earnedArray = $query->earnedPerMonth($accounts, $start, $end);
-        $income      = '0';
-        $expense     = '0';
-        $count       = 0;
-
-        bcscale(2);
-
         if ($start->diffInMonths($end) > 12) {
             // per year
-            while ($start < $end) {
-
-                $currentIncome  = $this->pluckFromArray($start->year, $earnedArray);
-                $currentExpense = $this->pluckFromArray($start->year, $spentArray) * -1;
-                $income         = bcadd($income, $currentIncome);
-                $expense        = bcadd($expense, $currentExpense);
-
-                $count++;
-                $start->addYear();
-            }
-
-            $data = $this->generator->multiYearInOutSummarized($income, $expense, $count);
-            $cache->store($data);
+            $data = $this->multiYearInOutSummarized($earnedArray, $spentArray, $start, $end);
         } else {
             // per month!
-            while ($start < $end) {
-                $date           = $start->format('Y-m');
-                $currentIncome  = isset($earnedArray[$date]) ? $earnedArray[$date] : 0;
-                $currentExpense = isset($spentArray[$date]) ? ($spentArray[$date] * -1) : 0;
-                $income         = bcadd($income, $currentIncome);
-                $expense        = bcadd($expense, $currentExpense);
-
-                $count++;
-                $start->addMonth();
-            }
-
-            $data = $this->generator->yearInOutSummarized($income, $expense, $count);
-            $cache->store($data);
+            $data = $this->singleYearInOutSummarized($earnedArray, $spentArray, $start, $end);
         }
-
+        $cache->store($data);
 
         return Response::json($data);
+    }
 
+    /**
+     * @param array  $earned
+     * @param array  $spent
+     * @param Carbon $start
+     * @param Carbon $end
+     *
+     * @return array
+     */
+    protected function singleYearInOutSummarized(array $earned, array $spent, Carbon $start, Carbon $end)
+    {
+        $income  = '0';
+        $expense = '0';
+        $count   = 0;
+        while ($start < $end) {
+            $date           = $start->format('Y-m');
+            $currentIncome  = isset($earned[$date]) ? $earned[$date] : 0;
+            $currentExpense = isset($spent[$date]) ? ($spent[$date] * -1) : 0;
+            $income         = bcadd($income, $currentIncome);
+            $expense        = bcadd($expense, $currentExpense);
+
+            $count++;
+            $start->addMonth();
+        }
+
+        $data = $this->generator->yearInOutSummarized($income, $expense, $count);
+
+        return $data;
+    }
+
+    /**
+     * @param array  $earned
+     * @param array  $spent
+     * @param Carbon $start
+     * @param Carbon $end
+     *
+     * @return array
+     */
+    protected function multiYearInOutSummarized(array $earned, array $spent, Carbon $start, Carbon $end)
+    {
+        $income  = '0';
+        $expense = '0';
+        $count   = 0;
+        while ($start < $end) {
+
+            $currentIncome  = $this->pluckFromArray($start->year, $earned);
+            $currentExpense = $this->pluckFromArray($start->year, $spent) * -1;
+            $income         = bcadd($income, $currentIncome);
+            $expense        = bcadd($expense, $currentExpense);
+
+            $count++;
+            $start->addYear();
+        }
+
+        $data = $this->generator->multiYearInOutSummarized($income, $expense, $count);
+
+        return $data;
+    }
+
+    /**
+     * @param array  $earned
+     * @param array  $spent
+     * @param Carbon $start
+     * @param Carbon $end
+     *
+     * @return array
+     */
+    protected function multiYearInOut(array $earned, array $spent, Carbon $start, Carbon $end)
+    {
+        $entries = new Collection;
+        while ($start < $end) {
+
+            $incomeSum  = $this->pluckFromArray($start->year, $earned);
+            $expenseSum = $this->pluckFromArray($start->year, $spent) * -1;
+
+            $entries->push([clone $start, $incomeSum, $expenseSum]);
+            $start->addYear();
+        }
+
+        $data = $this->generator->multiYearInOut($entries);
+
+        return $data;
+    }
+
+    /**
+     * @param array  $earned
+     * @param array  $spent
+     * @param Carbon $start
+     * @param Carbon $end
+     *
+     * @return array
+     */
+    protected function singleYearInOut(array $earned, array $spent, Carbon $start, Carbon $end)
+    {
+        // per month? simply use each month.
+
+        $entries = new Collection;
+        while ($start < $end) {
+            // total income and total expenses:
+            $date       = $start->format('Y-m');
+            $incomeSum  = isset($earned[$date]) ? $earned[$date] : 0;
+            $expenseSum = isset($spent[$date]) ? ($spent[$date] * -1) : 0;
+
+            $entries->push([clone $start, $incomeSum, $expenseSum]);
+            $start->addMonth();
+        }
+
+        $data = $this->generator->yearInOut($entries);
+
+        return $data;
     }
 
     /**
diff --git a/app/Repositories/Account/AccountRepositoryInterface.php b/app/Repositories/Account/AccountRepositoryInterface.php
index d03cf070e6..b18ffb2807 100644
--- a/app/Repositories/Account/AccountRepositoryInterface.php
+++ b/app/Repositories/Account/AccountRepositoryInterface.php
@@ -44,7 +44,7 @@ interface AccountRepositoryInterface
     /**
      * @param array $types
      *
-     * @return mixed
+     * @return Collection
      */
     public function getAccounts(array $types);
 
diff --git a/app/Support/Steam.php b/app/Support/Steam.php
index 4a2a733355..216d5528e4 100644
--- a/app/Support/Steam.php
+++ b/app/Support/Steam.php
@@ -127,7 +127,7 @@ class Steam
      * @param array          $ids
      * @param \Carbon\Carbon $date
      *
-     * @return float
+     * @return array
      */
     public function balancesById(array $ids, Carbon $date)
     {
diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php
index 6d0d056296..1503518a1d 100644
--- a/app/Validation/FireflyValidator.php
+++ b/app/Validation/FireflyValidator.php
@@ -43,8 +43,8 @@ class FireflyValidator extends Validator
      *
      * @return bool
      */
-    public function validateBelongsToUser($attribute, $value, $parameters
-    ) {
+    public function validateBelongsToUser($attribute, $value, $parameters)
+    {
 
         $count = DB::table($parameters[0])->where('user_id', Auth::user()->id)->where('id', $value)->count();
         if ($count == 1) {

From 9dc3f614affdc2b68ad151c4cbd34dde1ff1aff8 Mon Sep 17 00:00:00 2001
From: James Cole 
Date: Sat, 2 Jan 2016 16:59:36 +0100
Subject: [PATCH 55/62] Localised date

---
 resources/twig/list/journals-tiny.twig | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/resources/twig/list/journals-tiny.twig b/resources/twig/list/journals-tiny.twig
index 4265f62298..ca488f91fa 100644
--- a/resources/twig/list/journals-tiny.twig
+++ b/resources/twig/list/journals-tiny.twig
@@ -1,7 +1,7 @@
 
{% for journal in transactions %} - + {{ journal|typeIcon }} From 6573bd6b4bbca59dce9e016da4fa4fde4191904d Mon Sep 17 00:00:00 2001 From: James Cole Date: Sat, 2 Jan 2016 19:33:44 +0100 Subject: [PATCH 56/62] Code cleanup according to PHPStorm. --- app/Http/Controllers/Auth/AuthController.php | 24 +----- .../Controllers/TransactionController.php | 7 +- .../Account/AccountRepository.php | 73 ------------------- app/Repositories/Bill/BillRepository.php | 35 --------- app/Repositories/Budget/BudgetRepository.php | 24 ------ .../Journal/JournalRepository.php | 8 -- .../Shared/ComponentRepository.php | 15 ---- app/Repositories/Tag/TagRepository.php | 10 --- 8 files changed, 3 insertions(+), 193 deletions(-) diff --git a/app/Http/Controllers/Auth/AuthController.php b/app/Http/Controllers/Auth/AuthController.php index ab6e06a35e..c4f5ba4f9b 100644 --- a/app/Http/Controllers/Auth/AuthController.php +++ b/app/Http/Controllers/Auth/AuthController.php @@ -58,15 +58,7 @@ class AuthController extends Controller */ public function postLogin(Request $request) { - $this->validate( - $request, [ - $this->loginUsername() => 'required', 'password' => 'required', - ] - ); - - // If the class is using the ThrottlesLogins trait, we can automatically throttle - // the login attempts for this application. We'll key this by the username and - // the IP address of the client making these requests into this application. + $this->validate($request, [$this->loginUsername() => 'required', 'password' => 'required',]); $throttles = $this->isUsingThrottlesLoginsTrait(); if ($throttles && $this->hasTooManyLoginAttempts($request)) { @@ -80,10 +72,7 @@ class AuthController extends Controller return $this->handleUserWasAuthenticated($request, $throttles); } - // default error message: $message = $this->getFailedLoginMessage(); - - // try to find a blocked user with this email address. /** @var User $foundUser */ $foundUser = User::where('email', $credentials['email'])->where('blocked', 1)->first(); if (!is_null($foundUser)) { @@ -95,22 +84,13 @@ class AuthController extends Controller $message = trans('firefly.' . $code . '_error', ['email' => $credentials['email']]); } - // try - - // If the login attempt was unsuccessful we will increment the number of attempts - // to login and redirect the user back to the login form. Of course, when this - // user surpasses their maximum number of attempts they will get locked out. if ($throttles) { $this->incrementLoginAttempts($request); } return redirect($this->loginPath()) ->withInput($request->only($this->loginUsername(), 'remember')) - ->withErrors( - [ - $this->loginUsername() => $message, - ] - ); + ->withErrors([$this->loginUsername() => $message,]); } diff --git a/app/Http/Controllers/TransactionController.php b/app/Http/Controllers/TransactionController.php index 60712a986e..54e9b5fc2b 100644 --- a/app/Http/Controllers/TransactionController.php +++ b/app/Http/Controllers/TransactionController.php @@ -163,11 +163,7 @@ class TransactionController extends Controller 'piggy_bank_id' => 0 ]; // get tags: - $tags = []; - foreach ($journal->tags as $tag) { - $tags[] = $tag->tag; - } - $preFilled['tags'] = join(',', $tags); + $preFilled['tags'] = join(',', $journal->tags->pluck('tag')->toArray()); $category = $journal->categories()->first(); if (!is_null($category)) { @@ -354,7 +350,6 @@ class TransactionController extends Controller public function update(JournalFormRequest $request, JournalRepositoryInterface $repository, AttachmentHelperInterface $att, TransactionJournal $journal) { - // cannot edit opening balance if ($journal->isOpeningBalance()) { return view('error')->with('message', 'Cannot edit this transaction. Edit the account instead!'); } diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index dd18c01265..a034e4534f 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -14,7 +14,6 @@ use FireflyIII\Models\Preference; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; -use FireflyIII\Support\CacheProperties; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; @@ -39,14 +38,7 @@ class AccountRepository implements AccountRepositoryInterface */ public function countAccounts(array $types) { - $cache = new CacheProperties; - $cache->addProperty('user-count-accounts'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $count = Auth::user()->accounts()->accountTypeIn($types)->count(); - $cache->store($count); return $count; } @@ -76,14 +68,6 @@ class AccountRepository implements AccountRepositoryInterface */ public function getAccounts(array $types) { - $cache = new CacheProperties(); - $cache->addProperty('get-accounts'); - $cache->addProperty($types); - - if ($cache->has()) { - return $cache->get(); - } - /** @var Collection $result */ $result = Auth::user()->accounts()->with( ['accountmeta' => function (HasMany $query) { @@ -96,9 +80,6 @@ class AccountRepository implements AccountRepositoryInterface return strtolower($account->name); } ); - - $cache->store($result); - return $result; } @@ -116,12 +97,6 @@ class AccountRepository implements AccountRepositoryInterface */ public function getCreditCards(Carbon $date) { - $cache = new CacheProperties(); - $cache->addProperty('user-credit-cards'); - if ($cache->has()) { - return $cache->get(); - } - $set = Auth::user()->accounts() ->hasMetaValue('accountRole', 'ccAsset') ->hasMetaValue('ccType', 'monthlyFull') @@ -138,8 +113,6 @@ class AccountRepository implements AccountRepositoryInterface DB::Raw('SUM(`transactions`.`amount`) AS `balance`') ] ); - $cache->store($set); - return $set; } @@ -151,16 +124,7 @@ class AccountRepository implements AccountRepositoryInterface */ public function getFirstTransaction(TransactionJournal $journal, Account $account) { - $cache = new CacheProperties(); - $cache->addProperty('first-transaction'); - $cache->addProperty($journal->id); - $cache->addProperty($account->id); - - if ($cache->has()) { - return $cache->get(); - } $transaction = $journal->transactions()->where('account_id', $account->id)->first(); - $cache->store($transaction); return $transaction; } @@ -172,11 +136,6 @@ class AccountRepository implements AccountRepositoryInterface */ public function getFrontpageAccounts(Preference $preference) { - $cache = new CacheProperties(); - $cache->addProperty('user-frontpage-accounts'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } $query = Auth::user()->accounts()->accountTypeIn(['Default account', 'Asset account']); if (count($preference->data) > 0) { @@ -184,9 +143,6 @@ class AccountRepository implements AccountRepositoryInterface } $result = $query->get(['accounts.*']); - - $cache->store($result); - return $result; } @@ -203,15 +159,6 @@ class AccountRepository implements AccountRepositoryInterface */ public function getFrontpageTransactions(Account $account, Carbon $start, Carbon $end) { - $cache = new CacheProperties(); - $cache->addProperty($account->id); - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty('frontpage-transactions'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $set = Auth::user() ->transactionjournals() ->with(['transactions']) @@ -226,8 +173,6 @@ class AccountRepository implements AccountRepositoryInterface ->orderBy('transaction_journals.id', 'DESC') ->take(10) ->get(['transaction_journals.*', 'transaction_currencies.symbol', 'transaction_types.type']); - $cache->store($set); - return $set; } @@ -271,13 +216,6 @@ class AccountRepository implements AccountRepositoryInterface $ids = $collection->pluck('account_id')->toArray(); $accounts = new Collection; - $cache = new CacheProperties; - $cache->addProperty($ids); - $cache->addProperty('user-piggy-bank-accounts'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $ids = array_unique($ids); if (count($ids) > 0) { $accounts = Auth::user()->accounts()->whereIn('id', $ids)->where('accounts.active', 1)->get(); @@ -303,8 +241,6 @@ class AccountRepository implements AccountRepositoryInterface } ); - $cache->store($accounts); - return $accounts; } @@ -381,21 +317,12 @@ class AccountRepository implements AccountRepositoryInterface */ public function openingBalanceTransaction(Account $account) { - $cache = new CacheProperties; - $cache->addProperty($account->id); - $cache->addProperty('opening-balance-journal'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - - $journal = TransactionJournal ::orderBy('transaction_journals.date', 'ASC') ->accountIs($account) ->transactionTypes([TransactionType::OPENING_BALANCE]) ->orderBy('created_at', 'ASC') ->first(['transaction_journals.*']); - $cache->store($journal); return $journal; } diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index 54bba39d9f..b07a37f45a 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -10,7 +10,6 @@ use FireflyIII\Models\Bill; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Support\CacheProperties; use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; @@ -136,13 +135,6 @@ class BillRepository implements BillRepositoryInterface */ public function getJournals(Bill $bill) { - $cache = new CacheProperties; - $cache->addProperty($bill->id); - $cache->addProperty('journals-for-bill'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $set = $bill->transactionjournals() ->leftJoin( 'transactions', function (JoinClause $join) { @@ -154,8 +146,6 @@ class BillRepository implements BillRepositoryInterface ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->get(['transaction_journals.*', 'transactions.amount as journalAmount']); - $cache->store($set); - return $set; } @@ -450,13 +440,6 @@ class BillRepository implements BillRepositoryInterface */ public function getBillsPaidInRange(Carbon $start, Carbon $end) { - $cache = new CacheProperties; - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty('bills-paid-in-range'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } $amount = '0'; $bills = $this->getActiveBills(); @@ -477,8 +460,6 @@ class BillRepository implements BillRepositoryInterface $amount = bcadd($amount, $paid->sum_amount); } } - $cache->store($amount); - return $amount; } @@ -511,13 +492,6 @@ class BillRepository implements BillRepositoryInterface */ public function getBillsUnpaidInRange(Carbon $start, Carbon $end) { - $cache = new CacheProperties; - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty('bills-unpaid-in-range'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } $amount = '0'; $bills = $this->getActiveBills(); @@ -541,8 +515,6 @@ class BillRepository implements BillRepositoryInterface $amount = bcadd($amount, $bill->expectedAmount); } } - $cache->store($amount); - return $amount; } @@ -558,13 +530,6 @@ class BillRepository implements BillRepositoryInterface public function getCreditCardBill(Carbon $start, Carbon $end) { - $cache = new CacheProperties; - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty('credit-card-bill'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } /** @var AccountRepositoryInterface $accountRepository */ $accountRepository = app('FireflyIII\Repositories\Account\AccountRepositoryInterface'); $amount = '0'; diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 85ec767e52..2750dcfe6a 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -10,7 +10,6 @@ use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\LimitRepetition; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Shared\ComponentRepository; -use FireflyIII\Support\CacheProperties; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Query\JoinClause; @@ -262,21 +261,10 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn */ public function getCurrentRepetition(Budget $budget, Carbon $start, Carbon $end) { - $cache = new CacheProperties; - $cache->addProperty($budget->id); - $cache->addProperty($start); - $cache->addProperty($end); - - $cache->addProperty('getCurrentRepetition'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } $data = $budget->limitrepetitions() ->where('limit_repetitions.startdate', $start->format('Y-m-d 00:00:00')) ->where('limit_repetitions.enddate', $end->format('Y-m-d 00:00:00')) ->first(['limit_repetitions.*']); - $cache->store($data); - return $data; } @@ -381,17 +369,6 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn */ public function getJournals(Budget $budget, LimitRepetition $repetition = null, $take = 50) { - $cache = new CacheProperties; - $cache->addProperty($budget->id); - if ($repetition) { - $cache->addProperty($repetition->id); - } - $cache->addProperty($take); - $cache->addProperty('getJournals'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $offset = intval(Input::get('page')) > 0 ? intval(Input::get('page')) * $take : 0; $setQuery = $budget->transactionJournals()->withRelevantData()->take($take)->offset($offset) ->orderBy('transaction_journals.date', 'DESC') @@ -411,7 +388,6 @@ class BudgetRepository extends ComponentRepository implements BudgetRepositoryIn $paginator = new LengthAwarePaginator($set, $count, $take, $offset); - $cache->store($paginator); return $paginator; } diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php index 061d9c39a3..c3d4d08c5e 100644 --- a/app/Repositories/Journal/JournalRepository.php +++ b/app/Repositories/Journal/JournalRepository.php @@ -13,7 +13,6 @@ use FireflyIII\Models\Tag; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; -use FireflyIII\Support\CacheProperties; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; use Log; @@ -45,14 +44,7 @@ class JournalRepository implements JournalRepositoryInterface */ public function first() { - $cache = new CacheProperties; - $cache->addProperty('user-first-journal'); - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $entry = Auth::user()->transactionjournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']); - $cache->store($entry); return $entry; } diff --git a/app/Repositories/Shared/ComponentRepository.php b/app/Repositories/Shared/ComponentRepository.php index 7c976e8784..aa604b2859 100644 --- a/app/Repositories/Shared/ComponentRepository.php +++ b/app/Repositories/Shared/ComponentRepository.php @@ -5,7 +5,6 @@ namespace FireflyIII\Repositories\Shared; use Carbon\Carbon; use DB; use FireflyIII\Models\TransactionType; -use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; /** @@ -26,18 +25,6 @@ class ComponentRepository */ protected function commonBalanceInPeriod($object, Carbon $start, Carbon $end, Collection $accounts) { - $cache = new CacheProperties; // we must cache this. - $cache->addProperty($object->id); - $cache->addProperty(get_class($object)); - $cache->addProperty($start); - $cache->addProperty($end); - $cache->addProperty($accounts); - $cache->addProperty('balanceInPeriodList'); - - if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore - } - $ids = $accounts->pluck('id')->toArray(); @@ -51,8 +38,6 @@ class ComponentRepository ->first([DB::Raw('SUM(`transactions`.`amount`) as `journalAmount`')]); $amount = $entry->journalAmount; - $cache->store($amount); - return $amount; } } diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index 59085824ad..ccdb2d9dae 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -10,7 +10,6 @@ use FireflyIII\Models\Account; use FireflyIII\Models\Tag; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; -use FireflyIII\Support\CacheProperties; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; @@ -155,13 +154,6 @@ class TagRepository implements TagRepositoryInterface */ public function get() { - $cache = new CacheProperties; - $cache->addProperty('tags-list'); - - if ($cache->has()) { - return $cache->get(); - } - /** @var Collection $tags */ $tags = Auth::user()->tags()->get(); $tags = $tags->sortBy( @@ -170,8 +162,6 @@ class TagRepository implements TagRepositoryInterface } ); - $cache->store($tags); - return $tags; } From 9ff6f8fc524a4462da109ec74e196b46f90f12a7 Mon Sep 17 00:00:00 2001 From: leander091 Date: Sun, 3 Jan 2016 15:52:12 +0100 Subject: [PATCH 57/62] String is a reserved class name in php7 changed to Str according to the upstream project --- config/twigbridge.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/twigbridge.php b/config/twigbridge.php index 04826b5504..c4e6d2c4ba 100644 --- a/config/twigbridge.php +++ b/config/twigbridge.php @@ -94,7 +94,7 @@ return [ 'TwigBridge\Extension\Laravel\Dump', 'TwigBridge\Extension\Laravel\Input', 'TwigBridge\Extension\Laravel\Session', - 'TwigBridge\Extension\Laravel\String', + 'TwigBridge\Extension\Laravel\Str', 'TwigBridge\Extension\Laravel\Translator', 'TwigBridge\Extension\Laravel\Url', From 8526907f50d9581360a87510ba24c6619e17b701 Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 5 Jan 2016 21:23:58 +0100 Subject: [PATCH 58/62] Expand multi-year report. --- app/Http/Controllers/ReportController.php | 16 ++++-- public/js/reports/default/multi-year.js | 49 +++++++++++++++++++ .../twig/reports/default/multi-year.twig | 26 ++++++++++ 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index 874b254664..59f4f112b4 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -163,10 +163,14 @@ class ReportController extends Controller public function defaultMultiYear($reportType, $start, $end, $accounts) { - + $incomeTopLength = 8; + $expenseTopLength = 8; // list of users stuff: - $budgets = app('FireflyIII\Repositories\Budget\BudgetRepositoryInterface')->getActiveBudgets(); - $categories = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface')->listCategories(); + $budgets = app('FireflyIII\Repositories\Budget\BudgetRepositoryInterface')->getActiveBudgets(); + $categories = app('FireflyIII\Repositories\Category\CategoryRepositoryInterface')->listCategories(); + $accountReport = $this->helper->getAccountReport($start, $end, $accounts); // done (+2) + $incomes = $this->helper->getIncomeReport($start, $end, $accounts); // done (+3) + $expenses = $this->helper->getExpenseReport($start, $end, $accounts); // done (+1) // and some id's, joined: $accountIds = []; @@ -177,7 +181,11 @@ class ReportController extends Controller $accountIds = join(',', $accountIds); return view( - 'reports.default.multi-year', compact('budgets', 'accounts', 'categories', 'start', 'end', 'accountIds', 'reportType') + 'reports.default.multi-year', + compact( + 'budgets', 'accounts', 'categories', 'start', 'end', 'accountIds', 'reportType', 'accountReport', 'incomes', 'expenses', + 'incomeTopLength', 'expenseTopLength' + ) ); } diff --git a/public/js/reports/default/multi-year.js b/public/js/reports/default/multi-year.js index d43475f6c1..61931c1d78 100644 --- a/public/js/reports/default/multi-year.js +++ b/public/js/reports/default/multi-year.js @@ -5,6 +5,11 @@ $(function () { "use strict"; drawChart(); + // click open the top X income list: + $('#showIncomes').click(showIncomes); + // click open the top X expense list: + $('#showExpenses').click(showExpenses); + }); @@ -152,4 +157,48 @@ function readCookie(name) { function eraseCookie(name) { createCookie(name, "", -1); +} + + + +function showIncomes() { + "use strict"; + if (incomeRestShow) { + // hide everything, make button say "show" + $('#showIncomes').text(showTheRest); + $('.incomesCollapsed').removeClass('in').addClass('out'); + + // toggle: + incomeRestShow = false; + } else { + // show everything, make button say "hide". + $('#showIncomes').text(hideTheRest); + $('.incomesCollapsed').removeClass('out').addClass('in'); + + // toggle: + incomeRestShow = true; + } + + return false; +} + +function showExpenses() { + "use strict"; + if (expenseRestShow) { + // hide everything, make button say "show" + $('#showExpenses').text(showTheRestExpense); + $('.expenseCollapsed').removeClass('in').addClass('out'); + + // toggle: + expenseRestShow = false; + } else { + // show everything, make button say "hide". + $('#showExpenses').text(hideTheRestExpense); + $('.expenseCollapsed').removeClass('out').addClass('in'); + + // toggle: + expenseRestShow = true; + } + + return false; } \ No newline at end of file diff --git a/resources/twig/reports/default/multi-year.twig b/resources/twig/reports/default/multi-year.twig index 1d1334b1b9..bb18c3abb4 100644 --- a/resources/twig/reports/default/multi-year.twig +++ b/resources/twig/reports/default/multi-year.twig @@ -29,6 +29,22 @@
+ +
+
+ {% include 'reports/partials/accounts.twig' %} + {% include 'reports/partials/income-vs-expenses.twig' %} +
+
+ + {% include 'reports/partials/income.twig' %} +
+
+ + {% include 'reports/partials/expenses.twig' %} +
+
+ {% for account in accounts %}