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

516 lines
16 KiB
PHP
Raw Normal View History

2015-02-22 02:46:21 -06:00
<?php
/**
* BudgetRepository.php
2020-02-16 07:00:57 -06:00
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
2017-10-21 01:40:00 -05:00
*
* This program is distributed in the hope that it will be useful,
2017-10-21 01:40:00 -05:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2017-10-21 01:40:00 -05:00
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
2015-02-22 02:46:21 -06:00
namespace FireflyIII\Repositories\Budget;
use Carbon\Carbon;
use DB;
2018-06-24 01:33:06 -05:00
use Exception;
2019-10-30 14:02:21 -05:00
use FireflyIII\Exceptions\FireflyException;
2020-05-06 23:44:01 -05:00
use FireflyIII\Models\Attachment;
2020-03-14 01:30:55 -05:00
use FireflyIII\Models\AutoBudget;
2015-02-22 02:46:21 -06:00
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\RecurrenceTransactionMeta;
2018-07-22 01:27:18 -05:00
use FireflyIII\Models\RuleAction;
use FireflyIII\Models\RuleTrigger;
2020-03-14 01:30:55 -05:00
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
2019-01-11 09:57:40 -06:00
use FireflyIII\Services\Internal\Destroy\BudgetDestroyService;
use FireflyIII\User;
2019-10-30 14:02:21 -05:00
use Illuminate\Database\QueryException;
2015-04-05 03:36:28 -05:00
use Illuminate\Support\Collection;
2017-11-24 10:05:22 -06:00
use Log;
2020-05-06 23:44:01 -05:00
use Storage;
2015-02-22 02:46:21 -06:00
/**
2017-11-15 05:25:49 -06:00
* Class BudgetRepository.
*
2015-02-22 02:46:21 -06:00
*/
2016-05-05 23:15:46 -05:00
class BudgetRepository implements BudgetRepositoryInterface
2015-02-22 02:46:21 -06:00
{
/** @var User */
private $user;
/**
* Constructor.
*/
public function __construct()
{
if ('testing' === config('app.env')) {
2019-06-07 11:20:15 -05:00
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this)));
2019-09-04 14:05:50 -05:00
die(get_class($this));
}
}
2019-08-22 11:04:26 -05:00
/**
* @return bool
*/
public function cleanupBudgets(): bool
{
// delete limits with amount 0:
try {
BudgetLimit::where('amount', 0)->delete();
} catch (Exception $e) {
Log::debug(sprintf('Could not delete budget limit: %s', $e->getMessage()));
}
$budgets = $this->getActiveBudgets();
/**
* @var int $index
* @var Budget $budget
*/
foreach ($budgets as $index => $budget) {
$budget->order = $index + 1;
$budget->save();
2019-08-22 11:04:26 -05:00
}
2020-04-25 23:57:59 -05:00
// other budgets, set to 0.
$this->user->budgets()->where('active', 0)->update(['order' => 0]);
2019-08-22 11:04:26 -05:00
return true;
}
2015-02-22 08:40:13 -06:00
/**
* @param Budget $budget
*
2016-04-05 15:00:03 -05:00
* @return bool
2015-02-22 08:40:13 -06:00
*/
2016-04-05 15:00:03 -05:00
public function destroy(Budget $budget): bool
2015-02-22 08:40:13 -06:00
{
2019-01-11 09:57:40 -06:00
/** @var BudgetDestroyService $service */
$service = app(BudgetDestroyService::class);
$service->destroy($budget);
2015-02-22 08:40:13 -06:00
return true;
}
/**
2019-08-22 11:04:26 -05:00
* @param int|null $budgetId
* @param string|null $budgetName
*
* @return Budget|null
*/
public function findBudget(?int $budgetId, ?string $budgetName): ?Budget
{
Log::debug('Now in findBudget()');
Log::debug(sprintf('Searching for budget with ID #%d...', $budgetId));
$result = $this->findNull((int)$budgetId);
2019-05-23 22:28:41 -05:00
if (null === $result && null !== $budgetName && '' !== $budgetName) {
Log::debug(sprintf('Searching for budget with name %s...', $budgetName));
$result = $this->findByName((string)$budgetName);
}
if (null !== $result) {
Log::debug(sprintf('Found budget #%d: %s', $result->id, $result->name));
}
Log::debug(sprintf('Found result is null? %s', var_export(null === $result, true)));
return $result;
}
/**
2019-08-22 11:04:26 -05:00
* Find budget by name.
*
2019-08-22 11:04:26 -05:00
* @param string|null $name
*
* @return Budget|null
*/
2019-08-22 11:04:26 -05:00
public function findByName(?string $name): ?Budget
{
2019-08-22 11:04:26 -05:00
if (null === $name) {
return null;
}
2019-08-22 11:04:26 -05:00
$query = sprintf('%%%s%%', $name);
2019-08-22 11:04:26 -05:00
return $this->user->budgets()->where('name', 'LIKE', $query)->first();
}
2018-02-16 08:19:19 -06:00
/**
2019-08-22 11:04:26 -05:00
* Find a budget or return NULL
2018-02-16 08:19:19 -06:00
*
2019-08-22 11:04:26 -05:00
* @param int $budgetId |null
2018-02-16 08:19:19 -06:00
*
* @return Budget|null
*/
2019-08-22 11:04:26 -05:00
public function findNull(int $budgetId = null): ?Budget
2018-02-16 08:19:19 -06:00
{
2019-08-22 11:04:26 -05:00
if (null === $budgetId) {
2018-07-05 11:02:02 -05:00
return null;
}
2019-08-22 11:04:26 -05:00
return $this->user->budgets()->find($budgetId);
}
/**
* This method returns the oldest journal or transaction date known to this budget.
* Will cache result.
*
* @param Budget $budget
*
* @return Carbon
2019-08-17 03:47:29 -05:00
*
*/
2018-07-23 14:49:15 -05:00
public function firstUseDate(Budget $budget): ?Carbon
{
2018-07-23 14:49:15 -05:00
$oldest = null;
$journal = $budget->transactionJournals()->orderBy('date', 'ASC')->first();
2017-11-15 05:25:49 -06:00
if (null !== $journal) {
$oldest = $journal->date < $oldest ? $journal->date : $oldest;
}
$transaction = $budget
->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.id')
->orderBy('transaction_journals.date', 'ASC')->first(['transactions.*', 'transaction_journals.date']);
2017-11-15 05:25:49 -06:00
if (null !== $transaction) {
2016-05-11 10:17:43 -05:00
$carbon = new Carbon($transaction->date);
$oldest = $carbon < $oldest ? $carbon : $oldest;
}
return $oldest;
}
2015-12-27 14:17:04 -06:00
/**
* @return Collection
*/
2016-04-05 15:00:03 -05:00
public function getActiveBudgets(): Collection
2015-12-27 14:17:04 -06:00
{
/** @var Collection $set */
2018-10-17 08:18:09 -05:00
$set = $this->user->budgets()->where('active', 1)
2020-04-25 23:54:12 -05:00
->orderBy('order', 'ASC')
2019-05-23 22:28:41 -05:00
->orderBy('name', 'ASC')
2018-10-17 08:18:09 -05:00
->get();
2015-12-27 14:17:04 -06:00
return $set;
}
2016-01-20 08:21:27 -06:00
/**
* @return Collection
*/
public function getBudgets(): Collection
2016-01-20 08:21:27 -06:00
{
/** @var Collection $set */
2020-04-25 23:54:12 -05:00
$set = $this->user->budgets()->orderBy('order', 'ASC')
2019-05-04 13:58:43 -05:00
->orderBy('name', 'ASC')->get();
2016-01-20 08:21:27 -06:00
return $set;
}
2015-04-05 03:36:28 -05:00
2018-05-07 13:35:14 -05:00
/**
* Get all budgets with these ID's.
*
* @param array $budgetIds
*
* @return Collection
*/
public function getByIds(array $budgetIds): Collection
{
return $this->user->budgets()->whereIn('id', $budgetIds)->get();
}
/**
* @return Collection
*/
public function getInactiveBudgets(): Collection
{
/** @var Collection $set */
2019-09-21 00:15:32 -05:00
$set = $this->user->budgets()
2020-04-25 23:54:12 -05:00
->orderBy('order', 'ASC')
2019-05-04 13:58:43 -05:00
->orderBy('name', 'ASC')->where('active', 0)->get();
return $set;
}
2019-03-02 07:12:09 -06:00
/**
* @param string $query
*
* @return Collection
*/
public function searchBudget(string $query): Collection
{
$search = $this->user->budgets();
if ('' !== $query) {
$search->where('name', 'LIKE', sprintf('%%%s%%', $query));
}
2020-01-08 11:13:42 -06:00
$search->orderBy('order', 'ASC')
2019-09-21 00:15:32 -05:00
->orderBy('name', 'ASC')->where('active', 1);
return $search->get();
2019-03-02 07:12:09 -06:00
}
2018-10-17 08:18:09 -05:00
/**
* @param Budget $budget
2019-08-22 11:04:26 -05:00
* @param int $order
2018-10-17 08:18:09 -05:00
*/
public function setBudgetOrder(Budget $budget, int $order): void
{
$budget->order = $order;
$budget->save();
}
2017-01-30 09:46:30 -06:00
/**
* @param User $user
*/
2018-07-22 11:50:27 -05:00
public function setUser(User $user): void
2017-01-30 09:46:30 -06:00
{
$this->user = $user;
}
2016-01-20 08:21:27 -06:00
/**
* @param array $data
*
* @return Budget
2019-10-30 14:02:21 -05:00
* @throws FireflyException
2016-01-20 08:21:27 -06:00
*/
2016-04-05 15:00:03 -05:00
public function store(array $data): Budget
2016-01-20 08:21:27 -06:00
{
2020-04-25 23:57:59 -05:00
$order = $this->getMaxOrder();
2019-10-30 14:02:21 -05:00
try {
$newBudget = Budget::create(
[
'user_id' => $this->user->id,
'name' => $data['name'],
2020-04-25 23:57:59 -05:00
'order' => $order + 1,
2019-10-30 14:02:21 -05:00
]
);
2020-03-13 15:35:22 -05:00
} catch (QueryException $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
2019-10-30 14:02:21 -05:00
throw new FireflyException('400002: Could not store budget.');
}
2016-01-20 08:21:27 -06:00
2020-03-13 15:35:22 -05:00
// try to create associated auto budget:
2020-03-14 01:30:55 -05:00
$type = $data['auto_budget_type'] ?? 0;
if (0 === $type) {
2020-03-13 15:35:22 -05:00
return $newBudget;
}
2020-03-14 01:30:55 -05:00
if ('reset' === $type) {
$type = AutoBudget::AUTO_BUDGET_RESET;
}
if ('rollover' === $type) {
$type = AutoBudget::AUTO_BUDGET_ROLLOVER;
}
$repos = app(CurrencyRepositoryInterface::class);
$currencyId = (int)($data['transaction_currency_id'] ?? 0);
$currencyCode = (string)($data['transaction_currency_code'] ?? '');
$currency = $repos->findNull($currencyId);
if(null === $currency) {
$currency = $repos->findByCodeNull($currencyCode);
}
if(null === $currency) {
$currency = app('amount')->getDefaultCurrencyByUser($this->user);
}
2020-03-13 15:35:22 -05:00
$autoBudget = new AutoBudget;
$autoBudget->budget()->associate($newBudget);
2020-03-14 01:30:55 -05:00
$autoBudget->transaction_currency_id = $currency->id;
$autoBudget->auto_budget_type = $type;
2020-03-13 15:35:22 -05:00
$autoBudget->amount = $data['auto_budget_amount'] ?? '1';
$autoBudget->period = $data['auto_budget_period'] ?? 'monthly';
$autoBudget->save();
2020-03-14 01:30:55 -05:00
2020-03-14 09:18:32 -05:00
// create initial budget limit.
$today = new Carbon;
$start = app('navigation')->startOfPeriod($today, $autoBudget->period);
2020-05-23 12:54:02 -05:00
$end = app('navigation')->endOfPeriod($start, $autoBudget->period);
2020-03-14 09:18:32 -05:00
$limitRepos = app(BudgetLimitRepositoryInterface::class);
$limitRepos->setUser($this->user);
$limitRepos->store(
[
'budget_id' => $newBudget->id,
'transaction_currency_id' => $autoBudget->transaction_currency_id,
'start_date' => $start->format('Y-m-d'),
'end_date' => $end->format('Y-m-d'),
'amount' => $autoBudget->amount,
]
);
2016-01-20 08:21:27 -06:00
return $newBudget;
}
/**
* @param Budget $budget
2019-08-22 11:04:26 -05:00
* @param array $data
2016-01-20 08:21:27 -06:00
*
* @return Budget
*/
2016-04-05 15:00:03 -05:00
public function update(Budget $budget, array $data): Budget
2016-01-20 08:21:27 -06:00
{
$oldName = $budget->name;
2016-01-20 08:21:27 -06:00
$budget->name = $data['name'];
$budget->active = $data['active'];
$budget->save();
// update or create auto-budget:
$autoBudgetType = $data['auto_budget_type'] ?? 0;
if ('reset' === $autoBudgetType) {
$autoBudgetType = AutoBudget::AUTO_BUDGET_RESET;
}
if ('rollover' === $autoBudgetType) {
$autoBudgetType = AutoBudget::AUTO_BUDGET_ROLLOVER;
}
if ('none' === $autoBudgetType) {
$autoBudgetType = 0;
}
if (0 !== $autoBudgetType) {
$autoBudget = $this->getAutoBudget($budget);
if (null === $autoBudget) {
$autoBudget = new AutoBudget;
$autoBudget->budget()->associate($budget);
}
$repos = app(CurrencyRepositoryInterface::class);
$currencyId = (int)($data['transaction_currency_id'] ?? 0);
$currencyCode = (string)($data['transaction_currency_code'] ?? '');
$currency = $repos->findNull($currencyId);
if(null === $currency) {
$currency = $repos->findByCodeNull($currencyCode);
}
if(null === $currency) {
$currency = app('amount')->getDefaultCurrencyByUser($this->user);
}
$autoBudget->transaction_currency_id = $currency->id;
$autoBudget->auto_budget_type = $autoBudgetType;
$autoBudget->amount = $data['auto_budget_amount'] ?? '0';
$autoBudget->period = $data['auto_budget_period'] ?? 'monthly';
$autoBudget->save();
}
if (0 === $autoBudgetType) {
$autoBudget = $this->getAutoBudget($budget);
if (null !== $autoBudget) {
$this->destroyAutoBudget($budget);
}
}
$this->updateRuleTriggers($oldName, $data['name']);
$this->updateRuleActions($oldName, $data['name']);
2018-07-22 01:27:18 -05:00
app('preferences')->mark();
2016-01-20 08:21:27 -06:00
return $budget;
}
2019-06-04 13:42:11 -05:00
/**
2019-08-22 11:04:26 -05:00
* @param string $oldName
* @param string $newName
2019-06-04 13:42:11 -05:00
*/
2019-08-22 11:04:26 -05:00
private function updateRuleActions(string $oldName, string $newName): void
2019-06-04 13:42:11 -05:00
{
2019-08-22 11:04:26 -05:00
$types = ['set_budget',];
$actions = RuleAction::leftJoin('rules', 'rules.id', '=', 'rule_actions.rule_id')
->where('rules.user_id', $this->user->id)
->whereIn('rule_actions.action_type', $types)
->where('rule_actions.action_value', $oldName)
->get(['rule_actions.*']);
Log::debug(sprintf('Found %d actions to update.', $actions->count()));
/** @var RuleAction $action */
foreach ($actions as $action) {
$action->action_value = $newName;
$action->save();
Log::debug(sprintf('Updated action %d: %s', $action->id, $action->action_value));
2019-06-04 13:42:11 -05:00
}
}
/**
* @param string $oldName
* @param string $newName
*/
private function updateRuleTriggers(string $oldName, string $newName): void
{
$types = ['budget_is',];
$triggers = RuleTrigger::leftJoin('rules', 'rules.id', '=', 'rule_triggers.rule_id')
->where('rules.user_id', $this->user->id)
->whereIn('rule_triggers.trigger_type', $types)
->where('rule_triggers.trigger_value', $oldName)
->get(['rule_triggers.*']);
Log::debug(sprintf('Found %d triggers to update.', $triggers->count()));
/** @var RuleTrigger $trigger */
foreach ($triggers as $trigger) {
$trigger->trigger_value = $newName;
$trigger->save();
Log::debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value));
}
}
/**
* Destroy all budgets.
*/
public function destroyAll(): void
{
$budgets = $this->getBudgets();
/** @var Budget $budget */
foreach ($budgets as $budget) {
DB::table('budget_transaction')->where('budget_id', $budget->id)->delete();
DB::table('budget_transaction_journal')->where('budget_id', $budget->id)->delete();
RecurrenceTransactionMeta::where('name', 'budget_id')->where('value', $budget->id)->delete();
RuleAction::where('action_type', 'set_budget')->where('action_value', $budget->id)->delete();
$budget->delete();
}
}
/**
* @inheritDoc
*/
public function getAutoBudget(Budget $budget): ?AutoBudget
{
return $budget->autoBudgets()->first();
}
/**
* @inheritDoc
*/
public function destroyAutoBudget(Budget $budget): void
{
/** @var AutoBudget $autoBudget */
foreach ($budget->autoBudgets()->get() as $autoBudget) {
$autoBudget->delete();
}
}
/**
* @inheritDoc
*/
public function getAttachments(Budget $budget): Collection
{
2020-05-06 23:44:01 -05:00
$set = $budget->attachments()->get();
/** @var Storage $disk */
$disk = Storage::disk('upload');
$set = $set->each(
static function (Attachment $attachment) use ($disk) {
$notes = $attachment->notes()->first();
$attachment->file_exists = $disk->exists($attachment->fileName());
$attachment->notes = $notes ? $notes->text : '';
return $attachment;
}
);
return $set;
}
2020-04-25 23:57:59 -05:00
public function getMaxOrder(): int
{
return (int)$this->user->budgets()->max('order');
}
2015-03-29 01:14:32 -05:00
}