Files
firefly-iii/app/Repositories/Budget/BudgetRepository.php

667 lines
22 KiB
PHP
Raw Normal View History

2015-02-22 09:46:21 +01:00
<?php
namespace FireflyIII\Repositories\Budget;
2015-04-05 10:36:28 +02:00
use Auth;
2015-02-22 09:46:21 +01:00
use Carbon\Carbon;
2015-12-27 21:17:04 +01:00
use DB;
use FireflyIII\Models\Account;
2015-02-22 09:46:21 +01:00
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\LimitRepetition;
use FireflyIII\Models\TransactionType;
2015-06-05 10:02:40 +02:00
use FireflyIII\Repositories\Shared\ComponentRepository;
2015-06-05 19:02:23 +02:00
use FireflyIII\Support\CacheProperties;
2015-12-27 21:17:04 +01:00
use Illuminate\Database\Eloquent\Builder;
2015-04-07 17:51:22 +02:00
use Illuminate\Database\Query\Builder as QueryBuilder;
2015-12-27 21:17:04 +01:00
use Illuminate\Database\Query\JoinClause;
2015-02-22 15:40:13 +01:00
use Illuminate\Pagination\LengthAwarePaginator;
2015-04-05 10:36:28 +02:00
use Illuminate\Support\Collection;
2015-05-08 14:00:49 +02:00
use Input;
2015-02-22 09:46:21 +01:00
/**
* Class BudgetRepository
*
* @package FireflyIII\Repositories\Budget
*/
2015-06-05 10:02:40 +02:00
class BudgetRepository extends ComponentRepository implements BudgetRepositoryInterface
2015-02-22 09:46:21 +01:00
{
2015-04-03 19:39:36 +02:00
/**
* @return void
*/
public function cleanupBudgets()
{
// delete limits with amount 0:
2015-04-05 10:36:28 +02:00
BudgetLimit::where('amount', 0)->delete();
2015-04-03 19:39:36 +02:00
}
2015-12-29 08:27:13 +01:00
/**
* 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;
}
2015-02-22 15:40:13 +01:00
/**
* @param Budget $budget
*
* @return boolean
*/
public function destroy(Budget $budget)
{
$budget->delete();
return true;
}
2015-04-07 17:51:22 +02:00
/**
* @param Budget $budget
* @param Carbon $date
*
* @return float
*/
2015-12-13 10:05:13 +01:00
public function expensesOnDay(Budget $budget, Carbon $date)
2015-04-07 17:51:22 +02:00
{
2015-07-26 19:07:02 +02:00
bcscale(2);
$sum = $budget->transactionjournals()->transactionTypes([TransactionType::WITHDRAWAL])->onDate($date)->get(['transaction_journals.*'])->sum('amount');
2015-05-22 15:05:32 +02:00
2015-10-03 22:34:25 +02:00
return $sum;
2015-04-07 17:51:22 +02:00
}
2015-04-05 10:36:28 +02:00
/**
* @return Collection
*/
public function getActiveBudgets()
{
2015-07-08 13:11:51 +02:00
/** @var Collection $set */
$set = Auth::user()->budgets()->where('active', 1)->get();
2015-07-08 13:11:51 +02:00
$set = $set->sortBy(
function (Budget $budget) {
return strtolower($budget->name);
}
);
return $set;
}
2015-12-27 21:17:04 +01:00
/**
* Returns a list of budgets, budget limits and limit repetitions
* (doubling any of them in a left join)
*
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getBudgetsAndLimitsInRange(Carbon $start, Carbon $end)
{
/** @var Collection $set */
$set = Auth::user()
->budgets()
->leftJoin('budget_limits', 'budget_limits.budget_id', '=', 'budgets.id')
->leftJoin('limit_repetitions', 'limit_repetitions.budget_limit_id', '=', 'budget_limits.id')
->where(
function (Builder $query) use ($start, $end) {
$query->where(
function (Builder $query) use ($start, $end) {
$query->where('limit_repetitions.startdate', '>=', $start->format('Y-m-d'));
$query->where('limit_repetitions.startdate', '<=', $end->format('Y-m-d'));
}
);
$query->orWhere(
function (Builder $query) {
$query->whereNull('limit_repetitions.startdate');
$query->whereNull('limit_repetitions.enddate');
}
);
}
)
->get(['budgets.*', 'limit_repetitions.startdate', 'limit_repetitions.enddate', 'limit_repetitions.amount']);
$set = $set->sortBy(
function (Budget $budget) {
return strtolower($budget->name);
}
);
return $set;
}
/**
* @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')
2015-12-18 16:38:50 +01:00
->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
*
* @return Collection
*/
public function getBudgetLimits(Budget $budget)
{
return $budget->budgetLimits()->orderBy('startdate', 'DESC')->get();
}
/**
* @return Collection
*/
public function getBudgets()
{
2015-07-09 11:13:38 +02:00
/** @var Collection $set */
$set = Auth::user()->budgets()->get();
$set = $set->sortBy(
function (Budget $budget) {
return strtolower($budget->name);
}
);
2015-07-09 11:13:38 +02:00
return $set;
2015-04-05 10:36:28 +02:00
}
/**
* @param Budget $budget
2015-09-27 17:44:49 +02:00
* @param Carbon $start
* @param Carbon $end
2015-04-05 10:36:28 +02:00
*
* @return LimitRepetition|null
*/
2015-09-27 17:44:49 +02:00
public function getCurrentRepetition(Budget $budget, Carbon $start, Carbon $end)
2015-04-05 10:36:28 +02:00
{
2015-06-05 19:02:23 +02:00
$cache = new CacheProperties;
$cache->addProperty($budget->id);
2015-09-27 17:44:49 +02:00
$cache->addProperty($start);
$cache->addProperty($end);
2015-06-05 19:02:23 +02:00
$cache->addProperty('getCurrentRepetition');
if ($cache->has()) {
return $cache->get(); // @codeCoverageIgnore
}
2015-09-27 17:44:49 +02:00
$data = $budget->limitrepetitions()
2015-12-18 16:38:50 +01:00
->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.*']);
2015-06-05 19:02:23 +02:00
$cache->store($data);
return $data;
2015-04-05 10:36:28 +02:00
}
2015-04-07 17:51:22 +02:00
/**
* @param Budget $budget
*
* @return Carbon
*/
public function getFirstBudgetLimitDate(Budget $budget)
{
$limit = $budget->budgetlimits()->orderBy('startdate', 'ASC')->first();
if ($limit) {
return $limit->startdate;
}
return Carbon::now()->startOfYear();
}
2015-12-28 17:57:03 +01:00
/**
* Returns an array with every budget in it and the expenses for each budget
* per month.
*
* @param Collection $accounts
* @param Carbon $start
* @param Carbon $end
2015-12-28 17:57:03 +01:00
*
* @return array
*/
public function getBudgetsAndExpensesPerMonth(Collection $accounts, Carbon $start, Carbon $end)
2015-12-28 17:57:03 +01:00
{
$ids = [];
/** @var Account $account */
foreach ($accounts as $account) {
$ids[] = $account->id;
}
2015-12-28 17:57:03 +01:00
/** @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)
->get(
[
'budgets.*',
DB::Raw('DATE_FORMAT(`transaction_journals`.`date`, "%Y-%m") AS `dateFormatted`'),
DB::Raw('SUM(`transactions`.`amount`) AS `sumAmount`')
]
);
2015-12-28 17:57:03 +01:00
$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;
}
2015-12-28 17:57:03 +01:00
return $return;
}
2015-04-05 10:36:28 +02:00
/**
* @return Collection
*/
public function getInactiveBudgets()
{
2015-07-08 13:11:51 +02:00
/** @var Collection $set */
$set = Auth::user()->budgets()->where('active', 0)->get();
$set = $set->sortBy(
function (Budget $budget) {
return strtolower($budget->name);
}
);
return $set;
2015-04-05 10:36:28 +02:00
}
2015-02-22 15:40:13 +01:00
/**
* Returns all the transaction journals for a limit, possibly limited by a limit repetition.
*
2015-12-18 16:38:50 +01:00
* @param Budget $budget
2015-02-22 15:40:13 +01:00
* @param LimitRepetition $repetition
2015-12-18 16:38:50 +01:00
* @param int $take
2015-02-22 15:40:13 +01:00
*
2015-05-26 20:28:18 +02:00
* @return LengthAwarePaginator
2015-02-22 15:40:13 +01:00
*/
public function getJournals(Budget $budget, LimitRepetition $repetition = null, $take = 50)
{
2015-06-05 19:02:23 +02:00
$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
}
2015-02-22 15:40:13 +01:00
2015-12-18 16:38:50 +01:00
$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')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC');
2015-02-22 15:40:13 +01:00
$countQuery = $budget->transactionJournals();
if (!is_null($repetition->id)) {
$setQuery->after($repetition->startdate)->before($repetition->enddate);
$countQuery->after($repetition->startdate)->before($repetition->enddate);
}
2015-12-18 16:38:50 +01:00
$set = $setQuery->get(['transaction_journals.*']);
2015-02-22 15:40:13 +01:00
$count = $countQuery->count();
2015-03-29 21:27:51 +02:00
2015-06-05 19:02:23 +02:00
$paginator = new LengthAwarePaginator($set, $count, $take, $offset);
$cache->store($paginator);
return $paginator;
2015-02-22 15:40:13 +01:00
}
2015-04-07 17:51:22 +02:00
/**
* @deprecated
*
2015-04-07 17:51:22 +02:00
* @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
2015-12-27 21:17:04 +01:00
*
2015-04-07 17:51:22 +02:00
* @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')
2015-12-18 16:38:50 +01:00
->where('limit_repetitions.startdate', $date->format('Y-m-d 00:00:00'))
->where('budget_limits.budget_id', $budget->id)
->first(['limit_repetitions.*']);
2015-04-07 17:51:22 +02:00
if ($repetition) {
2015-07-26 19:07:02 +02:00
return $repetition->amount;
2015-04-07 17:51:22 +02:00
}
return null;
}
2015-04-05 10:36:28 +02:00
/**
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getWithoutBudget(Carbon $start, Carbon $end)
{
return Auth::user()
2015-12-18 16:38:50 +01:00
->transactionjournals()
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->whereNull('budget_transaction_journal.id')
->before($end)
->after($start)
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->get(['transaction_journals.*']);
2015-04-05 10:36:28 +02:00
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return double
*/
public function getWithoutBudgetSum(Carbon $start, Carbon $end)
{
2015-12-27 21:17:04 +01:00
$entry = Auth::user()
->transactionjournals()
->whereNotIn(
'transaction_journals.id', function (QueryBuilder $query) use ($start, $end) {
$query
->select('transaction_journals.id')
->from('transaction_journals')
->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00'))
->where('transaction_journals.date', '<=', $end->format('Y-m-d 00:00:00'))
->whereNotNull('budget_transaction_journal.budget_id');
}
)
->after($start)
->before($end)
->leftJoin(
'transactions', function (JoinClause $join) {
$join->on('transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transactions.amount', '<', 0);
}
)
->transactionTypes([TransactionType::WITHDRAWAL])
->first([DB::Raw('SUM(`transactions`.`amount`) as `journalAmount`')]);
return $entry->journalAmount;
}
/**
2015-12-18 16:38:50 +01:00
* @param Budget $budget
* @param Carbon $start
* @param Carbon $end
* @param Collection $accounts
*
* @return string
*/
public function balanceInPeriod(Budget $budget, Carbon $start, Carbon $end, Collection $accounts)
{
return $this->commonBalanceInPeriod($budget, $start, $end, $accounts);
}
2015-02-22 15:40:13 +01:00
/**
* @param array $data
*
* @return Budget
*/
public function store(array $data)
{
$newBudget = new Budget(
[
'user_id' => $data['user'],
2015-12-18 16:38:50 +01:00
'name' => $data['name'],
2015-02-22 15:40:13 +01:00
]
);
$newBudget->save();
return $newBudget;
}
2015-05-22 15:05:32 +02:00
2015-02-22 15:40:13 +01:00
/**
* @param Budget $budget
2015-12-18 16:38:50 +01:00
* @param array $data
2015-02-22 15:40:13 +01:00
*
* @return Budget
*/
public function update(Budget $budget, array $data)
{
// update the account:
2015-12-18 16:38:50 +01:00
$budget->name = $data['name'];
$budget->active = $data['active'];
2015-02-22 15:40:13 +01:00
$budget->save();
return $budget;
}
2015-02-22 09:46:21 +01:00
/**
* @param Budget $budget
* @param Carbon $date
* @param $amount
*
* @return BudgetLimit
2015-02-22 09:46:21 +01:00
*/
public function updateLimitAmount(Budget $budget, Carbon $date, $amount)
{
2015-04-03 19:11:55 +02:00
// there should be a budget limit for this startdate:
2015-02-22 09:46:21 +01:00
/** @var BudgetLimit $limit */
2015-04-03 19:11:55 +02:00
$limit = $budget->budgetlimits()->where('budget_limits.startdate', $date)->first(['budget_limits.*']);
2015-02-22 09:46:21 +01:00
if (!$limit) {
2015-04-03 19:11:55 +02:00
// if not, create one!
2015-02-22 09:46:21 +01:00
$limit = new BudgetLimit;
$limit->budget()->associate($budget);
2015-12-18 16:38:50 +01:00
$limit->startdate = $date;
$limit->amount = $amount;
2015-02-22 09:46:21 +01:00
$limit->repeat_freq = 'monthly';
2015-12-18 16:38:50 +01:00
$limit->repeats = 0;
2015-02-22 09:46:21 +01:00
$limit->save();
2015-04-03 19:11:55 +02:00
// likewise, there should be a limit repetition to match the end date
// (which is always the end of the month) but that is caught by an event.
2015-02-22 09:46:21 +01:00
} else {
if ($amount > 0) {
$limit->amount = $amount;
$limit->save();
} else {
$limit->delete();
}
}
2015-02-22 15:40:13 +01:00
2015-02-22 09:46:21 +01:00
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 = [];
2015-02-22 09:46:21 +01:00
/** @var Budget $budget */
foreach ($budgets as $budget) {
$budgetIds[] = $budget->id;
}
$set = Auth::user()->budgets()
2015-12-29 08:27:13 +01:00
->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;
}
2015-02-22 09:46:21 +01:00
/**
* 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;
2015-02-22 09:46:21 +01:00
}
2015-03-29 08:14:32 +02:00
}