Skip to content

Firefly III: a personal finances manager

Make sure that overlapping available budgets are also recalculated, this fixes #11685

James Colef6cd45a44ca1
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index 2025031907..2789d6da34 100644
--- a/app/Exceptions/Handler.php
+++ b/app/Exceptions/Handler.php
@@ -208,6 +208,7 @@ class Handler extends ExceptionHandler
}
Log::debug(sprintf('Error "%s" has no Firefly III treatment, parent will handle.', $e::class));
+ Log::error($e->getMessage());
return parent::render($request, $e);
}
diff --git a/app/Http/Controllers/System/InstallController.php b/app/Http/Controllers/System/InstallController.php
index c7270acf2e..7ec065af0e 100644
--- a/app/Http/Controllers/System/InstallController.php
+++ b/app/Http/Controllers/System/InstallController.php
@@ -39,7 +39,6 @@ use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Laravel\Passport\Passport;
use phpseclib3\Crypt\RSA;
-
use function Safe\file_put_contents;
/**
@@ -53,17 +52,19 @@ class InstallController extends Controller
public const string FORBIDDEN_ERROR = 'Internal PHP function "proc_close" is disabled for your installation. Auto-migration is not possible.';
public const string OTHER_ERROR = 'An unknown error prevented Firefly III from executing the upgrade commands. Sorry.';
- private string $lastError = '';
+ private string $lastError = '';
// empty on purpose.
- private array $upgradeCommands = [
- // there are 5 initial commands
- // Check 4 places: InstallController, Docker image, UpgradeDatabase, composer.json
- 'migrate' => ['--seed' => true, '--force' => true],
- 'generate-keys' => [], // an exception :(
- 'firefly-iii:upgrade-database' => [],
- 'firefly-iii:set-latest-version' => ['--james-is-cool' => true],
- 'firefly-iii:verify-security-alerts' => [],
- ];
+ private array $upgradeCommands
+ = [
+ // there are 5 initial commands
+ // Check 4 places: InstallController, Docker image, UpgradeDatabase, composer.json
+ 'firefly-iii:create-database' => [],
+ 'migrate' => ['--seed' => true, '--force' => true],
+ 'generate-keys' => [], // an exception :(
+ 'firefly-iii:upgrade-database' => [],
+ 'firefly-iii:set-latest-version' => ['--james-is-cool' => true],
+ 'firefly-iii:verify-security-alerts' => [],
+ ];
/**
* InstallController constructor.
@@ -78,13 +79,13 @@ class InstallController extends Controller
*
* @return Factory|View
*/
- public function index(): Factory|\Illuminate\Contracts\View\View
+ public function index(): Factory | \Illuminate\Contracts\View\View
{
app('view')->share('FF_VERSION', config('firefly.version'));
// index will set FF3 version.
- FireflyConfig::set('ff3_version', (string) config('firefly.version'));
- FireflyConfig::set('ff3_build_time', (int) config('firefly.build_time'));
+ FireflyConfig::set('ff3_version', (string)config('firefly.version'));
+ FireflyConfig::set('ff3_build_time', (int)config('firefly.build_time'));
return view('install.index');
}
@@ -94,7 +95,7 @@ class InstallController extends Controller
*/
public function keys(): void
{
- $key = RSA::createKey(4096);
+ $key = RSA::createKey(4096);
[$publicKey, $privateKey] = [Passport::keyPath('oauth-public.key'), Passport::keyPath('oauth-private.key')];
@@ -102,20 +103,20 @@ class InstallController extends Controller
return;
}
- file_put_contents($publicKey, (string) $key->getPublicKey());
+ file_put_contents($publicKey, (string)$key->getPublicKey());
file_put_contents($privateKey, $key->toString('PKCS1'));
}
public function runCommand(Request $request): JsonResponse
{
- $requestIndex = (int) $request->get('index');
- $response = ['hasNextCommand' => false, 'done' => true, 'previous' => null, 'error' => false, 'errorMessage' => null];
+ $requestIndex = (int)$request->get('index');
+ $response = ['hasNextCommand' => false, 'done' => true, 'previous' => null, 'error' => false, 'errorMessage' => null];
Log::debug(sprintf('Will now run commands. Request index is %d', $requestIndex));
- $indexes = array_keys($this->upgradeCommands);
+ $indexes = array_keys($this->upgradeCommands);
if (array_key_exists($requestIndex, $indexes)) {
- $command = $indexes[$requestIndex];
- $parameters = $this->upgradeCommands[$command];
+ $command = $indexes[$requestIndex];
+ $parameters = $this->upgradeCommands[$command];
Log::debug(sprintf('Will now execute command "%s" with parameters', $command), $parameters);
try {
diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php
index 94d950296d..34d6cb3168 100644
--- a/app/Repositories/Budget/AvailableBudgetRepository.php
+++ b/app/Repositories/Budget/AvailableBudgetRepository.php
@@ -54,17 +54,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;
@@ -96,8 +96,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();
}
public function findById(int $id): ?AvailableBudget
@@ -110,7 +109,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'));
@@ -126,7 +125,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
#[Deprecated]
public function getAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end): string
{
- $amount = '0';
+ $amount = '0';
/** @var null|AvailableBudget $availableBudget */
$availableBudget = $this->user
@@ -134,8 +133,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;
}
@@ -151,8 +149,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
return $this->user
->availableBudgets()
->where('transaction_currency_id', $currency->id)
- ->get()
- ;
+ ->get();
}
/**
@@ -181,8 +178,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 getAvailableBudgetWithCurrency(Carbon $start, Carbon $end): array
@@ -193,8 +189,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()));
@@ -209,7 +204,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]));
}
@@ -225,26 +220,25 @@ 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();
}
#[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());
+ $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')
- ));
+ '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);
+ $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 */
@@ -265,15 +259,14 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
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();
@@ -293,21 +286,21 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
if ($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
@@ -359,24 +352,24 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
$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')
- ));
+ '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());
+ $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;
+ 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;
+ return (string)$budgetLimit->amount;
}
if (
@@ -389,10 +382,26 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
if ($overlap instanceof Period) {
$length = $overlap->length();
- return bcmul($blRepository->getDailyAmount($budgetLimit), (string) $length);
+ return bcmul($blRepository->getDailyAmount($budgetLimit), (string)$length);
}
}
return '0';
}
+
+ #[\Override]
+ public function findInRange(TransactionCurrency $currency, Carbon $start, Carbon $end): Collection
+ {
+ /** @var null|AvailableBudget */
+ return $this->user
+ ->availableBudgets()
+ ->where('transaction_currency_id', $currency->id)
+
+ // start date OR end date must be the same or equal to start or END respectively.
+ ->where(function ($q1) use ($start, $end) {
+ $q1->whereBetween('start_date', [$start, $end]);
+ $q1->orWhereBetween('end_date', [$start, $end]);
+ })
+ ->get(['available_budgets.*']);
+ }
}
diff --git a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php
index 8e001f8cdc..36c5e9f64b 100644
--- a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php
+++ b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php
@@ -60,6 +60,11 @@ interface AvailableBudgetRepositoryInterface
*/
public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): ?AvailableBudget;
+ /**
+ * Find existing ABs in this exact time range.
+ */
+ public function findInRange(TransactionCurrency $currency, Carbon $start, Carbon $end): Collection;
+
public function findById(int $id): ?AvailableBudget;
/**
diff --git a/app/Support/Models/AvailableBudgetCalculator.php b/app/Support/Models/AvailableBudgetCalculator.php
index 6df237cb3e..5cf8da9380 100644
--- a/app/Support/Models/AvailableBudgetCalculator.php
+++ b/app/Support/Models/AvailableBudgetCalculator.php
@@ -38,15 +38,15 @@ use Spatie\Period\Precision;
class AvailableBudgetCalculator
{
- private User $user;
- private bool $create = true;
- private Carbon $start;
- private Carbon $end;
- private string $viewRange;
+ 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;
+ private BudgetLimitRepositoryInterface $blRepository;
public function recalculateByRange(): void
{
@@ -54,9 +54,9 @@ class AvailableBudgetCalculator
// 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);
+ $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];
@@ -68,7 +68,7 @@ class AvailableBudgetCalculator
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;
+ $current = clone $start;
while ($current <= $end) {
$this->refreshAvailableBudget($current);
$current = Navigation::addPeriod($current, $this->viewRange);
@@ -103,9 +103,9 @@ class AvailableBudgetCalculator
$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);
+ $viewRange = Preferences::getForUser($user, 'viewRange', '1M')->data;
+ $viewRange = !is_string($viewRange) ? '1M' : $viewRange;
+ $this->viewRange = $this->correctViewRange($viewRange);
}
private function correctViewRange(string $viewRange): string
@@ -131,33 +131,39 @@ class AvailableBudgetCalculator
private function refreshAvailableBudget(Carbon $start): void
{
- $end = Navigation::endOfPeriod($start, $this->viewRange);
+ $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);
+ if ($end->lt($start)) {
+ Log::error(sprintf('%s is less than %s, stop.', $start->format('Y-m-d'), $end->format('Y-m-d')));
return;
}
+
+ $availableBudget = $this->abRepository->find($this->currency, $start, $end);
+ $availableBudgets = $this->abRepository->findInRange($this->currency, $start, $end);
+
+ Log::debug(sprintf('Found #%d', $availableBudget->id));
+ foreach ($availableBudgets as $item) {
+ Log::debug(sprintf('findInRange found available budget #%d (%s - %s), will update it.', $item->id, $item->start_date->format('Y-m-d'), $item->end_date->format('Y-m-d')));
+ $this->abRepository->recalculateAmount($availableBudget);
+ }
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;
+ if (null === $availableBudget) {
+ 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);
}
- 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);
}
}