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

454 lines
19 KiB
PHP
Raw Normal View History

2019-08-29 21:33:12 +02:00
<?php
2019-08-29 21:33:12 +02:00
/**
* BudgetLimitRepository.php
2020-02-16 14:00:57 +01:00
* Copyright (c) 2019 james@firefly-iii.org
2019-08-29 21:33:12 +02:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2019-08-29 21:33:12 +02:00
*
* 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.
2019-08-29 21:33:12 +02:00
*
* This program is distributed in the hope that it will be useful,
2019-08-29 21:33:12 +02: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.
2019-08-29 21:33:12 +02: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/>.
2019-08-29 21:33:12 +02:00
*/
declare(strict_types=1);
namespace FireflyIII\Repositories\Budget;
2019-08-30 07:54:09 +02:00
use Carbon\Carbon;
2020-08-02 11:53:04 +02:00
use FireflyIII\Exceptions\FireflyException;
2019-08-30 09:19:29 +02:00
use FireflyIII\Factory\TransactionCurrencyFactory;
2019-08-30 08:09:13 +02:00
use FireflyIII\Models\Budget;
2019-08-30 07:49:08 +02:00
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\Note;
2019-08-30 07:54:09 +02:00
use FireflyIII\Models\TransactionCurrency;
2019-08-29 21:33:12 +02:00
use FireflyIII\User;
2023-02-19 08:43:28 +01:00
use Illuminate\Contracts\Auth\Authenticatable;
2019-08-30 07:54:09 +02:00
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
2024-01-05 10:55:46 +01:00
use Illuminate\Support\Facades\Log;
2019-08-29 21:33:12 +02:00
/**
* Class BudgetLimitRepository
*/
class BudgetLimitRepository implements BudgetLimitRepositoryInterface
{
2020-08-17 14:52:49 +02:00
private User $user;
2019-08-29 21:33:12 +02:00
/**
* Tells you which amount has been budgeted (for the given budgets)
* in the selected query. Returns a positive amount as a string.
*/
public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, ?Collection $budgets = null): string
{
2024-12-14 05:45:54 +01:00
$query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
// same complex where query as below.
2024-12-14 05:45:54 +01:00
->where(
2023-12-21 05:07:26 +01:00
static function (Builder $q5) use ($start, $end): void {
2023-12-10 06:51:59 +01:00
$q5->where(
2023-12-21 05:07:26 +01:00
static function (Builder $q1) use ($start, $end): void {
2023-12-10 06:51:59 +01:00
$q1->where(
2023-12-21 05:07:26 +01:00
static function (Builder $q2) use ($start, $end): void {
2023-12-10 06:51:59 +01:00
$q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d'));
$q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d'));
}
)
2024-12-14 05:45:54 +01:00
->orWhere(
static function (Builder $q3) use ($start, $end): void {
$q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d'));
$q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d'));
}
)
;
2023-12-10 06:51:59 +01:00
}
)
2024-12-14 05:45:54 +01:00
->orWhere(
static function (Builder $q4) use ($start, $end): void {
// or start is before start AND end is after end.
$q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d'));
$q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d'));
}
)
;
2023-12-10 06:51:59 +01:00
}
2023-12-20 19:35:52 +01:00
)
2024-12-14 05:45:54 +01:00
->where('budget_limits.transaction_currency_id', $currency->id)
->whereNull('budgets.deleted_at')
->where('budgets.active', true)
->where('budgets.user_id', $this->user->id)
;
if (null !== $budgets && $budgets->count() > 0) {
2019-10-05 05:18:40 +02:00
$query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray());
}
2019-10-05 05:18:40 +02:00
$set = $query->get(['budget_limits.*']);
$result = '0';
2023-12-20 19:35:52 +01:00
/** @var BudgetLimit $budgetLimit */
foreach ($set as $budgetLimit) {
$result = bcadd($budgetLimit->amount, $result);
}
return $result;
}
2021-03-12 06:20:01 +01:00
/**
* Destroy all budget limits.
*/
public function destroyAll(): void
{
$budgets = $this->user->budgets()->get();
2023-12-20 19:35:52 +01:00
2021-03-12 06:20:01 +01:00
/** @var Budget $budget */
foreach ($budgets as $budget) {
2024-01-05 10:55:46 +01:00
Log::channel('audit')->info(sprintf('Delete all budget limits of budget #%d ("%s") through destroyAll', $budget->id, $budget->name));
2021-03-12 06:20:01 +01:00
$budget->budgetlimits()->delete();
}
}
2019-08-30 07:49:08 +02:00
/**
* Destroy a budget limit.
*/
public function destroyBudgetLimit(BudgetLimit $budgetLimit): void
{
2022-12-30 20:25:04 +01:00
$budgetLimit->delete();
2019-08-30 07:49:08 +02:00
}
public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection
2022-03-29 14:59:58 +02:00
{
2023-06-21 12:34:58 +02:00
return $this->getAllBudgetLimits($start, $end)->filter(
static function (BudgetLimit $budgetLimit) use ($currency) {
return $budgetLimit->transaction_currency_id === $currency->id;
}
);
2022-03-29 14:59:58 +02:00
}
public function getAllBudgetLimits(?Carbon $start = null, ?Carbon $end = null): Collection
2019-08-30 07:54:09 +02:00
{
// both are NULL:
if (null === $start && null === $end) {
2020-10-23 19:11:25 +02:00
return BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
2024-12-14 05:45:54 +01:00
->with(['budget'])
->where('budgets.user_id', $this->user->id)
->whereNull('budgets.deleted_at')
->get(['budget_limits.*'])
;
2019-08-30 07:54:09 +02:00
}
// one of the two is NULL.
if (null === $start xor null === $end) {
$query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
2024-12-14 05:45:54 +01:00
->with(['budget'])
->whereNull('budgets.deleted_at')
->where('budgets.user_id', $this->user->id)
;
2019-08-30 07:54:09 +02:00
if (null !== $end) {
// end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
}
if (null !== $start) {
// start date must be after $start.
$query->where('start_date', '>=', $start->format('Y-m-d 00:00:00'));
}
2021-03-12 06:20:01 +01:00
2020-10-23 19:11:25 +02:00
return $query->get(['budget_limits.*']);
2019-08-30 07:54:09 +02:00
}
2021-03-12 06:20:01 +01:00
2019-08-30 07:54:09 +02:00
// neither are NULL:
2020-10-23 19:11:25 +02:00
return BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
2024-12-14 05:45:54 +01:00
->with(['budget'])
->where('budgets.user_id', $this->user->id)
->whereNull('budgets.deleted_at')
->where(
static function (Builder $q5) use ($start, $end): void {
$q5->where(
static function (Builder $q1) use ($start, $end): void {
$q1->where(
static function (Builder $q2) use ($start, $end): void {
$q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d'));
$q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d'));
}
)
->orWhere(
static function (Builder $q3) use ($start, $end): void {
$q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d'));
$q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d'));
}
)
;
}
)
->orWhere(
static function (Builder $q4) use ($start, $end): void {
// or start is before start AND end is after end.
$q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d'));
$q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d'));
}
)
;
}
)->get(['budget_limits.*'])
;
2019-08-30 07:54:09 +02:00
}
public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection
2019-08-30 08:09:13 +02:00
{
if (null === $end && null === $start) {
return $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']);
}
if (null === $end xor null === $start) {
$query = $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC');
// one of the two is null
if (null !== $end) {
// end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
}
if (null !== $start) {
// start date must be after $start.
$query->where('start_date', '>=', $start->format('Y-m-d 00:00:00'));
}
2021-03-12 06:20:01 +01:00
2020-10-23 19:11:25 +02:00
return $query->get(['budget_limits.*']);
2019-08-30 08:09:13 +02:00
}
// when both dates are set:
2020-10-23 19:11:25 +02:00
return $budget->budgetlimits()
2024-12-14 05:45:54 +01:00
->where(
static function (Builder $q5) use ($start, $end): void { // @phpstan-ignore-line
$q5->where(
static function (Builder $q1) use ($start, $end): void {
// budget limit ends within period
$q1->where(
static function (Builder $q2) use ($start, $end): void {
$q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d 00:00:00'));
$q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d 23:59:59'));
}
)
// budget limit start within period
->orWhere(
static function (Builder $q3) use ($start, $end): void {
$q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d 00:00:00'));
$q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d 23:59:59'));
}
)
;
}
)
->orWhere(
static function (Builder $q4) use ($start, $end): void {
// or start is before start AND end is after end.
$q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d 23:59:59'));
$q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d 00:00:00'));
}
)
;
}
)->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*'])
;
2019-08-30 08:09:13 +02:00
}
2024-12-14 05:45:54 +01:00
public function setUser(null|Authenticatable|User $user): void
2019-08-29 21:33:12 +02:00
{
2023-10-30 19:49:40 +01:00
if ($user instanceof User) {
2023-02-19 08:43:28 +01:00
$this->user = $user;
}
2019-08-29 21:33:12 +02:00
}
2019-08-30 09:19:29 +02:00
/**
2020-08-02 11:53:04 +02:00
* @throws FireflyException
2023-12-22 20:12:38 +01:00
*/
public function store(array $data): BudgetLimit
{
2019-08-30 09:19:29 +02:00
// if no currency has been provided, use the user's default currency:
/** @var TransactionCurrencyFactory $factory */
2024-12-14 05:45:54 +01:00
$factory = app(TransactionCurrencyFactory::class);
$currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null);
2019-08-30 09:19:29 +02:00
if (null === $currency) {
2023-10-29 17:41:14 +01:00
$currency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
2019-08-30 09:19:29 +02:00
}
2024-12-14 05:45:54 +01:00
$currency->enabled = true;
2020-08-02 11:53:04 +02:00
$currency->save();
// find the budget:
2024-12-14 05:45:54 +01:00
$budget = $this->user->budgets()->find((int) $data['budget_id']);
2020-08-02 11:53:04 +02:00
if (null === $budget) {
throw new FireflyException('200004: Budget does not exist.');
2020-08-02 11:53:04 +02:00
}
2019-08-30 09:19:29 +02:00
2020-08-02 11:53:04 +02:00
// find limit with same date range and currency.
2024-12-14 05:45:54 +01:00
$limit = $budget->budgetlimits()
->where('budget_limits.start_date', $data['start_date']->format('Y-m-d'))
->where('budget_limits.end_date', $data['end_date']->format('Y-m-d'))
->where('budget_limits.transaction_currency_id', $currency->id)
->first(['budget_limits.*'])
;
2019-08-30 09:19:29 +02:00
if (null !== $limit) {
throw new FireflyException('200027: Budget limit already exists.');
2019-08-30 09:19:29 +02:00
}
2023-10-29 06:33:43 +01:00
app('log')->debug('No existing budget limit, create a new one');
2019-08-30 09:19:29 +02:00
// or create one and return it.
2024-12-14 05:45:54 +01:00
$limit = new BudgetLimit();
2019-08-30 09:19:29 +02:00
$limit->budget()->associate($budget);
2021-04-07 07:28:43 +02:00
$limit->start_date = $data['start_date']->format('Y-m-d');
$limit->end_date = $data['end_date']->format('Y-m-d');
2019-08-30 09:19:29 +02:00
$limit->amount = $data['amount'];
$limit->transaction_currency_id = $currency->id;
$limit->save();
2024-12-14 05:45:54 +01:00
$noteText = (string) ($data['notes'] ?? '');
if ('' !== $noteText) {
$this->setNoteText($limit, $noteText);
}
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Created new budget limit with ID #%d and amount %s', $limit->id, $data['amount']));
2019-08-30 09:19:29 +02:00
return $limit;
}
2023-06-21 12:34:58 +02:00
public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit
{
return $budget->budgetlimits()
2024-12-14 05:45:54 +01:00
->where('transaction_currency_id', $currency->id)
->where('start_date', $start->format('Y-m-d'))
->where('end_date', $end->format('Y-m-d'))->first()
;
2023-06-21 12:34:58 +02:00
}
/**
2022-03-29 15:10:05 +02:00
* @throws FireflyException
2023-12-22 20:12:38 +01:00
*/
public function update(BudgetLimit $budgetLimit, array $data): BudgetLimit
{
2024-12-14 05:45:54 +01:00
$budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount;
$budgetLimit->budget_id = array_key_exists('budget_id', $data) ? $data['budget_id'] : $budgetLimit->budget_id;
2024-11-06 11:57:12 +01:00
if (array_key_exists('start', $data)) {
$budgetLimit->start_date = $data['start']->startOfDay();
$budgetLimit->start_date_tz = $data['start']->format('e');
}
if (array_key_exists('end', $data)) {
$budgetLimit->end_date = $data['end']->endOfDay();
$budgetLimit->end_date_tz = $data['end']->format('e');
}
2019-08-30 09:19:29 +02:00
// if no currency has been provided, use the user's default currency:
2024-12-14 05:45:54 +01:00
$currency = null;
2020-08-17 15:58:06 +02:00
// update if relevant:
2021-03-12 06:20:01 +01:00
if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
2020-08-17 15:58:06 +02:00
/** @var TransactionCurrencyFactory $factory */
$factory = app(TransactionCurrencyFactory::class);
$currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null);
}
// catch unexpected null:
2021-03-12 06:20:01 +01:00
if (null === $currency) {
2023-10-29 17:41:14 +01:00
$currency = $budgetLimit->transactionCurrency ?? app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
2019-08-30 09:19:29 +02:00
}
2024-12-14 05:45:54 +01:00
$currency->enabled = true;
2019-08-30 09:19:29 +02:00
$currency->save();
2020-08-02 11:59:43 +02:00
$budgetLimit->transaction_currency_id = $currency->id;
2019-08-30 09:19:29 +02:00
$budgetLimit->save();
2020-08-02 11:59:43 +02:00
// update notes if they exist.
2024-12-14 05:45:54 +01:00
if (array_key_exists('notes', $data)) {
$this->setNoteText($budgetLimit, (string)$data['notes']);
}
2019-08-30 09:19:29 +02:00
return $budgetLimit;
}
public function updateLimitAmount(Budget $budget, Carbon $start, Carbon $end, string $amount): ?BudgetLimit
{
// count the limits:
2024-12-14 05:45:54 +01:00
$limits = $budget->budgetlimits()
->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
->count('budget_limits.*')
;
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Found %d budget limits.', $limits));
2019-08-30 09:19:29 +02:00
// there might be a budget limit for these dates:
2023-12-20 19:35:52 +01:00
/** @var null|BudgetLimit $limit */
2024-12-14 05:45:54 +01:00
$limit = $budget->budgetlimits()
->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
->first(['budget_limits.*'])
;
2019-08-30 09:19:29 +02:00
// if more than 1 limit found, delete the others:
if ($limits > 1 && null !== $limit) {
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Found more than 1, delete all except #%d', $limit->id));
2019-08-30 09:19:29 +02:00
$budget->budgetlimits()
2024-12-14 05:45:54 +01:00
->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
->where('budget_limits.id', '!=', $limit->id)->delete()
;
2019-08-30 09:19:29 +02:00
}
// delete if amount is zero.
// Returns 0 if the two operands are equal,
// 1 if the left_operand is larger than the right_operand, -1 otherwise.
if (null !== $limit && bccomp($amount, '0') <= 0) {
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('%s is zero, delete budget limit #%d', $amount, $limit->id));
2022-12-30 20:25:04 +01:00
$limit->delete();
2019-08-30 09:19:29 +02:00
return null;
}
// update if exists:
if (null !== $limit) {
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Existing budget limit is #%d, update this to amount %s', $limit->id, $amount));
2019-08-30 09:19:29 +02:00
$limit->amount = $amount;
$limit->save();
return $limit;
}
2023-10-29 06:33:43 +01:00
app('log')->debug('No existing budget limit, create a new one');
2019-08-30 09:19:29 +02:00
// or create one and return it.
2024-12-14 05:45:54 +01:00
$limit = new BudgetLimit();
2019-08-30 09:19:29 +02:00
$limit->budget()->associate($budget);
2024-11-06 11:57:12 +01:00
$limit->start_date = $start->startOfDay();
$limit->start_date_tz = $start->format('e');
$limit->end_date = $end->startOfDay();
$limit->end_date_tz = $end->format('e');
$limit->amount = $amount;
2019-08-30 09:19:29 +02:00
$limit->save();
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Created new budget limit with ID #%d and amount %s', $limit->id, $amount));
2019-08-30 09:19:29 +02:00
return $limit;
}
2024-12-14 05:45:54 +01:00
#[\Override]
public function getNoteText(BudgetLimit $budgetLimit): string
{
return (string) $budgetLimit->notes()->first()?->text;
}
2024-12-14 05:45:54 +01:00
#[\Override]
public function setNoteText(BudgetLimit $budgetLimit, string $text): void
{
$dbNote = $budgetLimit->notes()->first();
if ('' !== $text) {
if (null === $dbNote) {
$dbNote = new Note();
$dbNote->noteable()->associate($budgetLimit);
}
$dbNote->text = trim($text);
$dbNote->save();
return;
}
$dbNote?->delete();
}
}