Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Clean up budget limit events.
James Cole264fec7a6a5a
diff --git a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php b/app/Api/V1/Controllers/Models/Transaction/UpdateController.phpindex 7c504e07dc..0f27f121e0 100644--- a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php+++ b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php@@ -93,9 +93,7 @@ class UpdateController extends Controller$flags->fireWebhooks = $fireWebhooks;$flags->recalculateCredit = $runRecalculations;event(new UpdatedSingleTransactionGroup($flags, $objects));- if($flags->fireWebhooks) {event(new WebhookMessagesRequestSending());- }/** @var User $admin */$admin = auth()->user();diff --git a/app/Handlers/Observer/BudgetLimitObserver.php b/app/Handlers/Observer/BudgetLimitObserver.phpindex c7fef71679..9ca31c3aec 100644--- a/app/Handlers/Observer/BudgetLimitObserver.php+++ b/app/Handlers/Observer/BudgetLimitObserver.php@@ -43,7 +43,6 @@ class BudgetLimitObserver{Log::debug('Observe "created" of a budget limit.');$this->updatePrimaryCurrencyAmount($budgetLimit);- //$this->updateAvailableBudget($budgetLimit);//$this->sendWebhookMessages('fire_webhooks_bl_store', WebhookTrigger::STORE_UPDATE_BUDGET_LIMIT, $budgetLimit);}@@ -51,7 +50,6 @@ class BudgetLimitObserver{Log::debug('Observe "updated" of a budget limit.');$this->updatePrimaryCurrencyAmount($budgetLimit);- //$this->updateAvailableBudget($budgetLimit);//$this->sendWebhookMessages('fire_webhooks_bl_update', WebhookTrigger::STORE_UPDATE_BUDGET_LIMIT, $budgetLimit);}diff --git a/app/Listeners/Model/BudgetLimit/RecalculatesAvailableBudgets.php b/app/Listeners/Model/BudgetLimit/RecalculatesAvailableBudgets.phpindex 1c963b8e53..43ff9bd261 100644--- a/app/Listeners/Model/BudgetLimit/RecalculatesAvailableBudgets.php+++ b/app/Listeners/Model/BudgetLimit/RecalculatesAvailableBudgets.php@@ -21,193 +21,39 @@namespace FireflyIII\Listeners\Model\BudgetLimit;-use Carbon\Carbon;use FireflyIII\Events\Model\BudgetLimit\CreatedBudgetLimit;use FireflyIII\Events\Model\BudgetLimit\DestroyedBudgetLimit;use FireflyIII\Events\Model\BudgetLimit\UpdatedBudgetLimit;-use FireflyIII\Models\AvailableBudget;-use FireflyIII\Models\BudgetLimit;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;use FireflyIII\Support\Facades\Amount;-use FireflyIII\Support\Facades\Navigation;-use FireflyIII\Support\Facades\Preferences;-use FireflyIII\User;+use FireflyIII\Support\Models\AvailableBudgetCalculator;use Illuminate\Contracts\Queue\ShouldQueue;-use Illuminate\Support\Facades\Log;-use Spatie\Period\Boundaries;-use Spatie\Period\Period;-use Spatie\Period\Precision;class RecalculatesAvailableBudgets implements ShouldQueue{- private AvailableBudgetRepositoryInterface $repository;- private BudgetLimitRepositoryInterface $blRepository;- private TransactionCurrency $currency;- private DestroyedBudgetLimit | CreatedBudgetLimit | UpdatedBudgetLimit $event;public function handle(DestroyedBudgetLimit | CreatedBudgetLimit | UpdatedBudgetLimit $event): void{- $this->event = $event;- $start = null;- $end = null;- $user = null;- if ($event instanceof DestroyedBudgetLimit) {- $start = $event->start->clone();- $end = $event->end->clone();- $user = $event->user;- $this->currency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup);- }- if (!($event instanceof DestroyedBudgetLimit)) {- $start = $event->budgetLimit->start_date->clone();- $end = $event->budgetLimit->end_date->clone();- $user = $event->budgetLimit->budget->user;- $this->currency = $event->budgetLimit->transactionCurrency;- }- if (null === $start || null === $end || null == $user) {- Log::error(sprintf('Cannot deal with event %s, because start and end are NULL.', get_class($event)));- return;- }- Log::debug(sprintf('Noticed event %s.', get_class($event)));- $this->refreshAvailableBudgets($user, $start, $end);- }-- private function calculateAmount(AvailableBudget $availableBudget): void- {- Log::debug(sprintf('Now in calculateAmount(#%d)', $availableBudget->id));- $newAmount = '0';- $period = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY());- Log::debug(sprintf('Now recalculating available budget #%d, (%s to %s)', $availableBudget->id, $availableBudget->start_date->format('Y-m-d'), $availableBudget->end_date->format('Y-m-d')));- // have to recalculate everything just in case.- $set = $this->blRepository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date);- Log::debug(sprintf('Found %d interesting budget limit(s).', $set->count()));-- /** @var BudgetLimit $budgetLimit */- foreach ($set as $budgetLimit) {- $newAmount = bcadd($newAmount, $this->getAmountFromBudgetLimit($budgetLimit, $period));- }- if (0 === bccomp('0', $newAmount)) {- Log::debug('New amount is zero, deleting AB.');- $availableBudget->delete();-- return;- }- Log::debug(sprintf('Concluded new amount for this AB must be %s', $newAmount));- $this->repository->update($availableBudget, ['amount' => $newAmount]);- }-- private function correctViewRange(string $viewRange): string- {- if ('MTD' === $viewRange) {- Log::debug(sprintf('Overrule %s to 1M', $viewRange));- return '1M';- }- if ('QTD' === $viewRange) {- Log::debug(sprintf('Overrule %s to 3M', $viewRange));- return '3M';- }- if ('YTD' === $viewRange) {- Log::debug(sprintf('Overrule %s to 1Y', $viewRange));- return '1Y';- }- return $viewRange;- }-- private function getAmountFromBudgetLimit(BudgetLimit $budgetLimit, Period $availableBudgetPeriod): string- {- Log::debug(sprintf('Found interesting budget limit #%d (%s to %s)', $budgetLimit->id, $budgetLimit->start_date->format('Y-m-d'), $budgetLimit->end_date->format('Y-m-d')));- // overlap in days:- $limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());- // if both equal each other, amount from this BL must be added to the AB- if ($limitPeriod->equals($availableBudgetPeriod)) {- Log::debug('This budget limit is equal to the available budget period.');- return (string)$budgetLimit->amount;- }- // if budget limit period is inside AB period, it can be added in full.- if (!$limitPeriod->equals($availableBudgetPeriod) && $availableBudgetPeriod->contains($limitPeriod)) {- Log::debug('This budget limit is smaller than the available budget period.');- return (string)$budgetLimit->amount;- }-- if (!$limitPeriod->equals($availableBudgetPeriod) && !$availableBudgetPeriod->contains($limitPeriod) && $availableBudgetPeriod->overlapsWith($limitPeriod)) {- Log::debug('This budget limit is something else entirely!');- $overlap = $availableBudgetPeriod->overlap($limitPeriod);- if ($overlap instanceof Period) {- $length = $overlap->length();- return bcmul($this->blRepository->getDailyAmount($budgetLimit), (string)$length);- }- }- return '0';- }-- private function refreshAvailableBudget(Carbon $start, string $viewRange): void- {- $end = Navigation::endOfPeriod($start, $viewRange);- Log::debug(sprintf('refreshAvailableBudget(%s, %s), end is %s', $start->format('Y-m-d'), $viewRange, $end->format('Y-m-d')));- $availableBudget = $this->repository->find($this->currency, $start, $end);-- if (null !== $availableBudget) {- Log::debug('Found available budget for this period, will update it.');- $this->calculateAmount($availableBudget);- return;- }- if ($this->event instanceof DestroyedBudgetLimit) {- Log::debug('Budget limit is deleted, but there was no available budget. Can stop here.');- return;- }- if ($end->lt($start)) {- Log::error(sprintf('%s is less than %s, stop.', $start->format('Y-m-d'), $end->format('Y-m-d')));+ if ($event instanceof DestroyedBudgetLimit && null !== $event->user) {+ // need to recalculate all available budgets for this user.+ $calculator = new AvailableBudgetCalculator();+ $calculator->setUser($event->user);+ $calculator->setStart($event->start->clone());+ $calculator->setEnd($event->end->clone());+ $calculator->setCreate(false);+ $calculator->setCurrency(Amount::getPrimaryCurrencyByUserGroup($event->user->userGroup));+ $calculator->recalculateByRange();return;}- Log::debug(sprintf('Will create new available budget for period %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d')));- $availableBudget = $this->repository->store(- [- 'start' => $start,- 'end' => $end,- 'currency_id' => $this->currency->id,- 'amount' => '1',- ]- );- Log::debug(sprintf('ID of new available budget is #%d', $availableBudget->id));- $this->calculateAmount($availableBudget);- }-- private function refreshAvailableBudgets(User $user, Carbon $start, Carbon $end): void- {- Log::debug(sprintf('Now in refreshAvailableBudget(%s, %s)', $start->format('Y-m-d'), $end->format('Y-m-d')));- $this->repository = app(AvailableBudgetRepositoryInterface::class);- $this->blRepository = app(BudgetLimitRepositoryInterface::class);- $this->repository->setUser($user);- $this->blRepository->setUser($user);- // based on the view range of the user (month week quarter etc) the budget limit could- // either overlap multiple available budget periods or be contained in a single one.- // all have to be created or updated.- $viewRange = Preferences::getForUser($user, 'viewRange', '1M')->data;- $viewRange = !is_string($viewRange) ? '1M' : $viewRange;- $viewRange = $this->correctViewRange($viewRange);-- $start = Navigation::startOfPeriod($start, $viewRange);- $end = Navigation::startOfPeriod($end, $viewRange);- $end = Navigation::endOfPeriod($end, $viewRange);-- if ($end < $start) {- [$start, $end] = [$end, $start];- }- Log::debug(sprintf('Corrected start to %s and end to %s.', $start->format('Y-m-d'), $end->format('Y-m-d')));-- // limit period in total is:- $limitPeriod = Period::make($start, $end, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());- Log::debug(sprintf('Limit period is from %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d')));-- // from the start until the end of the budget limit, need to loop!- $current = clone $start;- while ($current <= $end) {- $this->refreshAvailableBudget($current, $viewRange);- $current = Navigation::addPeriod($current, $viewRange);- }+ $calculator = new AvailableBudgetCalculator();+ $calculator->setUser($event->user);+ $calculator->setStart($event->budgetLimit->start_date->clone());+ $calculator->setEnd($event->budgetLimit->end_date->clone());+ $calculator->setCreate(true);+ $calculator->setCurrency($event->budgetLimit->transactionCurrency);+ $calculator->recalculateByRange();}--}diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.phpindex 7cffc377b9..d2efc9b69c 100644--- a/app/Repositories/Budget/AvailableBudgetRepository.php+++ b/app/Repositories/Budget/AvailableBudgetRepository.php@@ -27,6 +27,7 @@ namespace FireflyIII\Repositories\Budget;use Carbon\Carbon;use Deprecated;use FireflyIII\Models\AvailableBudget;+use FireflyIII\Models\BudgetLimit;use FireflyIII\Models\TransactionCurrency;use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface;@@ -34,6 +35,9 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait;use Illuminate\Database\Eloquent\Builder;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Log;+use Spatie\Period\Boundaries;+use Spatie\Period\Period;+use Spatie\Period\Precision;/*** Class AvailableBudgetRepository@@ -49,17 +53,17 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U/** @var AvailableBudget $availableBudget */foreach ($availableBudgets as $availableBudget) {- $start = $availableBudget->start_date->format('Y-m-d');- $end = $availableBudget->end_date->format('Y-m-d');- $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end);+ $start = $availableBudget->start_date->format('Y-m-d');+ $end = $availableBudget->end_date->format('Y-m-d');+ $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end);if (array_key_exists($key, $exists)) {Log::debug(sprintf(- 'Found duplicate AB: %s %s, %s-%s. Has been deleted',- $availableBudget->transaction_currency_id,- $availableBudget->amount,- $start,- $end- ));+ 'Found duplicate AB: %s %s, %s-%s. Has been deleted',+ $availableBudget->transaction_currency_id,+ $availableBudget->amount,+ $start,+ $end+ ));$availableBudget->delete();}$exists[$key] = true;@@ -71,7 +75,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U*/public function get(?Carbon $start = null, ?Carbon $end = null): Collection{- $query = $this->user->availableBudgets()->with(['transactionCurrency']);+ $query = $this->user->availableBudgets()->with(['transactionCurrency']);if ($start instanceof Carbon && $end instanceof Carbon) {$query->where(static function (Builder $q1) use ($start, $end): void {$q1->where('start_date', '=', $start->format('Y-m-d'));@@ -114,14 +118,13 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U->where('transaction_currency_id', $currency->id)->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))- ->first()- ;+ ->first();}#[Deprecated]public function getAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end): string{- $amount = '0';+ $amount = '0';/** @var null|AvailableBudget $availableBudget */$availableBudget = $this->user@@ -129,8 +132,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U->where('transaction_currency_id', $currency->id)->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))- ->first()- ;+ ->first();if (null !== $availableBudget) {return $availableBudget->amount;}@@ -146,8 +148,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U->availableBudgets()->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))- ->get()- ;+ ->get();Log::debug(sprintf('Found %d available budgets (already converted)', $availableBudgets->count()));@@ -162,7 +163,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U: $availableBudget->transaction_currency_id;$field = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? 'native_amount' : 'amount';$return[$currencyId] ??= '0';- $amount = '' === (string) $availableBudget->{$field} ? '0' : (string) $availableBudget->{$field};+ $amount = '' === (string)$availableBudget->{$field} ? '0' : (string)$availableBudget->{$field};$return[$currencyId] = bcadd($return[$currencyId], $amount);Log::debug(sprintf('Add #%d %s (%s) for a total of %s', $currencyId, $amount, $field, $return[$currencyId]));}@@ -178,8 +179,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, Ureturn $this->user->availableBudgets()->where('transaction_currency_id', $currency->id)- ->get()- ;+ ->get();}/**@@ -208,8 +208,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U->availableBudgets()->where('start_date', '=', $start->format('Y-m-d'))->where('end_date', '=', $end->format('Y-m-d'))- ->get()- ;+ ->get();}public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): ?AvailableBudget@@ -220,23 +219,21 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U->where('transaction_currency_id', $currency->id)->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))- ->first()- ;+ ->first();}#[Deprecated]public function setAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end, string $amount): AvailableBudget{/** @var null|AvailableBudget $availableBudget */- $availableBudget = $this->user+ $availableBudget = $this->user->availableBudgets()->where('transaction_currency_id', $currency->id)->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))- ->first()- ;+ ->first();if (null === $availableBudget) {- $availableBudget = new AvailableBudget();+ $availableBudget = new AvailableBudget();$availableBudget->user()->associate($this->user);$availableBudget->transactionCurrency()->associate($currency);$availableBudget->start_date = $start->startOfDay();@@ -256,21 +253,21 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, Uif ($start instanceof Carbon) {$start = $data['start']->startOfDay();}- $end = $data['end'];+ $end = $data['end'];if ($end instanceof Carbon) {$end = $data['end']->endOfDay();}return AvailableBudget::create([- 'user_id' => $this->user->id,- 'user_group_id' => $this->user->user_group_id,- 'transaction_currency_id' => $data['currency_id'],- 'amount' => $data['amount'],- 'start_date' => $start,- 'start_date_tz' => $start->format('e'),- 'end_date' => $end,- 'end_date_tz' => $end->format('e'),- ]);+ 'user_id' => $this->user->id,+ 'user_group_id' => $this->user->user_group_id,+ 'transaction_currency_id' => $data['currency_id'],+ 'amount' => $data['amount'],+ 'start_date' => $start,+ 'start_date_tz' => $start->format('e'),+ 'end_date' => $end,+ 'end_date_tz' => $end->format('e'),+ ]);}public function update(AvailableBudget $availableBudget, array $data): AvailableBudget@@ -315,4 +312,62 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, Ureturn $availableBudget;}++ #[\Override]+ public function recalculateAmount(AvailableBudget $availableBudget): void+ {+ Log::debug(sprintf('Now in recalculateAmount(#%d)', $availableBudget->id));+ $newAmount = '0';+ $period = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY());+ Log::debug(sprintf('Now recalculating available budget #%d, (%s to %s)', $availableBudget->id, $availableBudget->start_date->format('Y-m-d'), $availableBudget->end_date->format('Y-m-d')));+ // have to recalculate everything just in case.+ $blRepository = app(BudgetLimitRepositoryInterface::class);+ $blRepository->setUser($this->user);+ $set = $blRepository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date);+ Log::debug(sprintf('Found %d interesting budget limit(s).', $set->count()));++ /** @var BudgetLimit $budgetLimit */+ foreach ($set as $budgetLimit) {+ $newAmount = bcadd($newAmount, $this->getAmountFromBudgetLimit($budgetLimit, $period));+ }+ if (0 === bccomp('0', $newAmount)) {+ Log::debug('New amount is zero, deleting AB.');+ $availableBudget->delete();++ return;+ }+ Log::debug(sprintf('Concluded new amount for this AB must be %s', $newAmount));+ $this->update($availableBudget, ['amount' => $newAmount]);+ }+++ private function getAmountFromBudgetLimit(BudgetLimit $budgetLimit, Period $availableBudgetPeriod): string+ {+ $blRepository = app(BudgetLimitRepositoryInterface::class);+ $blRepository->setUser($this->user);++ Log::debug(sprintf('Found interesting budget limit #%d (%s to %s)', $budgetLimit->id, $budgetLimit->start_date->format('Y-m-d'), $budgetLimit->end_date->format('Y-m-d')));+ // overlap in days:+ $limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());+ // if both equal each other, amount from this BL must be added to the AB+ if ($limitPeriod->equals($availableBudgetPeriod)) {+ Log::debug('This budget limit is equal to the available budget period.');+ return (string)$budgetLimit->amount;+ }+ // if budget limit period is inside AB period, it can be added in full.+ if (!$limitPeriod->equals($availableBudgetPeriod) && $availableBudgetPeriod->contains($limitPeriod)) {+ Log::debug('This budget limit is smaller than the available budget period.');+ return (string)$budgetLimit->amount;+ }++ if (!$limitPeriod->equals($availableBudgetPeriod) && !$availableBudgetPeriod->contains($limitPeriod) && $availableBudgetPeriod->overlapsWith($limitPeriod)) {+ Log::debug('This budget limit is something else entirely!');+ $overlap = $availableBudgetPeriod->overlap($limitPeriod);+ if ($overlap instanceof Period) {+ $length = $overlap->length();+ return bcmul($blRepository->getDailyAmount($budgetLimit), (string)$length);+ }+ }+ return '0';+ }}diff --git a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.phpindex 46251e79d2..635c1d2cc7 100644--- a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php+++ b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php@@ -89,6 +89,8 @@ interface AvailableBudgetRepositoryInterface*/public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): ?AvailableBudget;+ public function recalculateAmount(AvailableBudget $availableBudget): void;+#[Deprecated]public function setAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end, string $amount): AvailableBudget;diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.phpindex 3afc0ec423..ed75d7d118 100644--- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php+++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php@@ -421,10 +421,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,$flags->fireWebhooks = $data['fire_webhooks'] ?? true;$flags->batchSubmission = $data['batch_submission'] ?? false;event(new CreatedSingleTransactionGroup($flags, $objects));- if($flags->fireWebhooks) {- Log::debug(sprintf('send event WebhookMessagesRequestSending from %s', __METHOD__));- event(new WebhookMessagesRequestSending());- }+ event(new WebhookMessagesRequestSending());return $transactionGroup;}diff --git a/app/Support/Models/AvailableBudgetCalculator.php b/app/Support/Models/AvailableBudgetCalculator.phpnew file mode 100644index 0000000000..8ae2f694fa--- /dev/null+++ b/app/Support/Models/AvailableBudgetCalculator.php@@ -0,0 +1,157 @@+<?php+/*+ * AvailableBudgetCalculator.php+ * Copyright (c) 2026 [email protected]+ *+ * 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.+ *+ * This program is distributed in the hope that it will be useful,+ * 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.+ *+ * 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/>.+ */++namespace FireflyIII\Support\Models;++use Carbon\Carbon;+use FireflyIII\Models\TransactionCurrency;+use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;+use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;+use FireflyIII\Support\Facades\Navigation;+use FireflyIII\Support\Facades\Preferences;+use FireflyIII\User;+use Illuminate\Support\Facades\Log;+use Spatie\Period\Boundaries;+use Spatie\Period\Period;+use Spatie\Period\Precision;++class AvailableBudgetCalculator+{+ private User $user;+ private bool $create = true;+ private Carbon $start;+ private Carbon $end;+ private string $viewRange;+ private TransactionCurrency $currency;++ private AvailableBudgetRepositoryInterface $abRepository;+ private BudgetLimitRepositoryInterface $blRepository;++ public function recalculateByRange(): void+ {+ Log::debug(sprintf('Now in recalculateByRange(%s, %s)', $this->start->format('Y-m-d'), $this->start->format('Y-m-d')));+ // based on the view range of the user (month week quarter etc) the budget limit could+ // either overlap multiple available budget periods or be contained in a single one.+ // all have to be created or updated.+ $start = Navigation::startOfPeriod($this->start, $this->viewRange);+ $end = Navigation::startOfPeriod($this->end, $this->viewRange);+ $end = Navigation::endOfPeriod($end, $this->viewRange);++ if ($end < $start) {+ [$start, $end] = [$end, $start];+ }+ Log::debug(sprintf('Corrected start to %s and end to %s.', $start->format('Y-m-d'), $end->format('Y-m-d')));++ // limit period in total is:+ $limitPeriod = Period::make($start, $end, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());+ Log::debug(sprintf('Limit period is from %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d')));++ // from the start until the end of the budget limit, need to loop!+ $current = clone $start;+ while ($current <= $end) {+ $this->refreshAvailableBudget($current);+ $current = Navigation::addPeriod($current, $this->viewRange);+ }+ }++ public function setUser(User $user): void+ {+ $this->user = $user;+ $this->abRepository = app(AvailableBudgetRepositoryInterface::class);+ $this->blRepository = app(BudgetLimitRepositoryInterface::class);+ $this->abRepository->setUser($user);+ $this->blRepository->setUser($user);++ $viewRange = Preferences::getForUser($user, 'viewRange', '1M')->data;+ $viewRange = !is_string($viewRange) ? '1M' : $viewRange;+ $this->viewRange = $this->correctViewRange($viewRange);++ }++ public function setEnd(Carbon $end): void+ {+ $this->end = $end;+ }++ public function setStart(Carbon $start): void+ {+ $this->start = $start;+ }++ public function setCurrency(TransactionCurrency $currency): void+ {+ $this->currency = $currency;+ }++ private function correctViewRange(string $viewRange): string+ {+ if ('MTD' === $viewRange) {+ Log::debug(sprintf('Overrule %s to 1M', $viewRange));+ return '1M';+ }+ if ('QTD' === $viewRange) {+ Log::debug(sprintf('Overrule %s to 3M', $viewRange));+ return '3M';+ }+ if ('YTD' === $viewRange) {+ Log::debug(sprintf('Overrule %s to 1Y', $viewRange));+ return '1Y';+ }+ return $viewRange;+ }++ private function refreshAvailableBudget(Carbon $start): void+ {+ $end = Navigation::endOfPeriod($start, $this->viewRange);+ Log::debug(sprintf('refreshAvailableBudget(%s), end is %s', $start->format('Y-m-d'), $end->format('Y-m-d')));+ $availableBudget = $this->abRepository->find($this->currency, $start, $end);++ if (null !== $availableBudget) {+ Log::debug('Found available budget for this period, will update it.');+ $this->abRepository->recalculateAmount($availableBudget);+ return;+ }+ if (!$this->create) {+ Log::debug('Can stop here. have not been asked to create an available budget.');+ return;+ }+ if ($end->lt($start)) {+ Log::error(sprintf('%s is less than %s, stop.', $start->format('Y-m-d'), $end->format('Y-m-d')));+ return;+ }+ Log::debug(sprintf('Will create new available budget for period %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d')));+ $availableBudget = $this->abRepository->store(+ [+ 'start' => $start,+ 'end' => $end,+ 'currency_id' => $this->currency->id,+ 'amount' => '1',+ ]+ );+ $this->abRepository->recalculateAmount($availableBudget);+ }++ public function setCreate(bool $create): void+ {+ $this->create = $create;+ }++}