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

409 lines
18 KiB
PHP
Raw Permalink 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;
use FireflyIII\Events\Model\BudgetLimit\CreatedBudgetLimit;
use FireflyIII\Events\Model\BudgetLimit\DestroyedBudgetLimit;
use FireflyIII\Events\Model\BudgetLimit\UpdatedBudgetLimit;
2026-02-06 08:33:10 +01:00
use FireflyIII\Events\Model\Webhook\WebhookMessagesRequestSending;
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;
use FireflyIII\Support\Facades\Amount;
2025-02-23 12:28:27 +01:00
use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface;
use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait;
use FireflyIII\Support\Singleton\PreferencesSingleton;
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;
use Override;
use Spatie\Period\Boundaries;
use Spatie\Period\Period;
use Spatie\Period\Precision;
2019-08-29 21:33:12 +02:00
/**
* Class BudgetLimitRepository
*/
2025-02-23 12:28:27 +01:00
class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroupInterface
2019-08-29 21:33:12 +02:00
{
2025-02-23 12:28:27 +01:00
use UserGroupTrait;
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
{
$query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
// same complex where query as below.
->where(static function (Builder $q5) use ($start, $end): void {
2026-01-23 15:09:50 +01:00
$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'));
});
})
->where('budget_limits.transaction_currency_id', $currency->id)
->whereNull('budgets.deleted_at')
->where('budgets.active', true)
->where('budgets.user_id', $this->user->id)
;
2025-05-27 17:06:15 +02:00
if ($budgets instanceof Collection && $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) {
2026-02-06 15:38:32 +01:00
if ($budgetLimit->start_date->isSameDay($start) && $budgetLimit->end_date->isSameDay($end)) {
$result = bcadd((string) $budgetLimit->amount, $result);
2026-02-06 15:38:32 +01:00
continue;
}
$period = Period::make($start, $end, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());
$amountPerDay = $this->getDailyAmount($budgetLimit);
$result = bcadd($result, bcmul((string) $period->length(), $amountPerDay));
}
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
{
$user = $budgetLimit->budget->user;
$start = $budgetLimit->start_date->clone();
$end = $budgetLimit->end_date->clone();
2026-02-06 08:33:10 +01:00
event(new DestroyedBudgetLimit($user, $budgetLimit->budget, $start, $end, true));
2022-12-30 20:25:04 +01:00
$budgetLimit->delete();
2026-02-06 08:33:10 +01:00
event(new WebhookMessagesRequestSending());
}
public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit
2022-03-29 14:59:58 +02:00
{
/** @var null|BudgetLimit */
return $budget
->budgetlimits()
->where('transaction_currency_id', $currency->id)
->where('start_date', $start->format('Y-m-d'))
->where('end_date', $end->format('Y-m-d'))
->first()
;
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:
2025-05-27 17:06:15 +02:00
if (!$start instanceof Carbon && !$end instanceof Carbon) {
2020-10-23 19:11:25 +02:00
return BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->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.
2025-05-27 17:06:15 +02:00
if (!$start instanceof Carbon xor !$end instanceof Carbon) {
2019-08-30 07:54:09 +02:00
$query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->with(['budget'])
->whereNull('budgets.deleted_at')
->where('budgets.user_id', $this->user->id)
;
2025-05-27 17:06:15 +02:00
if ($end instanceof Carbon) {
2019-08-30 07:54:09 +02:00
// end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
}
2025-05-27 17:06:15 +02:00
if ($start instanceof Carbon) {
2019-08-30 07:54:09 +02:00
// 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')
->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.*'])
;
}
public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection
{
return $this->getAllBudgetLimits($start, $end)->filter(
static fn (BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id
);
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
{
2025-05-27 17:06:15 +02:00
if (!$end instanceof Carbon && !$start instanceof Carbon) {
2019-08-30 08:09:13 +02:00
return $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']);
}
2025-05-27 17:06:15 +02:00
if (!$end instanceof Carbon xor !$start instanceof Carbon) {
2019-08-30 08:09:13 +02:00
$query = $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC');
// one of the two is null
2025-05-27 17:06:15 +02:00
if ($end instanceof Carbon) {
2019-08-30 08:09:13 +02:00
// end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
}
2025-05-27 17:06:15 +02:00
if ($start instanceof Carbon) {
2019-08-30 08:09:13 +02:00
// 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:
2026-01-23 15:09:50 +01:00
return $budget
->budgetlimits()
->where(static function (Builder $q5) use ($start, $end): void {
$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'));
})
;
2026-01-23 15:09:50 +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 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.*'])
;
}
public function getDailyAmount(BudgetLimit $budgetLimit): string
{
$limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());
$days = $limitPeriod->length();
$amount = bcdiv($budgetLimit->amount, (string) $days, 12);
Log::debug(sprintf(
'Total amount for budget limit #%d is %s. Nr. of days is %d. Amount per day is %s',
$budgetLimit->id,
$budgetLimit->amount,
$days,
$amount
));
return $amount;
2019-08-30 08:09:13 +02:00
}
#[Override]
2024-12-22 08:43:12 +01:00
public function getNoteText(BudgetLimit $budgetLimit): string
{
return (string) $budgetLimit->notes()->first()?->text;
}
#[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();
2024-12-22 08:43:12 +01: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 */
$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) {
$currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
2019-08-30 09:19:29 +02:00
}
$currency->enabled = true;
2020-08-02 11:53:04 +02:00
$currency->save();
// find the budget:
/** @var null|Budget $budget */
$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.
$limit = $budget
2026-01-23 15:09:50 +01:00
->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
}
Log::debug('No existing budget limit, create a new one');
// this is a lame trick to communicate with the observer.
$singleton = PreferencesSingleton::getInstance();
$singleton->setPreference('fire_webhooks_bl_store', $data['fire_webhooks'] ?? true);
2019-08-30 09:19:29 +02:00
// or create one and return it.
$limit = new BudgetLimit();
2019-08-30 09:19:29 +02:00
$limit->budget()->associate($budget);
$limit->start_date = $data['start_date']->format('Y-m-d');
$limit->end_date = $data['end_date']->format('Y-m-d');
$limit->amount = $data['amount'];
$limit->generated = $data['generated'] ?? false;
$limit->period = $data['period'] ?? '';
2019-08-30 09:19:29 +02:00
$limit->transaction_currency_id = $currency->id;
$limit->save();
$noteText = (string) ($data['notes'] ?? '');
if ('' !== $noteText) {
$this->setNoteText($limit, $noteText);
}
Log::debug(sprintf('Created new budget limit with ID #%d and amount %s', $limit->id, $data['amount']));
$createWebhookMessages = $data['fire_webhooks'] ?? true;
2026-02-06 08:33:10 +01:00
event(new CreatedBudgetLimit($limit, $createWebhookMessages));
event(new WebhookMessagesRequestSending());
2023-06-21 12:34:58 +02:00
return $limit;
2024-12-22 08:43:12 +01:00
}
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
{
$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();
2024-11-06 11:57:12 +01:00
$budgetLimit->start_date_tz = $data['start']->format('e');
}
if (array_key_exists('end', $data)) {
$budgetLimit->end_date = $data['end']->endOfDay();
2024-11-06 11:57:12 +01:00
$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:
$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) {
$currency = $budgetLimit->transactionCurrency ?? Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
2019-08-30 09:19:29 +02:00
}
$currency->enabled = true;
2019-08-30 09:19:29 +02:00
$currency->save();
// this is a lame trick to communicate with the observer.
// FIXME so don't do that lol.
$singleton = PreferencesSingleton::getInstance();
$singleton->setPreference('fire_webhooks_bl_update', $data['fire_webhooks'] ?? true);
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']);
}
$generateMessages = $data['fire_webhooks'] ?? true;
2026-02-06 08:33:10 +01:00
event(new UpdatedBudgetLimit($budgetLimit, $generateMessages));
event(new WebhookMessagesRequestSending());
2019-08-30 09:19:29 +02:00
return $budgetLimit;
}
}