Compare commits

..

45 Commits

Author SHA1 Message Date
github-actions
aa5bde122e Auto commit for release 'branch-v6.2' on 2024-12-27 2024-12-27 12:43:57 +01:00
James Cole
0fa3c2bd8d Fix issue with prefilled piggy banks. 2024-12-27 12:39:26 +01:00
James Cole
b9249a4d96 Update commands. 2024-12-27 09:30:41 +01:00
James Cole
6638ca270f Merge branch 'v6.2' of github.com:firefly-iii/firefly-iii into v6.2 2024-12-27 07:36:37 +01:00
James Cole
9bfef892f8 Remove lots of debug logs 2024-12-27 07:36:30 +01:00
github-actions
32e5efec7c Auto commit for release 'branch-v6.2' on 2024-12-27 2024-12-27 07:29:17 +01:00
James Cole
36457455ca Rename and clean up commands. 2024-12-27 07:24:47 +01:00
James Cole
062c148e43 Rename all correction commands. 2024-12-27 06:56:08 +01:00
James Cole
2314ce8004 Refactor and renam commands. 2024-12-27 06:48:58 +01:00
James Cole
a3ff73903a Fix bad error message. 2024-12-27 05:44:03 +01:00
James Cole
7c8445707e Add moar debug. 2024-12-26 14:12:05 +01:00
James Cole
291e73da4b Rename bills to subscriptions 2024-12-26 13:41:57 +01:00
James Cole
286a29ca3e Display for bills. 2024-12-26 11:28:31 +01:00
github-actions
71cf6c6a5e Auto commit for release 'branch-v6.2' on 2024-12-26 2024-12-26 10:24:39 +01:00
James Cole
1e8f0adaf8 Fix broken account balance. 2024-12-26 10:20:40 +01:00
James Cole
33531244aa Merge branch 'v6.2' of github.com:firefly-iii/firefly-iii into v6.2
# Conflicts:
#	app/Http/Controllers/Chart/AccountController.php
#	app/Support/Steam.php
2024-12-26 09:19:04 +01:00
James Cole
06049a9a28 Update various pages, clean up some code. 2024-12-26 09:16:17 +01:00
James Cole
d313f5fdf5 Fix chart balance. 2024-12-26 08:53:16 +01:00
github-actions
f4868126c1 Auto commit for release 'branch-v6.2' on 2024-12-26 2024-12-26 05:25:46 +01:00
James Cole
00147e98dd Fix home chart. 2024-12-26 05:21:28 +01:00
James Cole
6d22663ca2 Fix charts and balances. 2024-12-26 05:11:32 +01:00
James Cole
756bb9cf5e Fix overview, skip chart for now. 2024-12-25 11:59:15 +01:00
James Cole
399d7968f5 Fix another null. 2024-12-25 08:30:00 +01:00
James Cole
966b68f42e Merge branch 'v6.2' of github.com:firefly-iii/firefly-iii into v6.2 2024-12-25 08:29:50 +01:00
James Cole
134c551c12 Remove some comments, add others. 2024-12-25 08:23:17 +01:00
github-actions
9aeca15355 Auto commit for release 'branch-v6.2' on 2024-12-25 2024-12-25 08:17:59 +01:00
James Cole
6c6d31830b Fix nullpointer 2024-12-25 08:14:07 +01:00
github-actions
e8cc321898 Auto commit for release 'branch-v6.2' on 2024-12-25 2024-12-25 07:13:41 +01:00
James Cole
e73fe06f7e Expand currency view in accounts. 2024-12-25 07:10:02 +01:00
James Cole
98b579c042 Fix native display. 2024-12-24 19:03:47 +01:00
James Cole
7b3a5c1afd Frontpage seems to be multi currency aware. 2024-12-24 16:56:31 +01:00
James Cole
7e2e49e129 Convert more charts. 2024-12-24 10:29:07 +01:00
James Cole
e8ef630424 Expand native amount things. 2024-12-24 06:34:12 +01:00
James Cole
8805bcf6f6 Various updates to display native/foreign amounts. 2024-12-23 17:32:15 +01:00
James Cole
ff5c9a3aa0 Merge branch 'v6.2' of github.com:firefly-iii/firefly-iii into v6.2 2024-12-23 14:35:34 +01:00
James Cole
3a274dcaa7 Little debug page with routes. 2024-12-23 14:35:27 +01:00
github-actions
ddfededf02 Auto commit for release 'branch-v6.2' on 2024-12-23 2024-12-23 08:40:29 +01:00
James Cole
e1785898ba Add notes to audit report. 2024-12-23 08:35:33 +01:00
James Cole
ae09200f42 Fix import 2024-12-23 08:26:35 +01:00
James Cole
847984f678 New rule triggers for account balance. 2024-12-23 08:22:54 +01:00
James Cole
42305672ac Merge branch 'v6.2' of github.com:firefly-iii/firefly-iii into v6.2 2024-12-23 07:14:12 +01:00
James Cole
25a56d9f72 Chart no longer as a line chart. 2024-12-23 07:13:59 +01:00
github-actions
8f9f08b96f Auto commit for release 'branch-v6.2' on 2024-12-23 2024-12-23 07:01:44 +01:00
James Cole
3c65b46aa5 Merge branch 'v6.2' of github.com:firefly-iii/firefly-iii into v6.2
# Conflicts:
#	app/Support/Steam.php
2024-12-23 06:56:31 +01:00
James Cole
1cf9c76329 Fix array bug. 2024-12-23 06:55:14 +01:00
200 changed files with 5371 additions and 4612 deletions

View File

@@ -30,8 +30,8 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Support\Facades\Steam;
use FireflyIII\Support\Http\Api\AccountFilter;
use FireflyIII\Support\Steam;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;

View File

@@ -116,7 +116,7 @@ class AccountController extends Controller
];
// TODO this code is also present in the V2 chart account controller so this method is due to be deprecated.
$currentStart = clone $start;
$range = app('steam')->finalAccountBalanceInRange($account, $start, clone $end);
$range = app('steam')->finalAccountBalanceInRange($account, $start, clone $end, $this->convertToNative);
// 2022-10-11 this method no longer converts to float.
$previous = array_values($range)[0];
while ($currentStart <= $end) {

View File

@@ -50,11 +50,12 @@ abstract class Controller extends BaseController
use DispatchesJobs;
use ValidatesRequests;
protected const string CONTENT_TYPE = 'application/vnd.api+json';
protected const string CONTENT_TYPE = 'application/vnd.api+json';
/** @var array<int, string> */
protected array $allowedSort;
protected ParameterBag $parameters;
protected bool $convertToNative = false;
/**
* Controller constructor.
@@ -67,8 +68,10 @@ abstract class Controller extends BaseController
function ($request, $next) {
$this->parameters = $this->getParameters();
if (auth()->check()) {
$language = app('steam')->getLanguage();
$language = app('steam')->getLanguage();
$this->convertToNative = app('preferences')->get('convert_to_native', false)->data;
app()->setLocale($language);
}
return $next($request);

View File

@@ -27,19 +27,21 @@ namespace FireflyIII\Api\V1\Controllers\Summary;
use Carbon\Carbon;
use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Data\DateRequest;
use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Report\NetWorthInterface;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Repositories\UserGroups\Currency\CurrencyRepositoryInterface;
use FireflyIII\Support\Facades\Amount;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
/**
* Class BasicController
@@ -120,48 +122,53 @@ class BasicController extends Controller
private function getBalanceInformation(Carbon $start, Carbon $end): array
{
// some config settings
$convertToNative = app('preferences')->get('convert_to_native', false)->data;
$default = app('amount')->getDefaultCurrency();
// prep some arrays:
$incomes = [];
$expenses = [];
$sums = [];
$return = [];
$incomes = [];
$expenses = [];
$sums = [];
$return = [];
// collect income of user using the new group collector.
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector->setRange($start, $end)->setPage($this->parameters->get('page'))->setTypes([TransactionTypeEnum::DEPOSIT->value]);
$set = $collector->getExtractedJournals();
$set = $collector->getExtractedJournals();
/** @var array $transactionJournal */
foreach ($set as $transactionJournal) {
$currencyId = (int) $transactionJournal['currency_id'];
/** @var array $journal */
foreach ($set as $journal) {
$currencyId = $convertToNative ? $default->id : (int) $journal['currency_id'];
$amount = Amount::getAmountFromJournal($journal);
$incomes[$currencyId] ??= '0';
$incomes[$currencyId] = bcadd(
$incomes[$currencyId],
bcmul($transactionJournal['amount'], '-1')
bcmul($amount, '-1')
);
$sums[$currencyId] ??= '0';
$sums[$currencyId] = bcadd($sums[$currencyId], bcmul($transactionJournal['amount'], '-1'));
$sums[$currencyId] = bcadd($sums[$currencyId], bcmul($amount, '-1'));
}
// collect expenses of user using the new group collector.
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector->setRange($start, $end)->setPage($this->parameters->get('page'))->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
$set = $collector->getExtractedJournals();
$set = $collector->getExtractedJournals();
/** @var array $transactionJournal */
foreach ($set as $transactionJournal) {
$currencyId = (int) $transactionJournal['currency_id'];
/** @var array $journal */
foreach ($set as $journal) {
$currencyId = $convertToNative ? $default->id : (int) $journal['currency_id'];
$amount = Amount::getAmountFromJournal($journal);
$expenses[$currencyId] ??= '0';
$expenses[$currencyId] = bcadd($expenses[$currencyId], $transactionJournal['amount']);
$expenses[$currencyId] = bcadd($expenses[$currencyId], $amount);
$sums[$currencyId] ??= '0';
$sums[$currencyId] = bcadd($sums[$currencyId], $transactionJournal['amount']);
$sums[$currencyId] = bcadd($sums[$currencyId], $amount);
}
// format amounts:
$keys = array_keys($sums);
$keys = array_keys($sums);
foreach ($keys as $currencyId) {
$currency = $this->currencyRepos->find($currencyId);
if (null === $currency) {
@@ -274,19 +281,22 @@ class BasicController extends Controller
$available = $this->abRepository->getAvailableBudgetWithCurrency($start, $end);
$budgets = $this->budgetRepository->getActiveBudgets();
$spent = $this->opsRepository->sumExpenses($start, $end, null, $budgets);
$days = (int) $today->diffInDays($end, true) + 1;
Log::debug(sprintf('Now in getLeftToSpendInfo("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
foreach ($spent as $row) {
// either an amount was budgeted or 0 is available.
$amount = (string) ($available[$row['currency_id']] ?? '0');
$currencyId = $row['currency_id'];
$amount = (string) ($available[$currencyId] ?? '0');
$spentInCurrency = $row['sum'];
$leftToSpend = bcadd($amount, $spentInCurrency);
$days = (int) $today->diffInDays($end, true) + 1;
$perDay = '0';
if (0 !== $days && bccomp($leftToSpend, '0') > -1) {
$perDay = bcdiv($leftToSpend, (string) $days);
}
Log::debug(sprintf('Spent %s %s', $row['currency_code'], $row['sum']));
$return[] = [
'key' => sprintf('left-to-spend-in-%s', $row['currency_code']),
'title' => trans('firefly.box_left_to_spend_in_currency', ['currency' => $row['currency_symbol']]),
@@ -311,9 +321,11 @@ class BasicController extends Controller
private function getNetWorthInfo(Carbon $start, Carbon $end): array
{
Log::debug('getNetWorthInfo');
/** @var User $user */
$user = auth()->user();
$date = today(config('app.timezone'))->startOfDay();
$date = now(config('app.timezone'));
// start and end in the future? use $end
if ($this->notInDateRange($date, $start, $end)) {
/** @var Carbon $date */
@@ -323,9 +335,7 @@ class BasicController extends Controller
/** @var NetWorthInterface $netWorthHelper */
$netWorthHelper = app(NetWorthInterface::class);
$netWorthHelper->setUser($user);
$allAccounts = $this->accountRepository->getActiveAccountsByType(
[AccountType::ASSET, AccountType::DEFAULT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::DEBT]
);
$allAccounts = $this->accountRepository->getActiveAccountsByType([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value]);
// filter list on preference of being included.
$filtered = $allAccounts->filter(
@@ -360,6 +370,7 @@ class BasicController extends Controller
'sub_title' => '',
];
}
Log::debug('End of getNetWorthInfo');
return $return;
}

View File

@@ -118,7 +118,7 @@ class AccountController extends Controller
'native_entries' => [],
];
$currentStart = clone $params['start'];
$range = app('steam')->finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $currency);
$range = app('steam')->finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToNative);
$previous = array_values($range)[0]['balance'];
$previousNative = array_values($range)[0]['native_balance'];

View File

@@ -54,9 +54,10 @@ class Controller extends BaseController
{
use ValidatesUserGroupTrait;
protected const string CONTENT_TYPE = 'application/vnd.api+json';
protected array $acceptedRoles = [UserRoleEnum::READ_ONLY];
protected const string CONTENT_TYPE = 'application/vnd.api+json';
protected array $acceptedRoles = [UserRoleEnum::READ_ONLY];
protected ParameterBag $parameters;
protected bool $convertToNative = false;
public function __construct()
{

View File

@@ -1,5 +1,25 @@
<?php
/*
* ConvertsDatesToUTC.php
* Copyright (c) 2024 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.
*
* 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/.
*/
declare(strict_types=1);
/*
* ConvertDatesToUTC.php
@@ -21,7 +41,7 @@ declare(strict_types=1);
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
namespace FireflyIII\Console\Commands\Integrity;
namespace FireflyIII\Console\Commands\Correction;
use Carbon\Carbon;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
@@ -31,7 +51,7 @@ use Illuminate\Database\QueryException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
class ConvertDatesToUTC extends Command
class ConvertsDatesToUTC extends Command
{
use ShowsFriendlyMessages;
@@ -47,13 +67,17 @@ class ConvertDatesToUTC extends Command
*
* @var string
*/
protected $signature = 'firefly-iii:migrate-to-utc';
protected $signature = 'correction:convert-to-utc';
/**
* Execute the console command.
*/
public function handle(): int
{
$this->friendlyWarning('Please do not use this command.');
return 0;
/**
* @var string $model
* @var array $fields

View File

@@ -4,10 +4,6 @@ namespace FireflyIII\Console\Commands\Correction;
use Illuminate\Console\Command;
/**
* Class CorrectionSkeleton
* TODO DONT FORGET TO ADD THIS TO THE DOCKER BUILD
*/
class CorrectionSkeleton extends Command
{
use ShowsFriendlyMessages;

View File

@@ -29,15 +29,12 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class FixAccountOrder
*/
class FixAccountOrder extends Command
class CorrectsAccountOrder extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Make sure account order is correct.';
protected $signature = 'firefly-iii:fix-account-order';
protected $signature = 'correction:account-order';
private AccountRepositoryInterface $repository;
@@ -54,8 +51,6 @@ class FixAccountOrder extends Command
$this->repository->resetAccountOrder();
}
$this->friendlyPositive('All accounts are ordered correctly');
return 0;
}

View File

@@ -36,15 +36,12 @@ use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
/**
* Class FixAccountTypes
*/
class FixAccountTypes extends Command
class CorrectsAccountTypes extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Make sure all journals have the correct from/to account types.';
protected $signature = 'firefly-iii:fix-account-types';
protected $signature = 'correction:account-types';
private int $count;
private array $expected;
private AccountFactory $factory;
@@ -120,9 +117,6 @@ class FixAccountTypes extends Command
}
}
}
if (0 === $this->count) {
$this->friendlyPositive('All account types are OK');
}
if (0 !== $this->count) {
app('log')->debug(sprintf('%d journals had to be fixed.', $this->count));
$this->friendlyInfo(sprintf('Acted on %d transaction(s)', $this->count));

View File

@@ -36,15 +36,12 @@ use FireflyIII\Models\RuleTrigger;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Class ReportSkeleton
*/
class CorrectAmounts extends Command
class CorrectsAmounts extends Command
{
use ShowsFriendlyMessages;
protected $description = 'This command makes sure positive and negative amounts are recorded correctly.';
protected $signature = 'firefly-iii:fix-amount-pos-neg';
protected $signature = 'correction:amounts';
public function handle(): int
{
@@ -72,7 +69,6 @@ class CorrectAmounts extends Command
{
$count = AutoBudget::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]);
if (0 === $count) {
$this->friendlyPositive('All auto budget amounts are positive.');
return;
}
@@ -83,7 +79,6 @@ class CorrectAmounts extends Command
{
$count = AvailableBudget::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]);
if (0 === $count) {
$this->friendlyPositive('All available budget amounts are positive.');
return;
}
@@ -96,7 +91,6 @@ class CorrectAmounts extends Command
$count += Bill::where('amount_max', '<', 0)->update(['amount_max' => DB::raw('amount_max * -1')]);
$count += Bill::where('amount_min', '<', 0)->update(['amount_min' => DB::raw('amount_min * -1')]);
if (0 === $count) {
$this->friendlyPositive('All bill amounts are positive.');
return;
}
@@ -107,7 +101,6 @@ class CorrectAmounts extends Command
{
$count = BudgetLimit::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]);
if (0 === $count) {
$this->friendlyPositive('All budget limit amounts are positive.');
return;
}
@@ -118,7 +111,6 @@ class CorrectAmounts extends Command
{
$count = CurrencyExchangeRate::where('rate', '<', 0)->update(['rate' => DB::raw('rate * -1')]);
if (0 === $count) {
$this->friendlyPositive('All currency exchange rates are positive.');
return;
}
@@ -129,7 +121,6 @@ class CorrectAmounts extends Command
{
$count = PiggyBank::where('target_amount', '<', 0)->update(['target_amount' => DB::raw('target_amount * -1')]);
if (0 === $count) {
$this->friendlyPositive('All piggy bank amounts are positive.');
return;
}
@@ -142,7 +133,6 @@ class CorrectAmounts extends Command
$count += RecurrenceTransaction::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]);
$count += RecurrenceTransaction::where('foreign_amount', '<', 0)->update(['foreign_amount' => DB::raw('foreign_amount * -1')]);
if (0 === $count) {
$this->friendlyPositive('All recurring transaction amounts are positive.');
return;
}
@@ -165,7 +155,6 @@ class CorrectAmounts extends Command
}
}
if (0 === $fixed) {
$this->friendlyPositive('All rule trigger amounts are positive.');
return;
}

View File

@@ -37,15 +37,12 @@ use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Console\Command\Command as CommandAlias;
/**
* Class EnableCurrencies
*/
class EnableCurrencies extends Command
class CorrectsCurrencies extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Enables all currencies in use.';
protected $signature = 'firefly-iii:enable-currencies';
protected $signature = 'correction:currencies';
/**
* Execute the console command.

View File

@@ -27,14 +27,11 @@ namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
/**
* Class CorrectDatabase
*/
class CorrectDatabase extends Command
class CorrectsDatabase extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Will correct the integrity of your database, if necessary.';
protected $description = 'Will validate and correct the integrity of your database, if necessary.';
protected $signature = 'firefly-iii:correct-database';
/**
@@ -49,32 +46,36 @@ class CorrectDatabase extends Command
return 1;
}
$commands = [
'firefly-iii:fix-piggies',
'firefly-iii:create-link-types',
'firefly-iii:create-access-tokens',
'firefly-iii:remove-bills',
'firefly-iii:fix-amount-pos-neg',
'firefly-iii:enable-currencies',
'firefly-iii:fix-transfer-budgets',
'firefly-iii:fix-uneven-amount',
'firefly-iii:delete-zero-amount',
'firefly-iii:delete-orphaned-transactions',
'firefly-iii:delete-empty-journals',
'firefly-iii:delete-empty-groups',
'firefly-iii:fix-account-types',
'firefly-iii:fix-ibans',
'firefly-iii:fix-account-order',
'firefly-iii:rename-meta-fields',
'firefly-iii:fix-ob-currencies',
'firefly-iii:fix-long-descriptions',
'firefly-iii:fix-recurring-transactions',
'firefly-iii:upgrade-group-information',
// 'firefly-iii:fix-transaction-types', // very resource heavy.
'firefly-iii:fix-frontpage-accounts',
// new!
'firefly-iii:unify-group-accounts',
'firefly-iii:trigger-credit-recalculation',
'firefly-iii:migrate-preferences',
'correction:restore-oauth-keys',
'correction:timezones',
'correction:create-group-memberships',
'correction:group-information',
'correction:piggy-banks',
'correction:link-types',
'correction:access-tokens',
'correction:bills',
'correction:amounts',
'correction:currencies',
'correction:transfer-budgets',
'correction:uneven-amounts',
'correction:zero-amounts',
'correction:orphaned-transactions',
'correction:empty-journals',
'correction:empty-groups',
'correction:account-types',
'correction:ibans',
'correction:account-order',
'correction:meta-fields',
'correction:opening-balance-currencies',
'correction:long-descriptions',
'correction:recurring-transactions',
'correction:frontpage-accounts',
'correction:group-accounts',
'correction:recalculates-liabilities',
'correction:preferences',
// 'correction:transaction-types', // resource heavy, disabled.
// 'correction:recalculate-native-amounts', // not necessary, disabled.
'firefly-iii:report-integrity',
];
foreach ($commands as $command) {
$this->friendlyLine(sprintf('Now executing command "%s"', $command));

View File

@@ -31,15 +31,12 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class FixFrontpageAccounts
*/
class FixFrontpageAccounts extends Command
class CorrectsFrontpageAccounts extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Fixes a preference that may include deleted accounts or accounts of another type.';
protected $signature = 'firefly-iii:fix-frontpage-accounts';
protected $signature = 'correction:frontpage-accounts';
/**
* Execute the console command.
@@ -55,7 +52,6 @@ class FixFrontpageAccounts extends Command
$this->fixPreference($preference);
}
}
$this->friendlyPositive('Account preferences are OK');
return 0;
}

View File

@@ -31,15 +31,12 @@ use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
/**
* Class FixGroupAccounts
*/
class FixGroupAccounts extends Command
class CorrectsGroupAccounts extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Unify the source / destination accounts of split groups.';
protected $signature = 'firefly-iii:unify-group-accounts';
protected $signature = 'correction:group-accounts';
/**
* Execute the console command.
@@ -64,8 +61,6 @@ class FixGroupAccounts extends Command
$handler->unifyAccounts($event);
}
$this->friendlyPositive('Updated possible inconsistent transaction groups.');
return 0;
}
}

View File

@@ -1,8 +1,8 @@
<?php
/*
* UpdateGroupInformation.php
* Copyright (c) 2022 james@firefly-iii.org
* CorrectsGroupInformation.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
@@ -17,12 +17,12 @@
* 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/>.
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Console\Commands\Integrity;
namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\Account;
@@ -45,15 +45,12 @@ use FireflyIII\User;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
/**
* Class UpdateGroupInformation
*/
class UpdateGroupInformation extends Command
class CorrectsGroupInformation extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Makes sure that every object is linked to a group';
protected $signature = 'firefly-iii:upgrade-group-information';
protected $signature = 'correction:group-information';
/**
* Execute the console command.

View File

@@ -30,15 +30,12 @@ use FireflyIII\Models\AccountType;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
/**
* Class FixIbans
*/
class FixIbans extends Command
class CorrectsIbans extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Removes spaces from IBANs';
protected $signature = 'firefly-iii:fix-ibans';
protected $signature = 'correction:ibans';
private int $count = 0;
/**
@@ -49,9 +46,6 @@ class FixIbans extends Command
$accounts = Account::whereNotNull('iban')->get();
$this->filterIbans($accounts);
$this->countAndCorrectIbans($accounts);
if (0 === $this->count) {
$this->friendlyPositive('All IBANs are valid.');
}
return 0;
}

View File

@@ -28,24 +28,22 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Class FixLongDescriptions
*/
class FixLongDescriptions extends Command
class CorrectsLongDescriptions extends Command
{
use ShowsFriendlyMessages;
private const int MAX_LENGTH = 1000;
protected $description = 'Fixes long descriptions in journals and groups.';
protected $signature = 'firefly-iii:fix-long-descriptions';
protected $signature = 'correction:long-descriptions';
/**
* Execute the console command.
*/
public function handle(): int
{
$journals = TransactionJournal::get(['id', 'description']);
$journals = TransactionJournal::where(DB::raw('LENGTH(description)'), '>', self::MAX_LENGTH)->get(['id', 'description']);
$count = 0;
/** @var TransactionJournal $journal */
@@ -58,7 +56,7 @@ class FixLongDescriptions extends Command
}
}
$groups = TransactionGroup::get(['id', 'title']);
$groups = TransactionGroup::where(DB::raw('LENGTH(title)'), '>', self::MAX_LENGTH)->get(['id', 'title']);
/** @var TransactionGroup $group */
foreach ($groups as $group) {
@@ -69,9 +67,6 @@ class FixLongDescriptions extends Command
++$count;
}
}
if (0 === $count) {
$this->friendlyPositive('All transaction group and journal title lengths are within bounds.');
}
return 0;
}

View File

@@ -26,16 +26,14 @@ namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Class RenameMetaFields
*/
class RenameMetaFields extends Command
class CorrectsMetaDataFields extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Rename changed meta fields.';
protected $signature = 'firefly-iii:rename-meta-fields';
protected $signature = 'correction:meta-fields';
private int $count = 0;
@@ -61,9 +59,6 @@ class RenameMetaFields extends Command
foreach ($changes as $original => $update) {
$this->rename($original, $update);
}
if (0 === $this->count) {
$this->friendlyPositive('All meta fields are correct.');
}
if (0 !== $this->count) {
$this->friendlyInfo(sprintf('Renamed %d meta field(s).', $this->count));
}
@@ -73,7 +68,7 @@ class RenameMetaFields extends Command
private function rename(string $original, string $update): void
{
$total = \DB::table('journal_meta')
$total = DB::table('journal_meta')
->where('name', '=', $original)
->update(['name' => $update])
;

View File

@@ -46,13 +46,13 @@ use Illuminate\Database\Query\Builder as DatabaseBuilder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class RecalculateNativeAmounts extends Command
class CorrectsNativeAmounts extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Recalculate native amounts for all objects.';
protected $signature = 'firefly-iii:recalculate-native-amounts';
protected $signature = 'correction:recalculate-native-amounts';
/**
* Execute the console command.
@@ -102,12 +102,13 @@ class RecalculateNativeAmounts extends Command
foreach ($set as $account) {
$account->touch();
}
Log::debug(sprintf('Recalculated %d accounts', $set->count()));
Log::debug(sprintf('Recalculated %d accounts for user group #%d.', $set->count(), $userGroup->id));
}
private function recalculatePiggyBanks(UserGroup $userGroup, TransactionCurrency $currency): void
{
$converter = new ExchangeRateConverter();
$converter->setUserGroup($userGroup);
$converter->setIgnoreSettings(true);
$repository = app(PiggyBankRepositoryInterface::class);
$repository->setUserGroup($userGroup);
@@ -130,7 +131,7 @@ class RecalculateNativeAmounts extends Command
}
$this->recalculatePiggyBankEvents($piggyBank);
}
Log::debug(sprintf('Recalculated %d piggy banks.', $set->count()));
Log::debug(sprintf('Recalculated %d piggy banks for user group #%d.', $set->count(), $userGroup->id));
}
@@ -167,7 +168,7 @@ class RecalculateNativeAmounts extends Command
$limit->touch();
Log::debug(sprintf('Done with touch BL #%d', $limit->id));
}
Log::debug(sprintf('Recalculated %d budget limits.', $set->count()));
Log::debug(sprintf('Recalculated %d budget limits for budget #%d.', $set->count(), $budget->id));
}
private function recalculateAutoBudgets(Budget $budget, TransactionCurrency $currency): void
@@ -178,7 +179,7 @@ class RecalculateNativeAmounts extends Command
foreach ($set as $autoBudget) {
$autoBudget->touch();
}
Log::debug(sprintf('Recalculated %d auto budgets.', $set->count()));
Log::debug(sprintf('Recalculated %d auto budgets for budget #%d.', $set->count(), $budget->id));
}
private function recalculateAvailableBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
@@ -210,11 +211,19 @@ class RecalculateNativeAmounts extends Command
$set = DB::table('transactions')
->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.user_group_id', $userGroup->id)
->where(static function (DatabaseBuilder $q) use ($currency): void {
$q->whereNot('transactions.transaction_currency_id', $currency->id)
->orWhereNot('transactions.foreign_currency_id', $currency->id)
;
->where(function (DatabaseBuilder $q1) use ($currency): void {
$q1->where(function (DatabaseBuilder $q2) use ($currency): void {
$q2->whereNot('transactions.transaction_currency_id', $currency->id)->whereNull('transactions.foreign_currency_id');
})->orWhere(function (DatabaseBuilder $q3) use ($currency): void {
$q3->whereNot('transactions.transaction_currency_id', $currency->id)->whereNot('transactions.foreign_currency_id', $currency->id);
});
})
// ->where(static function (DatabaseBuilder $q) use ($currency): void {
// $q->whereNot('transactions.transaction_currency_id', $currency->id)
// ->whereNot('transactions.foreign_currency_id', $currency->id)
// ;
// })
->get(['transactions.id'])
;
TransactionObserver::$recalculate = false;

View File

@@ -35,15 +35,12 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
/**
* Class CorrectOpeningBalanceCurrencies
*/
class CorrectOpeningBalanceCurrencies extends Command
class CorrectsOpeningBalanceCurrencies extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Will make sure that opening balance transaction currencies match the account they\'re for.';
protected $signature = 'firefly-iii:fix-ob-currencies';
protected $signature = 'correction:opening-balance-currencies';
/**
* Execute the console command.
@@ -62,10 +59,6 @@ class CorrectOpeningBalanceCurrencies extends Command
$message = sprintf('Corrected %d opening balance transaction(s).', $count);
$this->friendlyInfo($message);
}
if (0 === $count) {
$message = 'There was nothing to fix in the opening balance transactions.';
$this->friendlyPositive($message);
}
return 0;
}

View File

@@ -29,17 +29,12 @@ use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
/**
* Report (and fix) piggy banks.
*
* Class FixPiggies
*/
class FixPiggies extends Command
class CorrectsPiggyBanks extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Fixes common issues with piggy banks.';
protected $signature = 'firefly-iii:fix-piggies';
protected $signature = 'correction:piggy-banks';
/**
* Execute the console command.
@@ -66,9 +61,6 @@ class FixPiggies extends Command
continue;
}
}
if (0 === $count) {
$this->friendlyPositive('All piggy bank events are OK.');
}
if (0 !== $count) {
$this->friendlyInfo(sprintf('Fixed %d piggy bank event(s).', $count));
}

View File

@@ -28,11 +28,11 @@ use FireflyIII\User;
use Illuminate\Console\Command;
use Symfony\Component\Console\Command\Command as CommandAlias;
class MigratePreferences extends Command
class CorrectsPreferences extends Command
{
protected $description = 'Give Firefly III preferences a user group ID so they can be made administration specific.';
protected $signature = 'firefly-iii:migrate-preferences';
protected $signature = 'correction:preferences';
/**
* Execute the console command.
@@ -50,7 +50,7 @@ class MigratePreferences extends Command
if (null === $preference) {
continue;
}
if (null !== $preference->user_group_id) {
if (null === $preference->user_group_id) {
$preference->user_group_id = $user->user_group_id;
$preference->save();
++$count;

View File

@@ -33,15 +33,12 @@ use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class FixRecurringTransactions
*/
class FixRecurringTransactions extends Command
class CorrectsRecurringTransactions extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Fixes recurring transactions with the wrong transaction type.';
protected $signature = 'firefly-iii:fix-recurring-transactions';
protected $signature = 'correction:recurring-transactions';
private int $count = 0;
private RecurringRepositoryInterface $recurringRepos;
private UserRepositoryInterface $userRepos;
@@ -53,9 +50,6 @@ class FixRecurringTransactions extends Command
{
$this->stupidLaravel();
$this->correctTransactions();
if (0 === $this->count) {
$this->friendlyPositive('All recurring transactions are OK.');
}
return 0;
}

View File

@@ -1,5 +1,25 @@
<?php
/*
* CorrectsTimezoneInformation.php
* Copyright (c) 2024 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.
*
* 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/.
*/
declare(strict_types=1);
/*
* AddTimezonesToDates.php
@@ -21,7 +41,7 @@ declare(strict_types=1);
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
namespace FireflyIII\Console\Commands\Integrity;
namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\AccountBalance;
@@ -41,7 +61,7 @@ use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;
class AddTimezonesToDates extends Command
class CorrectsTimezoneInformation extends Command
{
use ShowsFriendlyMessages;
@@ -73,7 +93,7 @@ class AddTimezonesToDates extends Command
*
* @var string
*/
protected $signature = 'firefly-iii:add-timezones-to-dates';
protected $signature = 'correction:timezones';
/**
* Execute the console command.
@@ -107,8 +127,6 @@ class AddTimezonesToDates extends Command
Log::error($e->getMessage());
}
if (0 === $count) {
$this->friendlyPositive(sprintf('Timezone information is present in field "%s" of model "%s".', $field, $shortModel));
return;
}
$this->friendlyInfo(sprintf('Adding timezone information to field "%s" of model "%s".', $field, $shortModel));

View File

@@ -34,15 +34,12 @@ use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
/**
* Class FixTransactionTypes
*/
class FixTransactionTypes extends Command
class CorrectsTransactionTypes extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Make sure all transactions are of the correct type, based on source + dest.';
protected $signature = 'firefly-iii:fix-transaction-types';
protected $signature = 'correction:transaction-types';
/**
* Execute the console command.

View File

@@ -29,15 +29,12 @@ use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use Illuminate\Console\Command;
/**
* Class TransferBudgets
*/
class TransferBudgets extends Command
class CorrectsTransferBudgets extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Removes budgets from transfers.';
protected $signature = 'firefly-iii:fix-transfer-budgets';
protected $signature = 'correction:transfer-budgets';
/**
* Execute the console command.
@@ -60,10 +57,6 @@ class TransferBudgets extends Command
$entry->budgets()->sync([]);
++$count;
}
if (0 === $count) {
$message = 'No invalid budget/journal entries.';
$this->friendlyPositive($message);
}
if (0 !== $count) {
$message = sprintf('Corrected %d invalid budget/journal entries (entry).', $count);
app('log')->debug($message);

View File

@@ -33,15 +33,12 @@ use FireflyIII\Support\Models\AccountBalanceCalculator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
/**
* Class FixUnevenAmount
*/
class FixUnevenAmount extends Command
class CorrectsUnevenAmount extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Fix journals with uneven amounts.';
protected $signature = 'firefly-iii:fix-uneven-amount';
protected $signature = 'correction:uneven-amounts';
private int $count;
/**
@@ -118,11 +115,6 @@ class FixUnevenAmount extends Command
++$count;
}
}
if (0 === $count) {
$this->friendlyPositive('No "old style" foreign currency transfers.');
return;
}
}
private function fixUnevenAmounts(): void
@@ -164,9 +156,6 @@ class FixUnevenAmount extends Command
$this->fixJournal($entry->transaction_journal_id);
}
}
if (0 === $this->count) {
$this->friendlyPositive('Database amount integrity is OK');
}
}
private function fixJournal(int $param): void
@@ -291,8 +280,6 @@ class FixUnevenAmount extends Command
Log::debug(sprintf('Can skip foreign currency transfer #%d.', $journal->id));
}
if (0 === $count) {
$this->friendlyPositive('Journal currency integrity is OK');
return;
}

View File

@@ -29,16 +29,13 @@ use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class CreateAccessTokens
*/
class CreateAccessTokens extends Command
class CreatesAccessTokens extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Creates user access tokens which are used for command line access to personal data.';
protected $signature = 'firefly-iii:create-access-tokens';
protected $signature = 'correction:access-tokens';
/**
* Execute the console command.
@@ -64,9 +61,6 @@ class CreateAccessTokens extends Command
++$count;
}
}
if (0 === $count) {
$this->friendlyPositive('Verified access tokens.');
}
return 0;
}

View File

@@ -1,8 +1,8 @@
<?php
/*
* CreateGroupMemberships.php
* Copyright (c) 2023 james@firefly-iii.org
* CreatesGroupMemberships.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
@@ -17,12 +17,12 @@
* 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/>.
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Console\Commands\Integrity;
namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Enums\UserRoleEnum;
@@ -33,16 +33,13 @@ use FireflyIII\Models\UserRole;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class CreateGroupMemberships
*/
class CreateGroupMemberships extends Command
class CreatesGroupMemberships extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '560_create_group_memberships';
protected $description = 'Update group memberships';
protected $signature = 'firefly-iii:create-group-memberships';
protected $signature = 'correction:create-group-memberships';
/**
* Execute the console command.
@@ -52,7 +49,6 @@ class CreateGroupMemberships extends Command
public function handle(): int
{
$this->createGroupMemberships();
$this->friendlyPositive('Validated group memberships');
return 0;
}

View File

@@ -28,16 +28,13 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\LinkType;
use Illuminate\Console\Command;
/**
* Class CreateLinkTypes. Created all link types in case a migration hasn't fired.
*/
class CreateLinkTypes extends Command
class CreatesLinkTypes extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Creates all link types.';
protected $signature = 'firefly-iii:create-link-types';
protected $signature = 'correction:link-types';
/**
* Execute the console command.
@@ -66,9 +63,6 @@ class CreateLinkTypes extends Command
$link->editable = false;
$link->save();
}
if (0 === $count) {
$this->friendlyPositive('All link types are OK');
}
return 0;
}

View File

@@ -29,15 +29,12 @@ use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use Illuminate\Console\Command;
/**
* Class RemoveBills
*/
class RemoveBills extends Command
class RemovesBills extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Remove bills from transactions that shouldn\'t have one.';
protected $signature = 'firefly-iii:remove-bills';
protected $signature = 'correction:bills';
/**
* Execute the console command.
@@ -60,7 +57,6 @@ class RemoveBills extends Command
if ($journals->count() > 0) {
$this->friendlyInfo('Fixed all transaction journals so they have correct bill information.');
}
$this->friendlyPositive('All bills and journals are OK');
return 0;
}

View File

@@ -29,15 +29,12 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\TransactionGroup;
use Illuminate\Console\Command;
/**
* Class DeleteEmptyGroups
*/
class DeleteEmptyGroups extends Command
class RemovesEmptyGroups extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Delete empty transaction groups.';
protected $signature = 'firefly-iii:delete-empty-groups';
protected $signature = 'correction:empty-groups';
/**
* Execute the console command.
@@ -61,9 +58,6 @@ class DeleteEmptyGroups extends Command
TransactionGroup::whereNull('deleted_at')->whereIn('id', $chunk)->delete();
}
}
if (0 === $total) {
$this->friendlyInfo('Verified there are no empty groups.');
}
return 0;
}

View File

@@ -30,16 +30,13 @@ use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
/**
* Class DeleteEmptyJournals
*/
class DeleteEmptyJournals extends Command
class RemovesEmptyJournals extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Delete empty and uneven transaction journals.';
protected $signature = 'firefly-iii:delete-empty-journals';
protected $signature = 'correction:empty-journals';
/**
* Execute the console command.
@@ -82,9 +79,6 @@ class DeleteEmptyJournals extends Command
++$total;
}
}
if (0 === $total) {
$this->friendlyPositive('No uneven transaction journals.');
}
}
private function deleteEmptyJournals(): void
@@ -107,8 +101,5 @@ class DeleteEmptyJournals extends Command
$this->friendlyInfo(sprintf('Deleted empty transaction journal #%d', $entry->id));
++$count;
}
if (0 === $count) {
$this->friendlyPositive('No empty transaction journals.');
}
}
}

View File

@@ -32,13 +32,13 @@ use Illuminate\Console\Command;
/**
* Deletes transactions where the journal has been deleted.
*/
class DeleteOrphanedTransactions extends Command
class RemovesOrphanedTransactions extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Deletes orphaned transactions.';
protected $signature = 'firefly-iii:delete-orphaned-transactions';
protected $signature = 'correction:orphaned-transactions';
/**
* Execute the console command.
@@ -63,7 +63,7 @@ class DeleteOrphanedTransactions extends Command
;
$count = $set->count();
if (0 === $count) {
$this->friendlyPositive('No orphaned journals.');
// $this->friendlyPositive('No orphaned journals.');
return;
}
@@ -116,9 +116,6 @@ class DeleteOrphanedTransactions extends Command
++$count;
}
}
if (0 === $count) {
$this->friendlyPositive('No orphaned transactions.');
}
}
private function deleteFromOrphanedAccounts(): void
@@ -147,8 +144,5 @@ class DeleteOrphanedTransactions extends Command
);
++$count;
}
if (0 === $count) {
$this->friendlyPositive('No orphaned accounts.');
}
}
}

View File

@@ -29,16 +29,13 @@ use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
/**
* Class DeleteZeroAmount
*/
class DeleteZeroAmount extends Command
class RemovesZeroAmount extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Delete transactions with zero amount.';
protected $signature = 'firefly-iii:delete-zero-amount';
protected $signature = 'correction:zero-amounts';
/**
* Execute the console command.
@@ -56,9 +53,6 @@ class DeleteZeroAmount extends Command
Transaction::where('transaction_journal_id', $journal->id)->delete();
}
if (0 === $journals->count()) {
$this->friendlyPositive('No zero-amount transaction journals.');
}
return 0;
}

View File

@@ -1,8 +1,8 @@
<?php
/**
* RestoreOAuthKeys.php
* Copyright (c) 2020 james@firefly-iii.org
/*
* RestoresOAuthKeys.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
@@ -17,26 +17,23 @@
* 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/>.
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
namespace FireflyIII\Console\Commands\Integrity;
namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Support\System\OAuthKeys;
use Illuminate\Console\Command;
/**
* Class RestoreOAuthKeys
*/
class RestoreOAuthKeys extends Command
class RestoresOAuthKeys extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Will restore the OAuth keys generated for the system.';
protected $signature = 'firefly-iii:restore-oauth-keys';
protected $signature = 'correction:restore-oauth-keys';
/**
* Execute the console command.
@@ -76,7 +73,6 @@ class RestoreOAuthKeys extends Command
return;
}
$this->friendlyPositive('OAuth keys are OK');
}
private function keysInDatabase(): bool

View File

@@ -28,13 +28,10 @@ use FireflyIII\Models\Account;
use FireflyIII\Services\Internal\Support\CreditRecalculateService;
use Illuminate\Console\Command;
/**
* Class CorrectionSkeleton
*/
class TriggerCreditCalculation extends Command
class TriggersCreditCalculation extends Command
{
protected $description = 'Triggers the credit recalculation service for liabilities.';
protected $signature = 'firefly-iii:trigger-credit-recalculation';
protected $signature = 'correction:recalculates-liabilities';
/**
* Execute the console command.

View File

@@ -36,10 +36,7 @@ use FireflyIII\Support\Export\ExportDataGenerator;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
/**
* Class ExportData
*/
class ExportData extends Command
class ExportsData extends Command
{
use ShowsFriendlyMessages;
use VerifiesAccessToken;

View File

@@ -4,10 +4,6 @@ namespace FireflyIII\Console\Commands\Integrity;
use Illuminate\Console\Command;
/**
* Class ReportSkeleton
* TODO DONT FORGET TO ADD THIS TO THE DOCKER BUILD
*/
class ReportSkeleton extends Command
{

View File

@@ -31,16 +31,13 @@ use FireflyIII\Models\Category;
use FireflyIII\Models\Tag;
use Illuminate\Console\Command;
/**
* Class ReportEmptyObjects
*/
class ReportEmptyObjects extends Command
class ReportsEmptyObjects extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Reports on empty database objects.';
protected $signature = 'firefly-iii:report-empty-objects';
protected $signature = 'integrity:empty-objects';
/**
* Execute the console command.

View File

@@ -27,10 +27,7 @@ namespace FireflyIII\Console\Commands\Integrity;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
/**
* Class ReportIntegrity
*/
class ReportIntegrity extends Command
class ReportsIntegrity extends Command
{
use ShowsFriendlyMessages;
@@ -48,11 +45,9 @@ class ReportIntegrity extends Command
return 1;
}
$commands = [
'firefly-iii:add-timezones-to-dates',
'firefly-iii:create-group-memberships',
'firefly-iii:report-empty-objects',
'firefly-iii:report-sum',
'firefly-iii:upgrade-group-information',
// 'firefly-iii:add-timezones-to-dates',
'integrity:empty-objects',
'integrity:total-sums',
];
foreach ($commands as $command) {
$this->friendlyLine(sprintf('Now executing %s', $command));

View File

@@ -29,15 +29,12 @@ use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class ReportSkeleton
*/
class ReportSum extends Command
class ReportsSums extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Report on the total sum of transactions. Must be 0.';
protected $signature = 'firefly-iii:report-sum';
protected $signature = 'integrity:total-sums';
/**
* Execute the console command.

View File

@@ -28,7 +28,7 @@ use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Symfony\Component\Console\Command\Command as CommandAlias;
class LaravelPassportKeys extends Command
class CallsLaravelPassportKeys extends Command
{
use ShowsFriendlyMessages;

View File

@@ -28,10 +28,7 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
use PDO;
/**
* Class CreateDatabase
*/
class CreateDatabase extends Command
class CreatesDatabase extends Command
{
use ShowsFriendlyMessages;

View File

@@ -29,16 +29,13 @@ use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
/**
* Class CreateFirstUser
*/
class CreateFirstUser extends Command
class CreatesFirstUser extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Creates a new user and gives admin rights. Outputs the password on the command line. Strictly for testing.';
protected $signature = 'firefly-iii:create-first-user {email}';
protected $signature = 'system:create-first-user {email}';
private UserRepositoryInterface $repository;
/**

View File

@@ -44,13 +44,11 @@ use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* Class ForceDecimalSize
*
* This command was inspired by https://github.com/elliot-gh. It will check all amount fields
* and their values and correct them to the correct number of decimal places. This fixes issues where
* Firefly III would store 0.01 as 0.01000000000000000020816681711721685132943093776702880859375.
*/
class ForceDecimalSize extends Command
class ForcesDecimalSize extends Command
{
use ShowsFriendlyMessages;

View File

@@ -33,10 +33,7 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
/**
* Class ForceMigration
*/
class ForceMigration extends Command
class ForcesMigrations extends Command
{
use ShowsFriendlyMessages;
use VerifiesAccessToken;

View File

@@ -27,16 +27,13 @@ namespace FireflyIII\Console\Commands\System;
use FireflyIII\Support\System\GeneratesInstallationId;
use Illuminate\Console\Command;
/**
* Class UpgradeFireflyInstructions.
*/
class UpgradeFireflyInstructions extends Command
class OutputsInstructions extends Command
{
use GeneratesInstallationId;
protected $description = 'Instructions in case of upgrade trouble.';
protected $signature = 'firefly:instructions {task}';
protected $signature = 'firefly-iii:instructions {task=install}';
/**
* Execute the console command.
@@ -79,7 +76,7 @@ class UpgradeFireflyInstructions extends Command
}
$prefix = 'v';
if (str_starts_with($version, 'develop')) {
if (str_starts_with($version, 'develop') || str_starts_with($version, 'branch')) {
$prefix = '';
}
@@ -94,6 +91,8 @@ class UpgradeFireflyInstructions extends Command
$this->boxedInfo('There are no extra upgrade instructions.');
$this->boxed('Firefly III should be ready for use.');
$this->boxed('');
$this->donationText();
$this->boxed('');
$this->showLine();
return;
@@ -102,6 +101,8 @@ class UpgradeFireflyInstructions extends Command
$this->boxed(sprintf('Thank you for updating to Firefly III, %s%s!', $prefix, $version));
$this->boxedInfo($text);
$this->boxed('');
$this->donationText();
$this->boxed('');
$this->showLine();
}
@@ -213,6 +214,8 @@ class UpgradeFireflyInstructions extends Command
$this->boxedInfo('There are no extra installation instructions.');
$this->boxed('Firefly III should be ready for use.');
$this->boxed('');
$this->donationText();
$this->boxed('');
$this->showLine();
return;
@@ -221,6 +224,15 @@ class UpgradeFireflyInstructions extends Command
$this->boxed(sprintf('Thank you for installing Firefly III, %s%s!', $prefix, $version));
$this->boxedInfo($text);
$this->boxed('');
$this->donationText();
$this->boxed('');
$this->showLine();
}
private function donationText(): void
{
$this->boxed('Did you know you can support the development of Firefly III?');
$this->boxed('You can donate in many ways, like GitHub Sponsors or Patreon.');
$this->boxed('For more information, please visit https://bit.ly/donate-to-Firefly-III');
}
}

View File

@@ -26,10 +26,7 @@ namespace FireflyIII\Console\Commands\System;
use Illuminate\Console\Command;
/**
* Class OutputVersion
*/
class OutputVersion extends Command
class OutputsVersion extends Command
{
protected $description = 'Outputs the Firefly III version';

View File

@@ -29,10 +29,7 @@ use FireflyIII\Models\Attachment;
use Illuminate\Console\Command;
use Illuminate\Contracts\Encryption\DecryptException;
/**
* Class ScanAttachments.
*/
class ScanAttachments extends Command
class ScansAttachments extends Command
{
use ShowsFriendlyMessages;

View File

@@ -27,10 +27,7 @@ namespace FireflyIII\Console\Commands\System;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
/**
* Class SetLatestVersion
*/
class SetLatestVersion extends Command
class SetsLatestVersion extends Command
{
use ShowsFriendlyMessages;

View File

@@ -29,9 +29,6 @@ use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
use League\Flysystem\FilesystemException;
/**
* Class VerifySecurityAlerts
*/
class VerifySecurityAlerts extends Command
{
use ShowsFriendlyMessages;

View File

@@ -40,9 +40,6 @@ use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
/**
* Class ApplyRules
*/
class ApplyRules extends Command
{
use ShowsFriendlyMessages;

View File

@@ -34,9 +34,6 @@ use FireflyIII\Support\Cronjobs\RecurringCronjob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
/**
* Class Cron
*/
class Cron extends Command
{
use ShowsFriendlyMessages;

View File

@@ -32,16 +32,13 @@ use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
/**
* Class TransactionIdentifier
*/
class TransactionIdentifier extends Command
class AddsTransactionIdentifiers extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_transaction_identifier';
protected $description = 'Fixes transaction identifiers.';
protected $signature = 'firefly-iii:transaction-identifiers {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-transaction-identifiers {--F|force : Force the execution of this command.}';
private JournalCLIRepositoryInterface $cliRepository;
private int $count;

View File

@@ -30,15 +30,12 @@ use FireflyIII\Models\Preference;
use Illuminate\Console\Command;
use Illuminate\Contracts\Encryption\DecryptException;
/**
* Class DecryptDatabase
*/
class DecryptDatabase extends Command
class RemovesDatabaseDecryption extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Decrypts the database.';
protected $signature = 'firefly-iii:decrypt-all';
protected $signature = 'upgrade:480-decrypt-all';
/**
* Execute the console command.

View File

@@ -28,16 +28,13 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Support\Models\AccountBalanceCalculator;
use Illuminate\Console\Command;
/**
* Class CorrectionSkeleton
*/
class CorrectAccountBalance extends Command
class RepairsAccountBalances extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '610_correct_balances';
protected $description = 'Recalculate all account balance amounts';
protected $signature = 'firefly-iii:correct-account-balance {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:610-account-balances {--F|force : Force the execution of this command.}';
public function handle(): int
{

View File

@@ -27,16 +27,13 @@ namespace FireflyIII\Console\Commands\Upgrade;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
/**
* Class FixPostgresSequences
*/
class FixPostgresSequences extends Command
class RepairsPostgresSequences extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Fixes issues with PostgreSQL sequences.';
protected $signature = 'firefly-iii:fix-pgsql-sequences';
protected $signature = 'upgrade:600-pgsql-sequences';
/**
* Execute the console command.

View File

@@ -4,9 +4,6 @@ namespace FireflyIII\Console\Commands\Upgrade;
use Illuminate\Console\Command;
/**
* Class UpgradeSkeleton.
*/
class UpgradeSkeleton extends Command
{
use ShowsFriendlyMessages;
@@ -14,7 +11,7 @@ class UpgradeSkeleton extends Command
protected $description = 'SOME DESCRIPTION';
protected $signature = 'firefly-iii:UPGRSKELETON {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:UPGRSKELETON {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -36,17 +36,14 @@ use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class AccountCurrencies
*/
class AccountCurrencies extends Command
class UpgradesAccountCurrencies extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_account_currencies';
protected $description = 'Give all accounts proper currency info.';
protected $signature = 'firefly-iii:account-currencies {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-account-currencies {--F|force : Force the execution of this command.}';
private AccountRepositoryInterface $accountRepos;
private int $count;
private UserRepositoryInterface $userRepos;

View File

@@ -29,10 +29,7 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\AccountMeta;
use Illuminate\Console\Command;
/**
* Class RenameAccountMeta
*/
class RenameAccountMeta extends Command
class UpgradesAccountMetaData extends Command
{
use ShowsFriendlyMessages;
@@ -40,7 +37,7 @@ class RenameAccountMeta extends Command
protected $description = 'Rename account meta-data to new format.';
protected $signature = 'firefly-iii:rename-account-meta {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-account-meta {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -30,10 +30,7 @@ use FireflyIII\Models\Attachment;
use FireflyIII\Models\Note;
use Illuminate\Console\Command;
/**
* Class MigrateAttachments
*/
class MigrateAttachments extends Command
class UpgradesAttachments extends Command
{
use ShowsFriendlyMessages;
@@ -41,7 +38,7 @@ class MigrateAttachments extends Command
protected $description = 'Migrates attachment meta-data.';
protected $signature = 'firefly-iii:migrate-attachments {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-attachments {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -36,10 +36,7 @@ use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class MigrateToRules
*/
class MigrateToRules extends Command
class UpgradesBillsToRules extends Command
{
use ShowsFriendlyMessages;
@@ -47,7 +44,7 @@ class MigrateToRules extends Command
protected $description = 'Migrate bills to rules.';
protected $signature = 'firefly-iii:bills-to-rules {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-bills-to-rules {--F|force : Force the execution of this command.}';
private BillRepositoryInterface $billRepository;
private int $count;
private RuleGroupRepositoryInterface $ruleGroupRepository;

View File

@@ -28,10 +28,7 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\BudgetLimit;
use Illuminate\Console\Command;
/**
* Class AppendBudgetLimitPeriods
*/
class AppendBudgetLimitPeriods extends Command
class UpgradesBudgetLimitPeriods extends Command
{
use ShowsFriendlyMessages;
@@ -39,7 +36,7 @@ class AppendBudgetLimitPeriods extends Command
protected $description = 'Append budget limits with their (estimated) timeframe.';
protected $signature = 'firefly-iii:budget-limit-periods {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:550-budget-limit-periods {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -31,10 +31,7 @@ use FireflyIII\Models\BudgetLimit;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class BudgetLimitCurrency
*/
class BudgetLimitCurrency extends Command
class UpgradesBudgetLimits extends Command
{
use ShowsFriendlyMessages;
@@ -42,7 +39,7 @@ class BudgetLimitCurrency extends Command
protected $description = 'Give budget limits a currency';
protected $signature = 'firefly-iii:bl-currency {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-budget-limit-currencies {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -31,16 +31,13 @@ use FireflyIII\Models\AccountType;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
/**
* Class CCLiabilities
*/
class CCLiabilities extends Command
class UpgradesCreditCardLiabilities extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_cc_liabilities';
protected $description = 'Convert old credit card liabilities.';
protected $signature = 'firefly-iii:cc-liabilities {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-cc-liabilities {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -32,10 +32,7 @@ use FireflyIII\User;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
/**
* Class UpgradeCurrencyPreferences
*/
class UpgradeCurrencyPreferences extends Command
class UpgradesCurrencyPreferences extends Command
{
use ShowsFriendlyMessages;
@@ -43,7 +40,7 @@ class UpgradeCurrencyPreferences extends Command
protected $description = 'Upgrade user currency preferences';
protected $signature = 'firefly-iii:upgrade-currency-preferences {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:610-currency-preferences {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -29,10 +29,7 @@ set_time_limit(0);
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
/**
* Class UpgradeDatabase
*/
class UpgradeDatabase extends Command
class UpgradesDatabase extends Command
{
use ShowsFriendlyMessages;
@@ -46,33 +43,30 @@ class UpgradeDatabase extends Command
{
$this->callInitialCommands();
$commands = [
'firefly-iii:transaction-identifiers',
'firefly-iii:migrate-to-groups',
'firefly-iii:account-currencies',
'firefly-iii:transfer-currencies',
'firefly-iii:other-currencies',
'firefly-iii:migrate-notes',
'firefly-iii:migrate-attachments',
'firefly-iii:bills-to-rules',
'firefly-iii:bl-currency',
'firefly-iii:cc-liabilities',
'firefly-iii:back-to-journals',
'firefly-iii:rename-account-meta',
'firefly-iii:migrate-recurrence-meta',
'firefly-iii:migrate-tag-locations',
'firefly-iii:migrate-recurrence-type',
'firefly-iii:upgrade-liabilities',
'firefly-iii:liabilities-600',
'firefly-iii:budget-limit-periods',
'firefly-iii:migrate-rule-actions',
'firefly-iii:restore-oauth-keys',
'firefly-iii:correct-account-balance',
// also just in case, some integrity commands:
'firefly-iii:add-timezones-to-dates',
'firefly-iii:create-group-memberships',
'firefly-iii:upgrade-group-information',
'firefly-iii:upgrade-currency-preferences',
'firefly-iii:upgrade-multi-piggies',
'upgrade:480-transaction-identifiers',
'upgrade:480-migrate-to-groups',
'upgrade:480-account-currencies',
'upgrade:480-transfer-currencies',
'upgrade:480-currency-information',
'upgrade:480-notes',
'upgrade:480-attachments',
'upgrade:480-bills-to-rules',
'upgrade:480-budget-limit-currencies',
'upgrade:480-cc-liabilities',
'upgrade:480-journal-meta-data',
'upgrade:480-account-meta',
'upgrade:481-recurrence-meta',
'upgrade:500-tag-locations',
'upgrade:550-recurrence-type',
'upgrade:560-liabilities',
'upgrade:600-liabilities',
'upgrade:550-budget-limit-periods',
'upgrade:600-rule-actions',
'upgrade:610-account-balance',
'upgrade:610-currency-preferences',
'upgrade:610-currency-preferences',
'upgrade:620-piggy-banks',
'upgrade:620-native-amounts',
'firefly-iii:correct-database',
];
$args = [];
@@ -94,7 +88,7 @@ class UpgradeDatabase extends Command
private function callInitialCommands(): void
{
$this->call('migrate', ['--seed' => true, '--force' => true, '--no-interaction' => true]);
$this->call('firefly-iii:fix-pgsql-sequences');
$this->call('firefly-iii:decrypt-all');
$this->call('upgrade:600-pgsql-sequences');
$this->call('upgrade:480-decrypt-all');
}
}

View File

@@ -32,10 +32,7 @@ use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
/**
* Class BackToJournals
*/
class BackToJournals extends Command
class UpgradesJournalMetaData extends Command
{
use ShowsFriendlyMessages;
@@ -43,7 +40,7 @@ class BackToJournals extends Command
protected $description = 'Move meta data back to journals, not individual transactions.';
protected $signature = 'firefly-iii:back-to-journals {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-journal-meta-data {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
@@ -71,7 +68,7 @@ class BackToJournals extends Command
private function isMigrated(): bool
{
$configVar = app('fireflyconfig')->get(MigrateToGroups::CONFIG_NAME, false);
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
return (bool) $configVar->data;
}

View File

@@ -29,10 +29,7 @@ use FireflyIII\Models\Note;
use FireflyIII\Models\TransactionJournalMeta;
use Illuminate\Console\Command;
/**
* Class MigrateJournalNotes
*/
class MigrateJournalNotes extends Command
class UpgradesJournalNotes extends Command
{
use ShowsFriendlyMessages;
@@ -40,7 +37,7 @@ class MigrateJournalNotes extends Command
protected $description = 'Migrate notes for transaction journals.';
protected $signature = 'firefly-iii:migrate-notes {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-notes {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -34,16 +34,13 @@ use FireflyIII\Services\Internal\Support\CreditRecalculateService;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class UpgradeLiabilities
*/
class UpgradeLiabilities extends Command
class UpgradesLiabilities extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '560_upgrade_liabilities';
protected $description = 'Upgrade liabilities to new 5.6.0 structure.';
protected $signature = 'firefly-iii:upgrade-liabilities {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:560-liabilities {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -35,16 +35,13 @@ use FireflyIII\Services\Internal\Support\CreditRecalculateService;
use FireflyIII\User;
use Illuminate\Console\Command;
/**
* Class UpgradeLiabilitiesEight
*/
class UpgradeLiabilitiesEight extends Command
class UpgradesLiabilitiesEight extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '600_upgrade_liabilities';
protected $description = 'Upgrade liabilities to new 6.0.0 structure.';
protected $signature = 'firefly-iii:liabilities-600 {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:600-liabilities {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
@@ -201,32 +198,9 @@ class UpgradeLiabilitiesEight extends Command
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
// $delete = false;
// /** @var Transaction $source */
// $source = $journal->transactions()->where('amount', '<', 0)->first();
// /** @var Transaction $dest */
// $dest = $journal->transactions()->where('amount', '>', 0)->first();
/**
* // if source is this liability and destination is expense, remove transaction.
* // if source is revenue and destination is liability, remove transaction.
* if ($source->account_id === $account->id && $dest->account->accountType->type === AccountType::EXPENSE) {
* $delete = true;
* }
* if ($dest->account_id === $account->id && $source->account->accountType->type === AccountType::REVENUE) {
* $delete = true;
* }
*
* // overruled. No transaction will be deleted, ever.
* // code is kept in place, so I can revisit my reasoning.
* $delete = false;
*/
// if ($delete) {
$service = app(TransactionGroupDestroyService::class);
$service->destroy($journal->transactionGroup);
++$count;
// }
}
return $count;

View File

@@ -30,15 +30,15 @@ use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class UpgradeMultiPiggyBanks extends Command
class UpgradesMultiPiggyBanks extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '620_make_multi_piggies';
protected $description = 'Upgrade piggybanks so they can use multiple accounts.';
protected $description = 'Upgrade piggy banks so they can use multiple accounts.';
protected $signature = 'firefly-iii:upgrade-multi-piggies {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:620-piggy-banks {--F|force : Force the execution of this command.}';
private AccountRepositoryInterface $accountRepository;
private PiggyBankRepositoryInterface $repository;

View File

@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
/*
* UpgradesNativeAmounts.php
* Copyright (c) 2024 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.
*
* 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\Console\Commands\Upgrade;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class UpgradesNativeAmounts extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '620_native_amounts';
protected $description = 'Runs the native amounts calculations.';
protected $signature = 'upgrade:620-native-amounts {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
*/
public function handle(): int
{
if ($this->isExecuted() && true !== $this->option('force')) {
$this->friendlyInfo('This command has already been executed.');
return 0;
}
Artisan::call('correction:recalculate-native-amounts');
$this->markAsExecuted();
return 0;
}
private function isExecuted(): bool
{
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
if (null !== $configVar) {
return (bool)$configVar->data;
}
return false;
}
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);
}
}

View File

@@ -30,10 +30,7 @@ use FireflyIII\Models\RecurrenceMeta;
use FireflyIII\Models\RecurrenceTransactionMeta;
use Illuminate\Console\Command;
/**
* Class MigrateRecurrenceMeta
*/
class MigrateRecurrenceMeta extends Command
class UpgradesRecurrenceMetaData extends Command
{
use ShowsFriendlyMessages;
@@ -41,7 +38,7 @@ class MigrateRecurrenceMeta extends Command
protected $description = 'Migrate recurrence meta data';
protected $signature = 'firefly-iii:migrate-recurrence-meta {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:481-recurrence-meta {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -27,10 +27,7 @@ namespace FireflyIII\Console\Commands\Upgrade;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
/**
* Class MigrateRecurrenceType
*/
class MigrateRecurrenceType extends Command
class UpgradesRecurrenceType extends Command
{
use ShowsFriendlyMessages;
@@ -38,7 +35,7 @@ class MigrateRecurrenceType extends Command
protected $description = 'Migrate transaction type of recurring transaction.';
protected $signature = 'firefly-iii:migrate-recurrence-type {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:550-recurrence-type {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -27,7 +27,7 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\RuleAction;
use Illuminate\Console\Command;
class MigrateRuleActions extends Command
class UpgradesRuleActions extends Command
{
use ShowsFriendlyMessages;
@@ -35,7 +35,7 @@ class MigrateRuleActions extends Command
protected $description = 'Migrate rule actions away from expression engine';
protected $signature = 'firefly-iii:migrate-rule-actions {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:600-rule-actions {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -29,10 +29,7 @@ use FireflyIII\Models\Location;
use FireflyIII\Models\Tag;
use Illuminate\Console\Command;
/**
* Class MigrateTagLocations
*/
class MigrateTagLocations extends Command
class UpgradesTagLocations extends Command
{
use ShowsFriendlyMessages;
@@ -40,7 +37,7 @@ class MigrateTagLocations extends Command
protected $description = 'Migrate tag locations.';
protected $signature = 'firefly-iii:migrate-tag-locations {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:500-tag-locations {--F|force : Force the execution of this command.}';
/**
* Execute the console command.

View File

@@ -36,20 +36,13 @@ use FireflyIII\Services\Internal\Destroy\JournalDestroyService;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
/**
* This command will take split transactions and migrate them to "transaction groups".
*
* It will only run once, but can be forced to run again.
*
* Class MigrateToGroups
*/
class MigrateToGroups extends Command
class UpgradesToGroups extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_migrated_to_groups';
protected $description = 'Migrates a pre-4.7.8 transaction structure to the 4.7.8+ transaction structure.';
protected $signature = 'firefly-iii:migrate-to-groups {--F|force : Force the migration, even if it fired before.}';
protected $signature = 'upgrade:480-migrate-to-groups {--F|force : Force the migration, even if it fired before.}';
private JournalCLIRepositoryInterface $cliRepository;
private int $count;
private TransactionGroupFactory $groupFactory;

View File

@@ -34,16 +34,13 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use Illuminate\Console\Command;
/**
* Class TransferCurrenciesCorrections
*/
class TransferCurrenciesCorrections extends Command
class UpgradesTransferCurrencies extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_transfer_currencies';
protected $description = 'Updates transfer currency information.';
protected $signature = 'firefly-iii:transfer-currencies {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-transfer-currencies {--F|force : Force the execution of this command.}';
private array $accountCurrencies;
private AccountRepositoryInterface $accountRepos;
private JournalCLIRepositoryInterface $cliRepos;

View File

@@ -36,16 +36,13 @@ use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Console\Command;
/**
* Class OtherCurrenciesCorrections
*/
class OtherCurrenciesCorrections extends Command
class UpgradesVariousCurrencyInformation extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_other_currencies';
protected $description = 'Update all journal currency information.';
protected $signature = 'firefly-iii:other-currencies {--F|force : Force the execution of this command.}';
protected $signature = 'upgrade:480-currency-information {--F|force : Force the execution of this command.}';
private array $accountCurrencies;
private AccountRepositoryInterface $accountRepos;
private JournalCLIRepositoryInterface $cliRepos;

View File

@@ -231,8 +231,8 @@ class PiggyBankFactory
foreach ($accounts as $info) {
if ($account->id === $info['account_id']) {
if (array_key_exists($account->id, $accounts)) {
$toBeLinked[$account->id] = ['current_amount' => $account->pivot->current_amount];
Log::debug(sprintf('Prefilled for account #%d with amount %s', $account->id, $account->pivot->current_amount));
$toBeLinked[$account->id] = ['current_amount' => $account->pivot->current_amount ?? '0'];
Log::debug(sprintf('Prefilled for account #%d with amount %s', $account->id, $account->pivot->current_amount ?? '0'));
}
}
}

View File

@@ -83,6 +83,9 @@ class MonthReportGenerator implements ReportGeneratorInterface
'create_date',
'update_date',
// more
'notes',
// date fields.
'interest_date',
'book_date',
@@ -126,7 +129,7 @@ class MonthReportGenerator implements ReportGeneratorInterface
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation()
->withBudgetInformation()->withCategoryInformation()->withBillInformation()
->withBudgetInformation()->withCategoryInformation()->withBillInformation()->withNotes()
;
$journals = $collector->getExtractedJournals();
$journals = array_reverse($journals, true);

View File

@@ -37,7 +37,7 @@ class AccountObserver
{
public function created(Account $account): void
{
Log::debug('Observe "created" of an account.');
// Log::debug('Observe "created" of an account.');
$this->updateNativeAmount($account);
}
@@ -57,7 +57,7 @@ class AccountObserver
$account->native_virtual_balance = null;
}
$account->saveQuietly();
Log::debug('Account native virtual balance is updated.');
// Log::debug('Account native virtual balance is updated.');
}
/**
@@ -65,7 +65,7 @@ class AccountObserver
*/
public function deleting(Account $account): void
{
app('log')->debug('Observe "deleting" of an account.');
// app('log')->debug('Observe "deleting" of an account.');
$account->accountMeta()->delete();
/** @var PiggyBank $piggy */
@@ -84,7 +84,7 @@ class AccountObserver
public function updated(Account $account): void
{
Log::debug('Observe "updated" of an account.');
// Log::debug('Observe "updated" of an account.');
$this->updateNativeAmount($account);
}
}

View File

@@ -48,6 +48,7 @@ class AvailableBudgetObserver
$availableBudget->native_amount = null;
if ($availableBudget->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setUserGroup($availableBudget->user->userGroup);
$converter->setIgnoreSettings(true);
$availableBudget->native_amount = $converter->convert($availableBudget->transactionCurrency, $userCurrency, today(), $availableBudget->amount);
}

View File

@@ -71,14 +71,16 @@ class TransactionObserver
$transaction->native_amount = null;
$transaction->native_foreign_amount = null;
// first normal amount
if ($transaction->transactionCurrency->id !== $userCurrency->id) {
if ($transaction->transactionCurrency->id !== $userCurrency->id && (null === $transaction->foreign_currency_id || (null !== $transaction->foreign_currency_id && $transaction->foreign_currency_id !== $userCurrency->id))) {
$converter = new ExchangeRateConverter();
$converter->setUserGroup($transaction->transactionJournal->user->userGroup);
$converter->setIgnoreSettings(true);
$transaction->native_amount = $converter->convert($transaction->transactionCurrency, $userCurrency, $transaction->transactionJournal->date, $transaction->amount);
}
// then foreign amount
if ($transaction->foreignCurrency?->id !== $userCurrency->id && null !== $transaction->foreign_amount && null !== $transaction->foreignCurrency) {
$converter = new ExchangeRateConverter();
$converter->setUserGroup($transaction->transactionJournal->user->userGroup);
$converter->setIgnoreSettings(true);
$transaction->native_foreign_amount = $converter->convert($transaction->foreignCurrency, $userCurrency, $transaction->transactionJournal->date, $transaction->foreign_amount);
}

View File

@@ -25,8 +25,11 @@ declare(strict_types=1);
namespace FireflyIII\Helpers\Collector\Extensions;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Account;
use FireflyIII\Support\Facades\Steam;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
/**
* Trait AccountCollection
@@ -228,4 +231,76 @@ trait AccountCollection
return $this;
}
#[\Override]
public function accountBalanceIs(string $direction, string $operator, string $value): GroupCollectorInterface
{
Log::warning(sprintf('GroupCollector will be SLOW: accountBalanceIs: "%s" "%s" "%s"', $direction, $operator, $value));
/**
* @param int $index
* @param array $object
*
* @return bool
*/
$filter = static function (array $object) use ($direction, $operator, $value): bool {
/** @var array $transaction */
foreach ($object['transactions'] as $transaction) {
$key = sprintf('%s_account_id', $direction);
$accountId = $transaction[$key] ?? 0;
if (0 === $accountId) {
return false;
}
// in theory, this could lead to finding other users accounts.
$balance = Steam::finalAccountBalance(Account::find($accountId), $transaction['date']);
$result = bccomp($balance['balance'], $value);
Log::debug(sprintf('"%s" vs "%s" is %d', $balance['balance'], $value, $result));
switch ($operator) {
default:
Log::error(sprintf('GroupCollector: accountBalanceIs: unknown operator "%s"', $operator));
return false;
case '==':
Log::debug('Expect result to be 0 (equal)');
return 0 === $result;
case '!=':
Log::debug('Expect result to be -1 or 1 (not equal)');
return 0 !== $result;
case '>':
Log::debug('Expect result to be 1 (greater then)');
return 1 === $result;
case '>=':
Log::debug('Expect result to be 0 or 1 (greater then or equal)');
return -1 !== $result;
case '<':
Log::debug('Expect result to be -1 (less than)');
return -1 === $result;
case '<=':
Log::debug('Expect result to be -1 or 0 (less than or equal)');
return 1 !== $result;
}
// if($balance['balance'] $operator $value) {
// }
}
return false;
};
$this->postFilters[] = $filter;
return $this;
}
}

View File

@@ -746,7 +746,7 @@ class GroupCollector implements GroupCollectorInterface
$currentCollection = $collection;
$countFilters = count($this->postFilters);
$countCollection = count($currentCollection);
if (0 === $countFilters && 0 === $countCollection) {
if (0 === $countFilters) {
return $currentCollection;
}
app('log')->debug(sprintf('GroupCollector: postFilterCollection has %d filter(s) and %d transaction(s).', count($this->postFilters), count($currentCollection)));
@@ -874,6 +874,16 @@ class GroupCollector implements GroupCollectorInterface
return $this;
}
/**
* Limit results to a specific currency, only normal one.
*/
public function setNormalCurrency(TransactionCurrency $currency): GroupCollectorInterface
{
$this->query->where('source.transaction_currency_id', $currency->id);
return $this;
}
public function setEndRow(int $endRow): self
{
$this->endRow = $endRow;

View File

@@ -457,6 +457,11 @@ interface GroupCollectorInterface
*/
public function setCurrency(TransactionCurrency $currency): self;
/**
* Limit results to a specific currency, either foreign or normal one.
*/
public function setNormalCurrency(TransactionCurrency $currency): self;
/**
* Set destination accounts.
*/
@@ -732,4 +737,6 @@ interface GroupCollectorInterface
public function yearIs(string $year): self;
public function yearIsNot(string $year): self;
public function accountBalanceIs(string $direction, string $operator, string $value): self;
}

View File

@@ -33,7 +33,8 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface as AdminAccountRepositoryInterface;
use FireflyIII\Repositories\UserGroups\Currency\CurrencyRepositoryInterface;
use FireflyIII\Support\CacheProperties;
use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Facades\Steam;
use FireflyIII\User;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Collection;
@@ -65,82 +66,53 @@ class NetWorth implements NetWorthInterface
public function byAccounts(Collection $accounts, Carbon $date): array
{
// start in the past, end in the future? use $date
$ids = implode(',', $accounts->pluck('id')->toArray());
$cache = new CacheProperties();
$convertToNative = app('preferences')->get('convert_to_native', false)->data;
$ids = implode(',', $accounts->pluck('id')->toArray());
$cache = new CacheProperties();
$cache->addProperty($date);
$cache->addProperty($convertToNative);
$cache->addProperty('net-worth-by-accounts');
$cache->addProperty($ids);
if ($cache->has()) {
return $cache->get();
// return $cache->get();
}
app('log')->debug(sprintf('Now in byAccounts("%s", "%s")', $ids, $date->format('Y-m-d')));
Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));
$default = app('amount')->getDefaultCurrency();
$converter = new ExchangeRateConverter();
// default "native" currency has everything twice, for consistency.
$netWorth = [
'native' => [
'balance' => '0',
'native_balance' => '0',
'currency_id' => $default->id,
'currency_code' => $default->code,
'currency_name' => $default->name,
'currency_symbol' => $default->symbol,
'currency_decimal_places' => $default->decimal_places,
'native_currency_id' => $default->id,
'native_currency_code' => $default->code,
'native_currency_name' => $default->name,
'native_currency_symbol' => $default->symbol,
'native_currency_decimal_places' => $default->decimal_places,
],
];
$balances = app('steam')->finalAccountsBalance($accounts, $date);
Log::debug(sprintf('Now in byAccounts("%s", "%s")', $ids, $date->format('Y-m-d H:i:s')));
$default = Amount::getDefaultCurrency();
$netWorth = [];
$balances = Steam::finalAccountsBalance($accounts, $date);
/** @var Account $account */
foreach ($accounts as $account) {
app('log')->debug(sprintf('Now at account #%d ("%s")', $account->id, $account->name));
$currency = $this->getRepository()->getAccountCurrency($account);
if (null === $currency) {
$currency = app('amount')->getDefaultCurrency();
}
$currencyCode = $currency->code;
$balance = '0';
$nativeBalance = '0';
Log::debug(sprintf('Now at account #%d ("%s")', $account->id, $account->name));
$currency = $this->getRepository()->getAccountCurrency($account) ?? $default;
$useNative = $convertToNative && $default->id !== $currency->id;
$currency = $useNative ? $default : $currency;
$currencyCode = $currency->code;
$balance = '0';
$nativeBalance = '0';
if (array_key_exists($account->id, $balances)) {
$balance = $balances[$account->id]['balance'] ?? '0';
$nativeBalance = $balances[$account->id]['native_balance'] ?? '0';
}
app('log')->debug(sprintf('Balance is %s, native balance is %s', $balance, $nativeBalance));
// always subtract virtual balance
$virtualBalance = $account->virtual_balance;
if ('' !== $virtualBalance) {
$balance = bcsub($balance, $virtualBalance);
$nativeVirtualBalance = $converter->convert($default, $currency, $account->created_at, $virtualBalance);
$nativeBalance = bcsub($nativeBalance, $nativeVirtualBalance);
}
Log::debug(sprintf('Balance is %s, native balance is %s', $balance, $nativeBalance));
// always subtract virtual balance again.
$balance = '' !== (string) $account->virtual_balance ? bcsub($balance, $account->virtual_balance) : $balance;
$nativeBalance = '' !== (string) $account->native_virtual_balance ? bcsub($nativeBalance, $account->native_virtual_balance) : $nativeBalance;
$amountToUse = $useNative ? $nativeBalance : $balance;
Log::debug(sprintf('Will use %s %s', $currencyCode, $amountToUse));
$netWorth[$currencyCode] ??= [
'balance' => '0',
'native_balance' => '0',
'currency_id' => (string) $currency->id,
'currency_code' => $currency->code,
'currency_name' => $currency->name,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
'native_currency_id' => (string) $default->id,
'native_currency_code' => $default->code,
'native_currency_name' => $default->name,
'native_currency_symbol' => $default->symbol,
'native_currency_decimal_places' => $default->decimal_places,
'balance' => '0',
'currency_id' => (string) $currency->id,
'currency_code' => $currency->code,
'currency_name' => $currency->name,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
];
$netWorth[$currencyCode]['balance'] = bcadd($balance, $netWorth[$currencyCode]['balance']);
$netWorth[$currencyCode]['native_balance'] = bcadd($nativeBalance, $netWorth[$currencyCode]['native_balance']);
$netWorth['native']['balance'] = bcadd($nativeBalance, $netWorth['native']['balance']);
$netWorth['native']['native_balance'] = bcadd($nativeBalance, $netWorth['native']['native_balance']);
$netWorth[$currencyCode]['balance'] = bcadd($amountToUse, $netWorth[$currencyCode]['balance']);
}
$cache->store($netWorth);
$converter->summarize();
return $netWorth;
}
@@ -187,7 +159,7 @@ class NetWorth implements NetWorthInterface
*/
$accounts = $this->getAccounts();
$return = [];
$balances = app('steam')->finalAccountsBalance($accounts, $date);
$balances = Steam::finalAccountsBalance($accounts, $date);
foreach ($accounts as $account) {
$currency = $this->getRepository()->getAccountCurrency($account);
$balance = $balances[$account->id]['balance'] ?? '0';

View File

@@ -28,6 +28,7 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Support\Facades\Steam;
use FireflyIII\Support\Http\Controllers\BasicDataSupport;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
@@ -93,12 +94,14 @@ class IndexController extends Controller
$endBalances = app('steam')->finalAccountsBalance($accounts, $end);
$activities = app('steam')->getLastActivities($ids);
$accounts->each(
function (Account $account) use ($activities, $startBalances, $endBalances): void {
$currency = $this->repository->getAccountCurrency($account);
$account->lastActivityDate = $this->isInArrayDate($activities, $account->id);
$account->startBalance = $this->isInArray($startBalances, $account->id);
$account->endBalance = $this->isInArray($endBalances, $account->id);
$account->difference = bcsub($account->endBalance, $account->startBalance);
$account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToNative, $currency);
$account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToNative, $currency);
$account->differences = $this->subtract($account->startBalances, $account->endBalances);
$account->interest = app('steam')->bcround($this->repository->getMetaValue($account, 'interest'), 4);
$account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period')));
$account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type));
@@ -153,16 +156,17 @@ class IndexController extends Controller
$endBalances = app('steam')->finalAccountsBalance($accounts, $end);
$activities = app('steam')->getLastActivities($ids);
$accounts->each(
function (Account $account) use ($activities, $startBalances, $endBalances): void {
$interest = (string) $this->repository->getMetaValue($account, 'interest');
$interest = '' === $interest ? '0' : $interest;
$currency = $this->repository->getAccountCurrency($account);
// See reference nr. 68
$account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToNative, $currency);
$account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToNative, $currency);
$account->differences = $this->subtract($account->startBalances, $account->endBalances);
$account->lastActivityDate = $this->isInArrayDate($activities, $account->id);
$account->startBalance = $this->isInArray($startBalances, $account->id);
$account->endBalance = $this->isInArray($endBalances, $account->id);
$account->difference = bcsub($account->endBalance, $account->startBalance);
$account->interest = app('steam')->bcround($interest, 4);
$account->interestPeriod = (string) trans(
sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))
@@ -171,7 +175,10 @@ class IndexController extends Controller
$account->location = $this->repository->getLocation($account);
$account->liability_direction = $this->repository->getMetaValue($account, 'liability_direction');
$account->current_debt = $this->repository->getMetaValue($account, 'current_debt') ?? '-';
$account->currency = $currency ?? $this->defaultCurrency;
$account->iban = implode(' ', str_split((string) $account->iban, 4));
}
);
// make paginator:
@@ -186,4 +193,14 @@ class IndexController extends Controller
return view('accounts.index', compact('objectType', 'inactiveCount', 'subTitleIcon', 'subTitle', 'page', 'accounts'));
}
private function subtract(array $startBalances, array $endBalances)
{
$result = [];
foreach ($endBalances as $key => $value) {
$result[$key] = bcsub($value, $startBalances[$key] ?? '0');
}
return $result;
}
}

View File

@@ -30,6 +30,7 @@ use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Facades\Steam;
use FireflyIII\Support\Http\Controllers\PeriodOverview;
use Illuminate\Contracts\View\Factory;
@@ -90,7 +91,7 @@ class ShowController extends Controller
// @var Carbon $end
$end ??= session('end');
if ($end < $start) {
if ($end->lt($start)) {
[$start, $end] = [$end, $start];
}
$location = $this->repository->getLocation($account);
@@ -99,7 +100,8 @@ class ShowController extends Controller
$subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type));
$page = (int) $request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
$currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
$accountCurrency = $this->repository->getAccountCurrency($account);
$currency = $accountCurrency ?? Amount::getDefaultCurrency();
$fStart = $start->isoFormat($this->monthAndDayFormat);
$fEnd = $end->isoFormat($this->monthAndDayFormat);
$subTitle = (string) trans('firefly.journals_in_period_for_account', ['name' => $account->name, 'start' => $fStart, 'end' => $fEnd]);
@@ -129,7 +131,7 @@ class ShowController extends Controller
$groups->setPath(route('accounts.show', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]));
$showAll = false;
$balance = Steam::finalAccountBalance($account, $end)['balance'];
$balances = Steam::filterAccountBalance(Steam::finalAccountBalance($account, $end), $account, $this->convertToNative, $accountCurrency);
return view(
'accounts.show',
@@ -148,7 +150,7 @@ class ShowController extends Controller
'end',
'chartUrl',
'location',
'balance'
'balances'
)
);
}
@@ -165,33 +167,34 @@ class ShowController extends Controller
if (!$this->isEditableAccount($account)) {
return $this->redirectAccountToAccount($account);
}
$location = $this->repository->getLocation($account);
$isLiability = $this->repository->isLiability($account);
$attachments = $this->repository->getAttachments($account);
$objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type));
$end = today(config('app.timezone'));
$today = today(config('app.timezone'));
$start = $this->repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
$subTitleIcon = config('firefly.subIconsByIdentifier.'.$account->accountType->type);
$page = (int) $request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
$currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
$subTitle = (string) trans('firefly.all_journals_for_account', ['name' => $account->name]);
$periods = new Collection();
$location = $this->repository->getLocation($account);
$isLiability = $this->repository->isLiability($account);
$attachments = $this->repository->getAttachments($account);
$objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type));
$end = today(config('app.timezone'));
$today = today(config('app.timezone'));
$accountCurrency = $this->repository->getAccountCurrency($account);
$start = $this->repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
$subTitleIcon = config('firefly.subIconsByIdentifier.'.$account->accountType->type);
$page = (int) $request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
$currency = $this->repository->getAccountCurrency($account) ?? Amount::getDefaultCurrency();
$subTitle = (string) trans('firefly.all_journals_for_account', ['name' => $account->name]);
$periods = new Collection();
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->setLimit($pageSize)->setPage($page)->withAccountInformation()->withCategoryInformation();
// this search will not include transaction groups where this asset account (or liability)
// is just part of ONE of the journals. To force this:
$collector->setExpandGroupSearch(true);
$groups = $collector->getPaginatedGroups();
$groups = $collector->getPaginatedGroups();
$groups->setPath(route('accounts.show.all', [$account->id]));
$chartUrl = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]);
$showAll = true;
$balance = Steam::finalAccountBalance($account, $end)['balance'];
$chartUrl = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]);
$showAll = true;
$balances = Steam::filterAccountBalance(Steam::finalAccountBalance($account, $end), $account, $this->convertToNative, $accountCurrency);
return view(
'accounts.show',
@@ -211,7 +214,7 @@ class ShowController extends Controller
'subTitle',
'start',
'end',
'balance'
'balances'
)
);
}

View File

@@ -71,29 +71,30 @@ class IndexController extends Controller
{
$this->cleanupObjectGroups();
$this->repository->correctOrder();
$start = session('start');
$end = session('end');
$collection = $this->repository->getBills();
$total = $collection->count();
$start = session('start');
$end = session('end');
$collection = $this->repository->getBills();
$total = $collection->count();
$defaultCurrency = app('amount')->getDefaultCurrency();
$parameters = new ParameterBag();
$parameters = new ParameterBag();
// sub one day from temp start so the last paid date is one day before it should be.
$tempStart = clone $start;
$tempStart = clone $start;
// 2023-06-23 do not sub one day from temp start, fix is in BillTransformer::payDates instead
// $tempStart->subDay();
$parameters->set('start', $tempStart);
$parameters->set('end', $end);
$parameters->set('convertToNative', $this->convertToNative);
$parameters->set('defaultCurrency', $this->defaultCurrency);
/** @var BillTransformer $transformer */
$transformer = app(BillTransformer::class);
$transformer = app(BillTransformer::class);
$transformer->setParameters($parameters);
// loop all bills, convert to array and add rules and stuff.
$rules = $this->repository->getRulesForBills($collection);
$rules = $this->repository->getRulesForBills($collection);
// make bill groups:
$bills = [
$bills = [
0 => [ // the index is the order, not the ID.
'object_group_id' => 0,
'object_group_title' => (string) trans('firefly.default_group_title_name'),
@@ -112,7 +113,7 @@ class IndexController extends Controller
'bills' => [],
];
$currency = $bill->transactionCurrency ?? $defaultCurrency;
$currency = $bill->transactionCurrency ?? $this->defaultCurrency;
$array['currency_id'] = $currency->id;
$array['currency_name'] = $currency->name;
$array['currency_symbol'] = $currency->symbol;
@@ -122,14 +123,13 @@ class IndexController extends Controller
$array['rules'] = $rules[$bill['id']] ?? [];
$bills[$groupOrder]['bills'][] = $array;
}
// order by key
ksort($bills);
// summarise per currency / per group.
$sums = $this->getSums($bills);
$totals = $this->getTotals($sums);
$today = now()->startOfDay();
$sums = $this->getSums($bills);
$totals = $this->getTotals($sums);
$today = now()->startOfDay();
return view('bills.index', compact('bills', 'sums', 'total', 'totals', 'today'));
}

View File

@@ -30,12 +30,12 @@ use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\UserGroups\Currency\CurrencyRepositoryInterface;
use FireflyIII\Support\CacheProperties;
use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Facades\Steam;
use FireflyIII\Support\Http\Controllers\AugumentData;
use FireflyIII\Support\Http\Controllers\ChartGeneration;
@@ -82,6 +82,8 @@ class AccountController extends Controller
*/
public function expenseAccounts(): JsonResponse
{
Log::debug('RevenueAccounts');
/** @var Carbon $start */
$start = clone session('start', today(config('app.timezone'))->startOfMonth());
@@ -90,6 +92,7 @@ class AccountController extends Controller
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($this->convertToNative);
$cache->addProperty('chart.account.expense-accounts');
if ($cache->has()) {
return response()->json($cache->get());
@@ -100,37 +103,67 @@ class AccountController extends Controller
$currencies = [];
$chartData = [];
$tempData = [];
$default = Amount::getDefaultCurrency();
// grab all accounts and names
$accounts = $this->accountRepository->getAccountsByType([AccountType::EXPENSE]);
$accounts = $this->accountRepository->getAccountsByType([AccountTypeEnum::EXPENSE->value]);
$accountNames = $this->extractNames($accounts);
// grab all balances
$startBalances = app('steam')->finalAccountsBalance($accounts, $start);
$endBalances = app('steam')->finalAccountsBalance($accounts, $end);
// loop the end balances. This is an array for each account ($expenses)
foreach ($endBalances as $accountId => $expenses) {
$accountId = (int) $accountId;
// loop each expense entry (each entry can be a different currency).
foreach ($expenses as $currencyCode => $endAmount) {
// loop the accounts, then check for balance and currency info.
foreach ($accounts as $account) {
Log::debug(sprintf('Now in account #%d ("%s")', $account->id, $account->name));
$expenses = $endBalances[$account->id] ?? false;
if (false === $expenses) {
Log::error(sprintf('Found no end balance for account #%d', $account->id));
continue;
}
/**
* @var string $key
* @var string $endBalance
*/
foreach ($expenses as $key => $endBalance) {
if (!$this->convertToNative && 'native_balance' === $key) {
Log::debug(sprintf('[a] Will skip expense array "%s"', $key));
continue;
}
if ($this->convertToNative && 'native_balance' !== $key) {
Log::debug(sprintf('[b] Will skip expense array "%s"', $key));
continue;
}
Log::debug(sprintf('Will process expense array "%s" with amount %s', $key, $endBalance));
$searchCode = $this->convertToNative ? $default->code : $key;
Log::debug(sprintf('Search code is %s', $searchCode));
// see if there is an accompanying start amount.
// grab the difference and find the currency.
$startAmount = (string) ($startBalances[$accountId][$currencyCode] ?? '0');
$diff = bcsub((string) $endAmount, $startAmount);
$currencies[$currencyCode] ??= $this->currencyRepository->findByCode($currencyCode);
$startBalance = ($startBalances[$account->id][$key] ?? '0');
Log::debug(sprintf('Start balance is %s', $startBalance));
$diff = bcsub($endBalance, $startBalance);
$currencies[$searchCode] ??= $this->currencyRepository->findByCode($searchCode);
if (0 !== bccomp($diff, '0')) {
// store the values in a temporary array.
$tempData[] = [
'name' => $accountNames[$accountId],
'name' => $accountNames[$account->id],
'difference' => $diff,
'diff_float' => (float) $diff, // intentional float
'currency_id' => $currencies[$currencyCode]->id,
'currency_id' => $currencies[$searchCode]->id,
];
}
}
}
// recreate currencies, but on ID instead of code.
$newCurrencies = [];
foreach ($currencies as $currency) {
$newCurrencies[$currency->id] = $currency;
}
$currencies = $newCurrencies;
// sort temp array by amount.
$amounts = array_column($tempData, 'diff_float');
@@ -157,7 +190,7 @@ class AccountController extends Controller
foreach ($tempData as $entry) {
$currencyId = $entry['currency_id'];
$name = $entry['name'];
$chartData[$currencyId]['entries'][$name] = $entry['difference'];
$chartData[$currencyId]['entries'][$name] = (float) $entry['difference'];
}
$data = $this->generator->multiSet($chartData);
@@ -384,83 +417,111 @@ class AccountController extends Controller
*/
public function period(Account $account, Carbon $start, Carbon $end): JsonResponse
{
$chartData = [];
$cache = new CacheProperties();
Log::debug(sprintf('Now in period("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d')));
$chartData = [];
$cache = new CacheProperties();
$cache->addProperty('chart.account.period');
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($this->convertToNative);
$cache->addProperty($account->id);
if ($cache->has()) {
return response()->json($cache->get());
}
$currencies = $this->accountRepository->getUsedCurrencies($account);
// if the account is not expense or revenue, just use the account's default currency.
if (!in_array($account->accountType->type, [AccountType::REVENUE, AccountType::EXPENSE], true)) {
$currencies = [$this->accountRepository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency()];
// return response()->json($cache->get());
}
/** @var TransactionCurrency $currency */
foreach ($currencies as $currency) {
$chartData[] = $this->periodByCurrency($start, $end, $account, $currency);
}
$data = $this->generator->multiSet($chartData);
$cache->store($data);
return response()->json($data);
}
/**
* @throws FireflyException
*/
private function periodByCurrency(Carbon $start, Carbon $end, Account $account, TransactionCurrency $currency): array
{
Log::debug(sprintf('Now in periodByCurrency("%s", "%s", %s, "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'), $account->id, $currency->code));
$locale = app('steam')->getLocale();
$step = $this->calculateStep($start, $end);
$result = [
'label' => sprintf('%s (%s)', $account->name, $currency->symbol),
'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code,
];
$entries = [];
$current = clone $start;
// collect and filter balances for the entire period.
$step = $this->calculateStep($start, $end);
Log::debug(sprintf('Step is %s', $step));
$locale = app('steam')->getLocale();
$return = [];
// fix for issue https://github.com/firefly-iii/firefly-iii/issues/8041
// have to make sure this chart is always based on the balance at the END of the period.
// This period depends on the size of the chart
$current = app('navigation')->endOfX($current, $step, null);
Log::debug(sprintf('$current date is %s', $current->format('Y-m-d')));
if ('1D' === $step) {
// per day the entire period, balance for every day.
$format = (string) trans('config.month_and_day_js', [], $locale);
$range = app('steam')->finalAccountBalanceInRange($account, $start, $end);
$previous = array_values($range)[0];
while ($end >= $current) {
$theDate = $current->format('Y-m-d');
$balance = $range[$theDate]['balance'] ?? $previous;
$label = $current->isoFormat($format);
$entries[$label] = (float) $balance;
$previous = $balance;
$current->addDay();
}
}
if ('1W' === $step || '1M' === $step || '1Y' === $step) {
while ($end >= $current) {
Log::debug(sprintf('Current is: %s', $current->format('Y-m-d')));
$balance = Steam::finalAccountBalance($account, $current)[$currency->code] ?? '0';
$label = app('navigation')->periodShow($current, $step);
$entries[$label] = $balance;
$current = app('navigation')->addPeriod($current, $step, 0);
// here too, to fix #8041, the data is corrected to the end of the period.
$current = app('navigation')->endOfX($current, $step, null);
}
}
$result['entries'] = $entries;
$current = clone $start;
$current = app('navigation')->endOfX($current, $step, null);
$format = (string) trans('config.month_and_day_js', [], $locale);
$accountCurrency = $this->accountRepository->getAccountCurrency($account);
return $result;
Log::debug('One');
$range = Steam::finalAccountBalanceInRange($account, $start, $end, $this->convertToNative);
Log::debug('Two');
$range = Steam::filterAccountBalances($range, $account, $this->convertToNative, $accountCurrency);
Log::debug('Three');
// temp, get end balance.
Log::debug('temp get end balance');
Steam::finalAccountBalance($account, $end);
Log::debug('END temp get end balance done');
$previous = array_values($range)[0];
$accountCurrency ??= $this->defaultCurrency; // do this AFTER getting the balances.
Log::debug('Start chart loop.');
$newRange = [];
$expectedIndex = 0;
Log::debug('Balances exist at:');
foreach ($range as $key => $value) {
$newRange[] = ['date' => $key, 'info' => $value];
Log::debug(sprintf(' - %s', $key));
}
$carbon = Carbon::createFromFormat('Y-m-d', $newRange[0]['date']);
while ($end->gte($current)) {
$momentBalance = $previous;
$theDate = $current->format('Y-m-d');
while ($carbon->lte($current) && array_key_exists($expectedIndex, $newRange)) {
$momentBalance = $newRange[$expectedIndex]['info'];
Log::debug(sprintf('Expected index is %d!, date is %s, current is %s', $expectedIndex, $carbon->format('Y-m-d'), $current->format('Y-m-d')));
$carbon = Carbon::createFromFormat('Y-m-d', $newRange[$expectedIndex]['date']);
++$expectedIndex;
}
$return = $this->updateChartKeys($return, $momentBalance);
$previous = $momentBalance;
Log::debug(sprintf('Now at %s', $theDate), $momentBalance);
// process each balance thing.
foreach ($momentBalance as $key => $amount) {
$label = $current->isoFormat($format);
$return[$key]['entries'][$label] = $amount;
}
$current = app('navigation')->addPeriod($current, $step, 0);
// here too, to fix #8041, the data is corrected to the end of the period.
$current = app('navigation')->endOfX($current, $step, null);
Log::debug(sprintf('Next moment is %s', $current->format('Y-m-d')));
}
Log::debug('End of chart loop.');
// second loop (yes) to create nice array with info! Yay!
$chartData = [];
foreach ($return as $key => $info) {
if (3 === strlen($key)) {
// assume it's a currency:
$setCurrency = $this->currencyRepository->findByCode($key);
$info['currency_symbol'] = $setCurrency->symbol;
$info['currency_code'] = $setCurrency->code;
$info['label'] = sprintf('%s (%s)', $account->name, $setCurrency->symbol);
}
if ('balance' === $key) {
$info['currency_symbol'] = $accountCurrency->symbol;
$info['currency_code'] = $accountCurrency->code;
$info['label'] = sprintf('%s (%s)', $account->name, $accountCurrency->symbol);
}
if ('native_balance' === $key) {
$info['currency_symbol'] = $this->defaultCurrency->symbol;
$info['currency_code'] = $this->defaultCurrency->code;
$info['label'] = sprintf('%s (%s) (%s)', $account->name, (string) trans('firefly.sum'), $this->defaultCurrency->symbol);
}
$chartData[] = $info;
}
$data = $this->generator->multiSet($chartData);
$cache->store($data);
return response()->json($data);
}
/**
@@ -490,6 +551,7 @@ class AccountController extends Controller
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($this->convertToNative);
$cache->addProperty('chart.account.revenue-accounts');
if ($cache->has()) {
return response()->json($cache->get());
@@ -500,38 +562,71 @@ class AccountController extends Controller
$currencies = [];
$chartData = [];
$tempData = [];
$default = Amount::getDefaultCurrency();
// grab all accounts and names
$accounts = $this->accountRepository->getAccountsByType([AccountType::REVENUE]);
$accounts = $this->accountRepository->getAccountsByType([AccountTypeEnum::REVENUE->value]);
$accountNames = $this->extractNames($accounts);
// grab all balances
$startBalances = app('steam')->finalAccountsBalance($accounts, $start);
$endBalances = app('steam')->finalAccountsBalance($accounts, $end);
// loop the end balances. This is an array for each account ($expenses)
foreach ($endBalances as $accountId => $expenses) {
$accountId = (int) $accountId;
// loop each expense entry (each entry can be a different currency).
foreach ($expenses as $currencyCode => $endAmount) {
// loop the accounts, then check for balance and currency info.
foreach ($accounts as $account) {
Log::debug(sprintf('Now in account #%d ("%s")', $account->id, $account->name));
$expenses = $endBalances[$account->id] ?? false;
if (false === $expenses) {
Log::error(sprintf('Found no end balance for account #%d', $account->id));
continue;
}
/**
* @var string $key
* @var string $endBalance
*/
foreach ($expenses as $key => $endBalance) {
if (!$this->convertToNative && 'native_balance' === $key) {
Log::debug(sprintf('[a] Will skip expense array "%s"', $key));
continue;
}
if ($this->convertToNative && 'native_balance' !== $key) {
Log::debug(sprintf('[b] Will skip expense array "%s"', $key));
continue;
}
Log::debug(sprintf('Will process expense array "%s" with amount %s', $key, $endBalance));
$searchCode = $this->convertToNative ? $default->code : $key;
Log::debug(sprintf('Search code is %s', $searchCode));
// see if there is an accompanying start amount.
// grab the difference and find the currency.
$startAmount = (string) ($startBalances[$accountId][$currencyCode] ?? '0');
$diff = bcsub((string) $endAmount, $startAmount);
$currencies[$currencyCode] ??= $this->currencyRepository->findByCode($currencyCode);
$startBalance = ($startBalances[$account->id][$key] ?? '0');
Log::debug(sprintf('Start balance is %s', $startBalance));
$diff = bcsub($endBalance, $startBalance);
$currencies[$searchCode] ??= $this->currencyRepository->findByCode($searchCode);
if (0 !== bccomp($diff, '0')) {
// store the values in a temporary array.
$tempData[] = [
'name' => $accountNames[$accountId],
'name' => $accountNames[$account->id],
'difference' => $diff,
'diff_float' => (float) $diff, // intentional float
'currency_id' => $currencies[$currencyCode]->id,
'currency_id' => $currencies[$searchCode]->id,
];
}
}
}
// recreate currencies, but on ID instead of code.
$newCurrencies = [];
foreach ($currencies as $currency) {
$newCurrencies[$currency->id] = $currency;
}
$currencies = $newCurrencies;
// sort temp array by amount.
$amounts = array_column($tempData, 'diff_float');
array_multisort($amounts, SORT_ASC, $tempData);
@@ -565,4 +660,15 @@ class AccountController extends Controller
return response()->json($data);
}
private function updateChartKeys(array $array, array $balances): array
{
foreach (array_keys($balances) as $key) {
$array[$key] ??= [
'key' => $key,
];
}
return $array;
}
}

View File

@@ -109,8 +109,9 @@ class BillController extends Controller
$cache = new CacheProperties();
$cache->addProperty('chart.bill.single');
$cache->addProperty($bill->id);
$cache->addProperty($this->convertToNative);
if ($cache->has()) {
return response()->json($cache->get());
// return response()->json($cache->get());
}
$locale = app('steam')->getLocale();
@@ -132,42 +133,55 @@ class BillController extends Controller
return 0;
}
);
$currency = $bill->transactionCurrency;
if ($this->convertToNative) {
$currency = $this->defaultCurrency;
}
$chartData = [
[
'type' => 'line',
'label' => (string) trans('firefly.min-amount'),
'currency_symbol' => $bill->transactionCurrency->symbol,
'currency_code' => $bill->transactionCurrency->code,
'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code,
'entries' => [],
],
[
'type' => 'line',
'label' => (string) trans('firefly.max-amount'),
'currency_symbol' => $bill->transactionCurrency->symbol,
'currency_code' => $bill->transactionCurrency->code,
'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code,
'entries' => [],
],
[
'type' => 'bar',
'label' => (string) trans('firefly.journal-amount'),
'currency_symbol' => $bill->transactionCurrency->symbol,
'currency_code' => $bill->transactionCurrency->code,
'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code,
'entries' => [],
],
];
$currencyId = $bill->transaction_currency_id;
$amountMin = $bill->amount_min;
$amountMax = $bill->amount_max;
if ($this->convertToNative && $currencyId !== $this->defaultCurrency->id) {
$amountMin = $bill->native_amount_min;
$amountMax = $bill->native_amount_max;
}
foreach ($journals as $journal) {
$date = $journal['date']->isoFormat((string) trans('config.month_and_day_js', [], $locale));
$chartData[0]['entries'][$date] = $bill->amount_min; // minimum amount of bill
$chartData[1]['entries'][$date] = $bill->amount_max; // maximum amount of bill
$chartData[0]['entries'][$date] = $amountMin; // minimum amount of bill
$chartData[1]['entries'][$date] = $amountMax; // maximum amount of bill
// append amount because there are more than one per moment:
if (!array_key_exists($date, $chartData[2]['entries'])) {
$chartData[2]['entries'][$date] = '0';
}
$amount = bcmul($journal['amount'], '-1');
if ($currencyId === $journal['foreign_currency_id']) {
if ($this->convertToNative && $currencyId !== $journal['currency_id']) {
$amount = bcmul($journal['native_amount'], '-1');
}
if ($this->convertToNative && $currencyId === $journal['foreign_currency_id']) {
$amount = bcmul($journal['foreign_amount'], '-1');
}

View File

@@ -38,10 +38,12 @@ use FireflyIII\Repositories\Budget\NoBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Support\CacheProperties;
use FireflyIII\Support\Chart\Budget\FrontpageChartGenerator;
use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Http\Controllers\AugumentData;
use FireflyIII\Support\Http\Controllers\DateCalculation;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
/**
* Class BudgetController.
@@ -374,25 +376,27 @@ class BudgetController extends Controller
*/
public function frontpage(): JsonResponse
{
$start = session('start', today(config('app.timezone'))->startOfMonth());
$end = session('end', today(config('app.timezone'))->endOfMonth());
$start = session('start', today(config('app.timezone'))->startOfMonth());
$end = session('end', today(config('app.timezone'))->endOfMonth());
// chart properties for cache:
$cache = new CacheProperties();
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($this->convertToNative);
$cache->addProperty('chart.budget.frontpage');
if ($cache->has()) {
return response()->json($cache->get());
// return response()->json($cache->get());
}
$chartGenerator = app(FrontpageChartGenerator::class);
Log::debug('Regenerate frontpage chart from scratch.');
$chartGenerator = app(FrontpageChartGenerator::class);
$chartGenerator->setUser(auth()->user());
$chartGenerator->setStart($start);
$chartGenerator->setEnd($end);
$chartGenerator->convertToNative = $this->convertToNative;
$chartGenerator->default = Amount::getDefaultCurrency();
$chartData = $chartGenerator->generate();
$data = $this->generator->multiSet($chartData);
$chartData = $chartGenerator->generate();
$data = $this->generator->multiSet($chartData);
$cache->store($data);
return response()->json($data);

View File

@@ -49,8 +49,7 @@ class CategoryController extends Controller
use ChartGeneration;
use DateCalculation;
/** @var GeneratorInterface Chart generation methods. */
protected $generator;
protected GeneratorInterface $generator;
/**
* CategoryController constructor.
@@ -111,9 +110,10 @@ class CategoryController extends Controller
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($this->convertToNative);
$cache->addProperty('chart.category.frontpage');
if ($cache->has()) {
return response()->json($cache->get());
// return response()->json($cache->get());
}
$frontpageGenerator = new FrontpageChartGenerator($start, $end);

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Support\Facades\Steam;
use FireflyIII\Support\Http\Controllers\RequestInformation;
use FireflyIII\Support\Http\Controllers\UserNavigation;
@@ -52,6 +53,8 @@ abstract class Controller extends BaseController
protected string $dateTimeFormat;
protected string $monthAndDayFormat;
protected bool $convertToNative = false;
protected ?TransactionCurrency $defaultCurrency;
protected string $monthFormat;
protected string $redirectUrl = '/';
@@ -111,17 +114,19 @@ abstract class Controller extends BaseController
$this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale);
$this->dateTimeFormat = (string) trans('config.date_time_js', [], $locale);
$darkMode = 'browser';
$this->defaultCurrency =null;
// get shown-intro-preference:
if (auth()->check()) {
$this->defaultCurrency = app('amount')->getDefaultCurrency();
$language = Steam::getLanguage();
$locale = Steam::getLocale();
$darkMode = app('preferences')->get('darkMode', 'browser')->data;
$convertToNative =app('preferences')->get('convert_to_native', false)->data;
$this->convertToNative =app('preferences')->get('convert_to_native', false)->data;
$page = $this->getPageName();
$shownDemo = $this->hasSeenDemo();
View::share('language', $language);
View::share('locale', $locale);
View::share('convertToNative', $convertToNative);
View::share('convertToNative', $this->convertToNative);
View::share('shownDemo', $shownDemo);
View::share('current_route_name', $page);
View::share('original_route_name', Route::currentRouteName());

View File

@@ -25,7 +25,6 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers;
use Carbon\Carbon;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Models\AccountType;
@@ -40,8 +39,10 @@ use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\View\View;
use Monolog\Handler\RotatingFileHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Class DebugController
@@ -59,6 +60,65 @@ class DebugController extends Controller
$this->middleware(IsDemoUser::class)->except(['displayError']);
}
public function routes(): never
{
if (!auth()->user()->hasRole('owner')) {
throw new NotFoundHttpException();
}
$routes = Route::getRoutes();
$return = [];
/** @var \Illuminate\Routing\Route $route */
foreach ($routes as $route) {
// skip API and other routes.
if (
str_starts_with($route->uri(), 'api')
|| str_starts_with($route->uri(), '_debugbar')
|| str_starts_with($route->uri(), '_ignition')
|| str_starts_with($route->uri(), 'oauth')
|| str_starts_with($route->uri(), 'sanctum')
) {
continue;
}
// skip non GET routes
if (!in_array('GET', $route->methods(), true)) {
continue;
}
// no name route:
if (null === $route->getName()) {
var_dump($route);
exit;
}
if (!str_contains($route->uri(), '{')) {
$return[$route->getName()] = route($route->getName());
continue;
}
$params = [];
foreach ($route->parameterNames() as $name) {
$params[] = $this->getParameter($name);
}
$return[$route->getName()] = route($route->getName(), $params);
}
$count = 0;
echo '<hr>';
echo '<h1>Routes</h1>';
echo sprintf('<h2>%s</h2>', $count);
foreach ($return as $name => $path) {
echo sprintf('<a href="%1$s">%2$s</a><br>', $path, $name).PHP_EOL;
++$count;
if (0 === $count % 10) {
echo '<hr>';
echo sprintf('<h2>%s</h2>', $count);
}
}
exit;
var_dump($return);
}
/**
* Show all possible errors.
*
@@ -344,4 +404,130 @@ class DebugController extends Controller
return redirect(route('home'));
}
private function getParameter(string $name): string
{
switch ($name) {
default:
throw new FireflyException(sprintf('Unknown parameter "%s"', $name));
case 'cliToken':
case 'token':
case 'code':
case 'oldAddressHash':
return 'fake-token';
case 'objectType':
return 'asset';
case 'account':
return '1';
case 'start_date':
return '20241201';
case 'end_date':
return '20241231';
case 'attachment':
return '1';
case 'bill':
return '1';
case 'budget':
return '1';
case 'budgetLimit':
return '1';
case 'category':
return '1';
case 'currency':
return '1';
case 'fromCurrencyCode':
return 'EUR';
case 'toCurrencyCode':
return 'USD';
case 'accountList':
return '1,6';
case 'budgetList':
return '1,2';
case 'categoryList':
return '1,2';
case 'doubleList':
return '1,2';
case 'tagList':
return '1,2';
case 'tag':
return '1';
case 'piggyBank':
return '1';
case 'objectGroup':
return '1';
case 'route':
return 'accounts';
case 'specificPage':
return 'show';
case 'recurrence':
return '1';
case 'tj':
return '1';
case 'reportType':
return 'default';
case 'ruleGroup':
return '1';
case 'rule':
return '1';
case 'tagOrId':
return '1';
case 'transactionGroup':
return '1';
case 'journalList':
return '1,2';
case 'transactionType':
return 'withdrawal';
case 'journalLink':
return '1';
case 'webhook':
return '1';
case 'user':
return '1';
case 'linkType':
return '1';
case 'userGroup':
return '1';
case 'date':
return '20241201';
}
}
}

Some files were not shown because too many files have changed in this diff Show More