Code cleanup.

This commit is contained in:
James Cole
2023-12-20 19:35:52 +01:00
parent c4f6366642
commit 64ec0cf62e
997 changed files with 12908 additions and 28136 deletions

View File

@@ -34,7 +34,6 @@ use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Models\RecurrenceTransaction;
use FireflyIII\Models\RuleTrigger;
use Illuminate\Console\Command;
use ValueError;
/**
* Class ReportSkeleton
@@ -46,9 +45,6 @@ class CorrectAmounts extends Command
protected $description = 'This command makes sure positive and negative amounts are recorded correctly.';
protected $signature = 'firefly-iii:fix-amount-pos-neg';
/**
* @return int
*/
public function handle(): int
{
// auto budgets must be positive
@@ -70,13 +66,9 @@ class CorrectAmounts extends Command
// rule_triggers must be positive or zero (amount_less, amount_more, amount_is)
$this->fixRuleTriggers();
return 0;
}
/**
* @return void
*/
private function fixAutoBudgets(): void
{
$set = AutoBudget::where('amount', '<', 0)->get();
@@ -86,6 +78,7 @@ class CorrectAmounts extends Command
return;
}
/** @var AutoBudget $item */
foreach ($set as $item) {
$item->amount = app('steam')->positive($item->amount);
@@ -94,9 +87,6 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d auto budget amount(s).', $count));
}
/**
* @return void
*/
private function fixAvailableBudgets(): void
{
$set = AvailableBudget::where('amount', '<', 0)->get();
@@ -106,6 +96,7 @@ class CorrectAmounts extends Command
return;
}
/** @var AvailableBudget $item */
foreach ($set as $item) {
$item->amount = app('steam')->positive($item->amount);
@@ -114,9 +105,6 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d available budget amount(s).', $count));
}
/**
* @return void
*/
private function fixBills(): void
{
$set = Bill::where('amount_min', '<', 0)->orWhere('amount_max', '<', 0)->get();
@@ -126,6 +114,7 @@ class CorrectAmounts extends Command
return;
}
/** @var Bill $item */
foreach ($set as $item) {
$item->amount_min = app('steam')->positive($item->amount_min);
@@ -135,9 +124,6 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d bill amount(s).', $count));
}
/**
* @return void
*/
private function fixBudgetLimits(): void
{
$set = BudgetLimit::where('amount', '<', 0)->get();
@@ -147,6 +133,7 @@ class CorrectAmounts extends Command
return;
}
/** @var BudgetLimit $item */
foreach ($set as $item) {
$item->amount = app('steam')->positive($item->amount);
@@ -155,9 +142,6 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d budget limit amount(s).', $count));
}
/**
* @return void
*/
private function fixExchangeRates(): void
{
$set = CurrencyExchangeRate::where('rate', '<', 0)->get();
@@ -167,6 +151,7 @@ class CorrectAmounts extends Command
return;
}
/** @var CurrencyExchangeRate $item */
foreach ($set as $item) {
$item->rate = app('steam')->positive($item->rate);
@@ -175,9 +160,6 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d currency exchange rate(s).', $count));
}
/**
* @return void
*/
private function fixRepetitions(): void
{
$set = PiggyBankRepetition::where('currentamount', '<', 0)->get();
@@ -187,6 +169,7 @@ class CorrectAmounts extends Command
return;
}
/** @var PiggyBankRepetition $item */
foreach ($set as $item) {
$item->currentamount = app('steam')->positive($item->currentamount);
@@ -195,9 +178,6 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d piggy bank repetition amount(s).', $count));
}
/**
* @return void
*/
private function fixPiggyBanks(): void
{
$set = PiggyBank::where('targetamount', '<', 0)->get();
@@ -207,6 +187,7 @@ class CorrectAmounts extends Command
return;
}
/** @var PiggyBank $item */
foreach ($set as $item) {
$item->targetamount = app('steam')->positive($item->targetamount);
@@ -215,20 +196,19 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d piggy bank amount(s).', $count));
}
/**
* @return void
*/
private function fixRecurrences(): void
{
$set = RecurrenceTransaction::where('amount', '<', 0)
->orWhere('foreign_amount', '<', 0)
->get();
->orWhere('foreign_amount', '<', 0)
->get()
;
$count = $set->count();
if (0 === $count) {
$this->friendlyPositive('All recurring transaction amounts are positive.');
return;
}
/** @var RecurrenceTransaction $item */
foreach ($set as $item) {
$item->amount = app('steam')->positive($item->amount);
@@ -238,27 +218,26 @@ class CorrectAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d recurring transaction amount(s).', $count));
}
/**
* @return void
*/
private function fixRuleTriggers(): void
{
$set = RuleTrigger::whereIn('trigger_type', ['amount_less', 'amount_more', 'amount_is'])->get();
$fixed = 0;
/** @var RuleTrigger $item */
foreach ($set as $item) {
// basic check:
$check = 0;
try {
$check = bccomp((string)$item->trigger_value, '0');
} catch (ValueError $e) {
} catch (\ValueError $e) {
$this->friendlyError(sprintf('Rule #%d contained invalid %s-trigger "%s". The trigger has been removed, and the rule is disabled.', $item->rule_id, $item->trigger_type, $item->trigger_value));
$item->rule->active = false;
$item->rule->save();
$item->forceDelete();
}
if (-1 === $check) {
$fixed++;
++$fixed;
$item->trigger_value = app('steam')->positive($item->trigger_value);
$item->save();
}
@@ -270,5 +249,4 @@ class CorrectAmounts extends Command
}
$this->friendlyInfo(sprintf('Corrected %d rule trigger amount(s).', $fixed));
}
}

View File

@@ -25,12 +25,9 @@ namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
use Schema;
/**
* Class CorrectDatabase
*
*/
class CorrectDatabase extends Command
{
@@ -45,7 +42,7 @@ class CorrectDatabase extends Command
public function handle(): int
{
// if table does not exist, return false
if (!Schema::hasTable('users')) {
if (!\Schema::hasTable('users')) {
$this->friendlyError('No "users"-table, will not continue.');
return 1;

View File

@@ -47,13 +47,12 @@ class CorrectOpeningBalanceCurrencies extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$journals = $this->getJournals();
$count = 0;
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$count += $this->correctJournal($journal);
@@ -71,22 +70,15 @@ class CorrectOpeningBalanceCurrencies extends Command
return 0;
}
/**
* @return Collection
*/
private function getJournals(): Collection
{
/** @var Collection */
// @var Collection
return TransactionJournal::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->whereNull('transaction_journals.deleted_at')
->where('transaction_types.type', TransactionType::OPENING_BALANCE)->get(['transaction_journals.*']);
->whereNull('transaction_journals.deleted_at')
->where('transaction_types.type', TransactionType::OPENING_BALANCE)->get(['transaction_journals.*'])
;
}
/**
* @param TransactionJournal $journal
*
* @return int
*/
private function correctJournal(TransactionJournal $journal): int
{
// get the asset account for this opening balance:
@@ -103,17 +95,13 @@ class CorrectOpeningBalanceCurrencies extends Command
return $this->setCorrectCurrency($account, $journal);
}
/**
* @param TransactionJournal $journal
*
* @return Account|null
*/
private function getAccount(TransactionJournal $journal): ?Account
{
$transactions = $journal->transactions()->get();
/** @var Transaction $transaction */
foreach ($transactions as $transaction) {
/** @var Account|null $account */
/** @var null|Account $account */
$account = $transaction->account()->first();
if (null !== $account && AccountType::INITIAL_BALANCE !== $account->accountType()->first()->type) {
return $account;
@@ -123,12 +111,6 @@ class CorrectOpeningBalanceCurrencies extends Command
return null;
}
/**
* @param Account $account
* @param TransactionJournal $journal
*
* @return int
*/
private function setCorrectCurrency(Account $account, TransactionJournal $journal): int
{
$currency = $this->getCurrency($account);
@@ -151,11 +133,6 @@ class CorrectOpeningBalanceCurrencies extends Command
return $count;
}
/**
* @param Account $account
*
* @return TransactionCurrency
*/
private function getCurrency(Account $account): TransactionCurrency
{
/** @var AccountRepositoryInterface $repos */

View File

@@ -23,7 +23,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Correction;
use Exception;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
@@ -43,8 +42,7 @@ class CreateAccessTokens extends Command
/**
* Execute the console command.
*
* @return int
* @throws Exception
* @throws \Exception
*/
public function handle(): int
{
@@ -54,6 +52,7 @@ class CreateAccessTokens extends Command
$count = 0;
$users = $repository->all();
/** @var User $user */
foreach ($users as $user) {
$pref = app('preferences')->getForUser($user, 'access_token');

View File

@@ -40,8 +40,6 @@ class CreateLinkTypes extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -54,7 +52,8 @@ class CreateLinkTypes extends Command
];
foreach ($set as $name => $values) {
$link = LinkType::where('name', $name)
->first();
->first()
;
if (null === $link) {
$link = new LinkType();
$link->name = $name;
@@ -69,6 +68,7 @@ class CreateLinkTypes extends Command
if (0 === $count) {
$this->friendlyPositive('All link types are OK');
}
return 0;
}
}

View File

@@ -41,15 +41,14 @@ class DeleteEmptyGroups extends Command
/**
* Execute the console command.
*
* @return int
* @throws Exception;
*
*/
public function handle(): int
{
$groupIds
= TransactionGroup::leftJoin('transaction_journals', 'transaction_groups.id', '=', 'transaction_journals.transaction_group_id')
->whereNull('transaction_journals.id')->get(['transaction_groups.id'])->pluck('id')->toArray();
->whereNull('transaction_journals.id')->get(['transaction_groups.id'])->pluck('id')->toArray()
;
$total = count($groupIds);
if ($total > 0) {

View File

@@ -23,7 +23,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Correction;
use DB;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
@@ -43,8 +42,6 @@ class DeleteEmptyJournals extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -60,9 +57,11 @@ class DeleteEmptyJournals extends Command
private function deleteUnevenJournals(): void
{
$set = Transaction::whereNull('deleted_at')
->groupBy('transactions.transaction_journal_id')
->get([DB::raw('COUNT(transactions.transaction_journal_id) as the_count'), 'transaction_journal_id']); // @phpstan-ignore-line
->groupBy('transactions.transaction_journal_id')
->get([\DB::raw('COUNT(transactions.transaction_journal_id) as the_count'), 'transaction_journal_id']) // @phpstan-ignore-line
;
$total = 0;
/** @var Transaction $row */
foreach ($set as $row) {
$count = (int)$row->the_count;
@@ -75,12 +74,11 @@ class DeleteEmptyJournals extends Command
app('log')->error($e->getTraceAsString());
}
Transaction::where('transaction_journal_id', $row->transaction_journal_id)->delete();
$this->friendlyWarning(
sprintf('Deleted transaction journal #%d because it had an uneven number of transactions.', $row->transaction_journal_id)
);
$total++;
++$total;
}
}
if (0 === $total) {
@@ -88,16 +86,14 @@ class DeleteEmptyJournals extends Command
}
}
/**
* @return void
*/
private function deleteEmptyJournals(): void
{
$count = 0;
$set = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->groupBy('transaction_journals.id')
->whereNull('transactions.transaction_journal_id')
->get(['transaction_journals.id']);
->groupBy('transaction_journals.id')
->whereNull('transactions.transaction_journal_id')
->get(['transaction_journals.id'])
;
foreach ($set as $entry) {
try {
@@ -107,7 +103,6 @@ class DeleteEmptyJournals extends Command
app('log')->error($e->getTraceAsString());
}
$this->friendlyInfo(sprintf('Deleted empty transaction journal #%d', $entry->id));
++$count;
}

View File

@@ -23,12 +23,10 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Correction;
use Exception;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
use stdClass;
/**
* Deletes transactions where the journal has been deleted.
@@ -44,8 +42,7 @@ class DeleteOrphanedTransactions extends Command
/**
* Execute the console command.
*
* @return int
* @throws Exception
* @throws \Exception
*/
public function handle(): int
{
@@ -56,18 +53,17 @@ class DeleteOrphanedTransactions extends Command
return 0;
}
/**
* @return void
*/
private function deleteOrphanedJournals(): void
{
$set = TransactionJournal::leftJoin('transaction_groups', 'transaction_journals.transaction_group_id', 'transaction_groups.id')
->whereNotNull('transaction_groups.deleted_at')
->whereNull('transaction_journals.deleted_at')
->get(['transaction_journals.id', 'transaction_journals.transaction_group_id']);
->whereNotNull('transaction_groups.deleted_at')
->whereNull('transaction_journals.deleted_at')
->get(['transaction_journals.id', 'transaction_journals.transaction_group_id'])
;
$count = $set->count();
if (0 === $count) {
$this->friendlyPositive('No orphaned journals.');
return;
}
$this->friendlyInfo(sprintf('Found %d orphaned journal(s).', $count));
@@ -87,22 +83,24 @@ class DeleteOrphanedTransactions extends Command
}
/**
* @throws Exception
* @throws \Exception
*/
private function deleteOrphanedTransactions(): void
{
$count = 0;
$set = Transaction::leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->whereNotNull('transaction_journals.deleted_at')
->whereNull('transactions.deleted_at')
->whereNotNull('transactions.id')
->get(
[
'transaction_journals.id as journal_id',
'transactions.id as transaction_id',
]
);
/** @var stdClass $entry */
->whereNotNull('transaction_journals.deleted_at')
->whereNull('transactions.deleted_at')
->whereNotNull('transactions.id')
->get(
[
'transaction_journals.id as journal_id',
'transactions.id as transaction_id',
]
)
;
/** @var \stdClass $entry */
foreach ($set as $entry) {
$transaction = Transaction::find((int)$entry->transaction_id);
if (null !== $transaction) {
@@ -122,16 +120,15 @@ class DeleteOrphanedTransactions extends Command
}
}
/**
*
*/
private function deleteFromOrphanedAccounts(): void
{
$set
= Transaction::leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id')
->whereNotNull('accounts.deleted_at')
->get(['transactions.*']);
->whereNotNull('accounts.deleted_at')
->get(['transactions.*'])
;
$count = 0;
/** @var Transaction $transaction */
foreach ($set as $transaction) {
// delete journals
@@ -147,7 +144,7 @@ class DeleteOrphanedTransactions extends Command
$transaction->account_id
)
);
$count++;
++$count;
}
if (0 === $count) {
$this->friendlyPositive('No orphaned accounts.');

View File

@@ -41,14 +41,13 @@ class DeleteZeroAmount extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$set = Transaction::where('amount', 0)->get(['transaction_journal_id'])->pluck('transaction_journal_id')->toArray();
$set = array_unique($set);
$journals = TransactionJournal::whereIn('id', $set)->get();
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$this->friendlyWarning(sprintf('Deleted transaction journal #%d because the amount is zero (0.00).', $journal->id));

View File

@@ -48,8 +48,6 @@ class EnableCurrencies extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -57,14 +55,10 @@ class EnableCurrencies extends Command
foreach ($userGroups as $userGroup) {
$this->correctCurrencies($userGroup);
}
return CommandAlias::SUCCESS;
}
/**
* @param UserGroup $userGroup
*
* @return void
*/
private function correctCurrencies(UserGroup $userGroup): void
{
/** @var CurrencyRepositoryInterface $repos */
@@ -75,40 +69,41 @@ class EnableCurrencies extends Command
Log::debug(sprintf('Now correcting currencies for user group #%d', $userGroup->id));
$found = [$defaultCurrency->id];
// get all meta entries
/** @var Collection $meta */
$meta = AccountMeta
::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id')
->where('accounts.user_group_id', $userGroup->id)
->where('account_meta.name', 'currency_id')->groupBy('data')->get(['data']);
$meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id')
->where('accounts.user_group_id', $userGroup->id)
->where('account_meta.name', 'currency_id')->groupBy('data')->get(['data'])
;
foreach ($meta as $entry) {
$found[] = (int)$entry->data;
}
// get all from journals:
$journals = TransactionJournal
::where('user_group_id', $userGroup->id)
->groupBy('transaction_currency_id')->get(['transaction_currency_id']);
$journals = TransactionJournal::where('user_group_id', $userGroup->id)
->groupBy('transaction_currency_id')->get(['transaction_currency_id'])
;
foreach ($journals as $entry) {
$found[] = (int)$entry->transaction_currency_id;
}
// get all from transactions
$transactions = Transaction
::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.user_group_id', $userGroup->id)
->groupBy('transactions.transaction_currency_id', 'transactions.foreign_currency_id')
->get(['transactions.transaction_currency_id', 'transactions.foreign_currency_id']);
$transactions = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.user_group_id', $userGroup->id)
->groupBy('transactions.transaction_currency_id', 'transactions.foreign_currency_id')
->get(['transactions.transaction_currency_id', 'transactions.foreign_currency_id'])
;
foreach ($transactions as $entry) {
$found[] = (int)$entry->transaction_currency_id;
$found[] = (int)$entry->foreign_currency_id;
}
// get all from budget limits
$limits = BudgetLimit
::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->groupBy('transaction_currency_id')
->get(['budget_limits.transaction_currency_id']);
$limits = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->groupBy('transaction_currency_id')
->get(['budget_limits.transaction_currency_id'])
;
foreach ($limits as $entry) {
$found[] = $entry->transaction_currency_id;
}
@@ -118,12 +113,13 @@ class EnableCurrencies extends Command
array_filter(
$found,
static function (int $currencyId) {
return $currencyId !== 0;
return 0 !== $currencyId;
}
)
);
$valid = new Collection();
/** @var int $currencyId */
foreach ($found as $currencyId) {
$currency = $repos->find($currencyId);
@@ -134,12 +130,11 @@ class EnableCurrencies extends Command
$ids = $valid->pluck('id')->toArray();
Log::debug(sprintf('Found currencies for user group #%d: %s', $userGroup->id, implode(', ', $ids)));
$userGroup->currencies()->sync($ids);
/** @var GroupMembership $membership */
foreach ($userGroup->groupMemberships()->get() as $membership) {
// make sure no individual different preferences.
$membership->user->currencies()->sync([]);
}
}
}

View File

@@ -42,8 +42,6 @@ class FixAccountOrder extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -64,8 +62,6 @@ class FixAccountOrder extends Command
* Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
* executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
* be called from the handle method instead of using the constructor to initialize the command.
*
*/
private function stupidLaravel(): void
{

View File

@@ -34,7 +34,6 @@ use FireflyIII\Models\TransactionType;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use JsonException;
/**
* Class FixAccountTypes
@@ -52,8 +51,7 @@ class FixAccountTypes extends Command
/**
* Execute the console command.
*
* @return int
* @throws FireflyException|JsonException
* @throws FireflyException|\JsonException
*/
public function handle(): int
{
@@ -63,22 +61,23 @@ class FixAccountTypes extends Command
$expected = config('firefly.source_dests');
$query = TransactionJournal::leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id')
->leftJoin(
'transactions as source',
static function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 'source.transaction_journal_id')->where('source.amount', '<', 0);
}
)
->leftJoin(
'transactions as destination',
static function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 'destination.transaction_journal_id')->where('destination.amount', '>', 0);
}
)
->leftJoin('accounts as source_account', 'source.account_id', '=', 'source_account.id')
->leftJoin('accounts as destination_account', 'destination.account_id', '=', 'destination_account.id')
->leftJoin('account_types as source_account_type', 'source_account.account_type_id', '=', 'source_account_type.id')
->leftJoin('account_types as destination_account_type', 'destination_account.account_type_id', '=', 'destination_account_type.id');
->leftJoin(
'transactions as source',
static function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 'source.transaction_journal_id')->where('source.amount', '<', 0);
}
)
->leftJoin(
'transactions as destination',
static function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 'destination.transaction_journal_id')->where('destination.amount', '>', 0);
}
)
->leftJoin('accounts as source_account', 'source.account_id', '=', 'source_account.id')
->leftJoin('accounts as destination_account', 'destination.account_id', '=', 'destination_account.id')
->leftJoin('account_types as source_account_type', 'source_account.account_type_id', '=', 'source_account_type.id')
->leftJoin('account_types as destination_account_type', 'destination_account.account_type_id', '=', 'destination_account_type.id')
;
// list all valid combinations, those are allowed. So we select those which are broken.
$query->where(static function (Builder $q) use ($expected) {
@@ -98,15 +97,15 @@ class FixAccountTypes extends Command
$resultSet = $query->get(
[
'transaction_journals.id',
//'transaction_type_id as type_id',
// 'transaction_type_id as type_id',
'transaction_types.type as journal_type',
//'source.id as source_transaction_id',
//'source_account.id as source_account_id',
//'source_account_type.id as source_account_type_id',
// 'source.id as source_transaction_id',
// 'source_account.id as source_account_id',
// 'source_account_type.id as source_account_type_id',
'source_account_type.type as source_account_type',
//'destination.id as destination_transaction_id',
//'destination_account.id as destination_account_id',
//'destination_account_type.id as destination_account_type_id',
// 'destination.id as destination_transaction_id',
// 'destination_account.id as destination_account_id',
// 'destination_account_type.id as destination_account_type_id',
'destination_account_type.type as destination_account_type',
]
);
@@ -131,17 +130,11 @@ class FixAccountTypes extends Command
return 0;
}
/**
* @return void
*/
private function stupidLaravel(): void
{
$this->count = 0;
}
/**
* @param TransactionJournal $journal
*/
private function inspectJournal(TransactionJournal $journal): void
{
app('log')->debug(sprintf('Now inspecting journal #%d', $journal->id));
@@ -179,36 +172,20 @@ class FixAccountTypes extends Command
}
}
/**
* @param TransactionJournal $journal
*
* @return Transaction
*/
private function getSourceTransaction(TransactionJournal $journal): Transaction
{
return $journal->transactions->firstWhere('amount', '<', 0);
}
/**
* @param TransactionJournal $journal
*
* @return Transaction
*/
private function getDestinationTransaction(TransactionJournal $journal): Transaction
{
return $journal->transactions->firstWhere('amount', '>', 0);
}
/**
* @param TransactionJournal $journal
* @param string $transactionType
* @param Transaction $source
* @param Transaction $dest
*/
private function fixJournal(TransactionJournal $journal, string $transactionType, Transaction $source, Transaction $dest): void
{
app('log')->debug(sprintf('Going to fix journal #%d', $journal->id));
$this->count++;
++$this->count;
// variables:
$sourceType = $source->account->accountType->type;
$destinationType = $dest->account->accountType->type;
@@ -217,18 +194,22 @@ class FixAccountTypes extends Command
if ($this->shouldBeTransfer($transactionType, $sourceType, $destinationType)) {
$this->makeTransfer($journal);
return;
}
if ($this->shouldBeDeposit($transactionType, $sourceType, $destinationType)) {
$this->makeDeposit($journal);
return;
}
if ($this->shouldGoToExpenseAccount($transactionType, $sourceType, $destinationType)) {
$this->makeExpenseDestination($journal, $dest);
return;
}
if ($this->shouldComeFromRevenueAccount($transactionType, $sourceType, $destinationType)) {
$this->makeRevenueSource($journal, $source);
return;
}
@@ -238,6 +219,7 @@ class FixAccountTypes extends Command
$hasValidSource = $this->hasValidAccountType($validSources, $sourceType);
if (!$hasValidSource && $canCreateSource) {
$this->giveNewRevenue($journal, $source);
return;
}
if (!$canCreateSource && !$hasValidSource) {
@@ -245,14 +227,17 @@ class FixAccountTypes extends Command
$message = sprintf('The source account of %s #%d cannot be of type "%s". Firefly III cannot fix this. You may have to remove the transaction yourself.', $transactionType, $journal->id, $source->account->accountType->type);
$this->friendlyError($message);
app('log')->debug($message);
return;
}
/** @var array $validDestinations */
$validDestinations = $this->expected[$transactionType][$sourceType] ?? [];
$canCreateDestination = $this->canCreateDestination($validDestinations);
$hasValidDestination = $this->hasValidAccountType($validDestinations, $destinationType);
if (!$hasValidDestination && $canCreateDestination) {
$this->giveNewExpense($journal, $dest);
return;
}
if (!$canCreateDestination && !$hasValidDestination) {
@@ -263,69 +248,31 @@ class FixAccountTypes extends Command
}
}
/**
* @param string $destinationType
*
* @return bool
*/
private function isLiability(string $destinationType): bool
{
return AccountType::LOAN === $destinationType || AccountType::DEBT === $destinationType || AccountType::MORTGAGE === $destinationType;
}
/**
* @param string $transactionType
* @param string $sourceType
* @param string $destinationType
*
* @return bool
*/
private function shouldBeTransfer(string $transactionType, string $sourceType, string $destinationType): bool
{
return $transactionType === TransactionType::TRANSFER && AccountType::ASSET === $sourceType && $this->isLiability($destinationType);
return TransactionType::TRANSFER === $transactionType && AccountType::ASSET === $sourceType && $this->isLiability($destinationType);
}
/**
* @param string $transactionType
* @param string $sourceType
* @param string $destinationType
*
* @return bool
*/
private function shouldBeDeposit(string $transactionType, string $sourceType, string $destinationType): bool
{
return $transactionType === TransactionType::TRANSFER && $this->isLiability($sourceType) && AccountType::ASSET === $destinationType;
return TransactionType::TRANSFER === $transactionType && $this->isLiability($sourceType) && AccountType::ASSET === $destinationType;
}
/**
* @param string $transactionType
* @param string $sourceType
* @param string $destinationType
*
* @return bool
*/
private function shouldGoToExpenseAccount(string $transactionType, string $sourceType, string $destinationType): bool
{
return $transactionType === TransactionType::WITHDRAWAL && AccountType::ASSET === $sourceType && AccountType::REVENUE === $destinationType;
return TransactionType::WITHDRAWAL === $transactionType && AccountType::ASSET === $sourceType && AccountType::REVENUE === $destinationType;
}
/**
* @param string $transactionType
* @param string $sourceType
* @param string $destinationType
*
* @return bool
*/
private function shouldComeFromRevenueAccount(string $transactionType, string $sourceType, string $destinationType): bool
{
return $transactionType === TransactionType::DEPOSIT && AccountType::EXPENSE === $sourceType && AccountType::ASSET === $destinationType;
return TransactionType::DEPOSIT === $transactionType && AccountType::EXPENSE === $sourceType && AccountType::ASSET === $destinationType;
}
/**
* @param TransactionJournal $journal
*
* @return void
*/
private function makeTransfer(TransactionJournal $journal): void
{
// from an asset to a liability should be a withdrawal:
@@ -339,11 +286,6 @@ class FixAccountTypes extends Command
$this->inspectJournal($journal);
}
/**
* @param TransactionJournal $journal
*
* @return void
*/
private function makeDeposit(TransactionJournal $journal): void
{
// from a liability to an asset should be a deposit.
@@ -357,12 +299,6 @@ class FixAccountTypes extends Command
$this->inspectJournal($journal);
}
/**
* @param TransactionJournal $journal
* @param Transaction $destination
*
* @return void
*/
private function makeExpenseDestination(TransactionJournal $journal, Transaction $destination): void
{
// withdrawals with a revenue account as destination instead of an expense account.
@@ -384,12 +320,6 @@ class FixAccountTypes extends Command
$this->inspectJournal($journal);
}
/**
* @param TransactionJournal $journal
* @param Transaction $source
*
* @return void
*/
private function makeRevenueSource(TransactionJournal $journal, Transaction $source): void
{
// deposits with an expense account as source instead of a revenue account.
@@ -414,43 +344,22 @@ class FixAccountTypes extends Command
/**
* Can only create revenue accounts out of the blue.
*
* @param array $validSources
*
* @return bool
*/
private function canCreateSource(array $validSources): bool
{
return in_array(AccountTypeEnum::REVENUE->value, $validSources, true);
}
/**
* @param array $validTypes
* @param string $accountType
*
* @return bool
*/
private function hasValidAccountType(array $validTypes, string $accountType): bool
{
return in_array($accountType, $validTypes, true);
}
/**
* @param array $validDestinations
*
* @return bool
*/
private function canCreateDestination(array $validDestinations): bool
{
return in_array(AccountTypeEnum::EXPENSE->value, $validDestinations, true);
}
/**
* @param TransactionJournal $journal
* @param Transaction $source
*
* @return void
*/
private function giveNewRevenue(TransactionJournal $journal, Transaction $source): void
{
app('log')->debug(sprintf('An account of type "%s" could be a valid source.', AccountTypeEnum::REVENUE->value));
@@ -464,12 +373,6 @@ class FixAccountTypes extends Command
$this->inspectJournal($journal);
}
/**
* @param TransactionJournal $journal
* @param Transaction $destination
*
* @return void
*/
private function giveNewExpense(TransactionJournal $journal, Transaction $destination)
{
app('log')->debug(sprintf('An account of type "%s" could be a valid destination.', AccountTypeEnum::EXPENSE->value));
@@ -482,5 +385,4 @@ class FixAccountTypes extends Command
app('log')->debug(sprintf('Associated account #%d with transaction #%d', $newDestination->id, $destination->id));
$this->inspectJournal($journal);
}
}

View File

@@ -43,12 +43,11 @@ class FixFrontpageAccounts extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$users = User::get();
/** @var User $user */
foreach ($users as $user) {
$preference = app('preferences')->getForUser($user, 'frontPageAccounts');
@@ -61,12 +60,10 @@ class FixFrontpageAccounts extends Command
return 0;
}
/**
* @param Preference $preference
*/
private function fixPreference(Preference $preference): void
{
$fixed = [];
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
if (null === $preference->user) {

View File

@@ -24,7 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Correction;
use DB;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Events\UpdatedTransactionGroup;
use FireflyIII\Handlers\Events\UpdatedGroupEventHandler;
@@ -44,14 +43,14 @@ class FixGroupAccounts extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$groups = [];
$res = TransactionJournal::groupBy('transaction_group_id')
->get(['transaction_group_id', DB::raw('COUNT(transaction_group_id) as the_count')]);// @phpstan-ignore-line
->get(['transaction_group_id', \DB::raw('COUNT(transaction_group_id) as the_count')])// @phpstan-ignore-line
;
/** @var TransactionJournal $journal */
foreach ($res as $journal) {
if ((int)$journal->the_count > 1) {

View File

@@ -43,8 +43,6 @@ class FixIbans extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -58,11 +56,6 @@ class FixIbans extends Command
return 0;
}
/**
* @param Collection $accounts
*
* @return void
*/
private function filterIbans(Collection $accounts): void
{
/** @var Account $account */
@@ -74,20 +67,16 @@ class FixIbans extends Command
$account->iban = $iban;
$account->save();
$this->friendlyInfo(sprintf('Removed spaces from IBAN of account #%d', $account->id));
$this->count++;
++$this->count;
}
}
}
}
/**
* @param Collection $accounts
*
* @return void
*/
private function countAndCorrectIbans(Collection $accounts): void
{
$set = [];
/** @var Account $account */
foreach ($accounts as $account) {
$userId = $account->user_id;
@@ -103,9 +92,8 @@ class FixIbans extends Command
if (array_key_exists($iban, $set[$userId])) {
// iban already in use! two exceptions exist:
if (
!(AccountType::EXPENSE === $set[$userId][$iban] && AccountType::REVENUE === $type)
&& // allowed combination
!(AccountType::REVENUE === $set[$userId][$iban] && AccountType::EXPENSE === $type) // also allowed combination.
!(AccountType::EXPENSE === $set[$userId][$iban] && AccountType::REVENUE === $type) // allowed combination
&& !(AccountType::REVENUE === $set[$userId][$iban] && AccountType::EXPENSE === $type) // also allowed combination.
) {
$this->friendlyWarning(
sprintf(
@@ -118,7 +106,7 @@ class FixIbans extends Command
);
$account->iban = null;
$account->save();
$this->count++;
++$this->count;
}
}

View File

@@ -42,31 +42,31 @@ class FixLongDescriptions extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$journals = TransactionJournal::get(['id', 'description']);
$count = 0;
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
if (strlen($journal->description) > self::MAX_LENGTH) {
$journal->description = substr($journal->description, 0, self::MAX_LENGTH);
$journal->save();
$this->friendlyWarning(sprintf('Truncated description of transaction journal #%d', $journal->id));
$count++;
++$count;
}
}
$groups = TransactionGroup::get(['id', 'title']);
/** @var TransactionGroup $group */
foreach ($groups as $group) {
if (strlen((string)$group->title) > self::MAX_LENGTH) {
$group->title = substr($group->title, 0, self::MAX_LENGTH);
$group->save();
$this->friendlyWarning(sprintf('Truncated description of transaction group #%d', $group->id));
$count++;
++$count;
}
}
if (0 === $count) {

View File

@@ -42,8 +42,6 @@ class FixPiggies extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -55,13 +53,15 @@ class FixPiggies extends Command
if (null === $event->transaction_journal_id) {
continue;
}
/** @var TransactionJournal|null $journal */
/** @var null|TransactionJournal $journal */
$journal = $event->transactionJournal;
if (null === $journal) {
$event->transaction_journal_id = null;
$event->save();
$count++;
++$count;
continue;
}
}

View File

@@ -48,8 +48,6 @@ class FixRecurringTransactions extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -66,8 +64,6 @@ class FixRecurringTransactions extends Command
* Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
* executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
* be called from the handle method instead of using the constructor to initialize the command.
*
*/
private function stupidLaravel(): void
{
@@ -75,34 +71,27 @@ class FixRecurringTransactions extends Command
$this->userRepos = app(UserRepositoryInterface::class);
}
/**
*
*/
private function correctTransactions(): void
{
$users = $this->userRepos->all();
/** @var User $user */
foreach ($users as $user) {
$this->processUser($user);
}
}
/**
* @param User $user
*/
private function processUser(User $user): void
{
$this->recurringRepos->setUser($user);
$recurrences = $this->recurringRepos->get();
/** @var Recurrence $recurrence */
foreach ($recurrences as $recurrence) {
$this->processRecurrence($recurrence);
}
}
/**
* @param Recurrence $recurrence
*/
private function processRecurrence(Recurrence $recurrence): void
{
/** @var RecurrenceTransaction $transaction */
@@ -111,10 +100,6 @@ class FixRecurringTransactions extends Command
}
}
/**
* @param Recurrence $recurrence
* @param RecurrenceTransaction $transaction
*/
private function processTransaction(Recurrence $recurrence, RecurrenceTransaction $transaction): void
{
$source = $transaction->sourceAccount;
@@ -129,7 +114,7 @@ class FixRecurringTransactions extends Command
if (null !== $transactionType) {
$recurrence->transaction_type_id = $transactionType->id;
$recurrence->save();
$this->count++;
++$this->count;
}
}
}

View File

@@ -45,18 +45,17 @@ class FixTransactionTypes extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$count = 0;
$journals = $this->collectJournals();
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$fixed = $this->fixJournal($journal);
if (true === $fixed) {
$count++;
++$count;
}
}
if ($count > 0) {
@@ -71,23 +70,18 @@ class FixTransactionTypes extends Command
/**
* Collect all transaction journals.
*
* @return Collection
*/
private function collectJournals(): Collection
{
return TransactionJournal::with(['transactionType', 'transactions', 'transactions.account', 'transactions.account.accountType'])
->get();
->get()
;
}
/**
* @param TransactionJournal $journal
*
* @return bool
*/
private function fixJournal(TransactionJournal $journal): bool
{
$type = $journal->transactionType->type;
try {
$source = $this->getSourceAccount($journal);
$destination = $this->getDestinationAccount($journal);
@@ -117,9 +111,6 @@ class FixTransactionTypes extends Command
}
/**
* @param TransactionJournal $journal
*
* @return Account
* @throws FireflyException
*/
private function getSourceAccount(TransactionJournal $journal): Account
@@ -135,9 +126,11 @@ class FixTransactionTypes extends Command
if (1 !== $collection->count()) {
throw new FireflyException(sprintf('300002: Journal #%d has multiple source transactions.', $journal->id));
}
/** @var Transaction $transaction */
$transaction = $collection->first();
/** @var Account|null $account */
/** @var null|Account $account */
$account = $transaction->account;
if (null === $account) {
throw new FireflyException(sprintf('300003: Journal #%d, transaction #%d has no source account.', $journal->id, $transaction->id));
@@ -147,9 +140,6 @@ class FixTransactionTypes extends Command
}
/**
* @param TransactionJournal $journal
*
* @return Account
* @throws FireflyException
*/
private function getDestinationAccount(TransactionJournal $journal): Account
@@ -165,9 +155,11 @@ class FixTransactionTypes extends Command
if (1 !== $collection->count()) {
throw new FireflyException(sprintf('300005: Journal #%d has multiple destination transactions.', $journal->id));
}
/** @var Transaction $transaction */
$transaction = $collection->first();
/** @var Account|null $account */
/** @var null|Account $account */
$account = $transaction->account;
if (null === $account) {
throw new FireflyException(sprintf('300006: Journal #%d, transaction #%d has no destination account.', $journal->id, $transaction->id));
@@ -176,10 +168,6 @@ class FixTransactionTypes extends Command
return $account;
}
/**
* @param TransactionJournal $journal
* @param string $expectedType
*/
private function changeJournal(TransactionJournal $journal, string $expectedType): void
{
$type = TransactionType::whereType($expectedType)->first();

View File

@@ -23,14 +23,11 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Correction;
use DB;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use stdClass;
use ValueError;
/**
* Class FixUnevenAmount
@@ -44,23 +41,23 @@ class FixUnevenAmount extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$count = 0;
$journals = DB::table('transactions')
->groupBy('transaction_journal_id')
->whereNull('deleted_at')
->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')]);
/** @var stdClass $entry */
$journals = \DB::table('transactions')
->groupBy('transaction_journal_id')
->whereNull('deleted_at')
->get(['transaction_journal_id', \DB::raw('SUM(amount) AS the_sum')])
;
/** @var \stdClass $entry */
foreach ($journals as $entry) {
$sum = (string)$entry->the_sum;
if (!is_numeric($sum) ||
'' === $sum || // @phpstan-ignore-line
str_contains($sum, 'e') ||
str_contains($sum, ',')) {
if (!is_numeric($sum)
|| '' === $sum // @phpstan-ignore-line
|| str_contains($sum, 'e')
|| str_contains($sum, ',')) {
$message = sprintf(
'Journal #%d has an invalid sum ("%s"). No sure what to do.',
$entry->transaction_journal_id,
@@ -68,13 +65,15 @@ class FixUnevenAmount extends Command
);
$this->friendlyWarning($message);
app('log')->warning($message);
$count++;
++$count;
continue;
}
$res = -1;
try {
$res = bccomp($sum, '0');
} catch (ValueError $e) {
} catch (\ValueError $e) {
$this->friendlyError(sprintf('Could not bccomp("%s", "0").', $sum));
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
@@ -88,7 +87,7 @@ class FixUnevenAmount extends Command
$this->friendlyWarning($message);
app('log')->warning($message);
$this->fixJournal($entry->transaction_journal_id);
$count++;
++$count;
}
}
if (0 === $count) {
@@ -98,9 +97,6 @@ class FixUnevenAmount extends Command
return 0;
}
/**
* @param int $param
*/
private function fixJournal(int $param): void
{
// one of the transactions is bad.
@@ -108,7 +104,8 @@ class FixUnevenAmount extends Command
if (null === $journal) {
return;
}
/** @var Transaction|null $source */
/** @var null|Transaction $source */
$source = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $source) {
@@ -128,7 +125,7 @@ class FixUnevenAmount extends Command
$amount = bcmul('-1', $source->amount);
// fix amount of destination:
/** @var Transaction|null $destination */
/** @var null|Transaction $destination */
$destination = $journal->transactions()->where('amount', '>', 0)->first();
if (null === $destination) {

View File

@@ -40,17 +40,16 @@ class RemoveBills extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
/** @var TransactionType|null $withdrawal */
/** @var null|TransactionType $withdrawal */
$withdrawal = TransactionType::where('type', TransactionType::WITHDRAWAL)->first();
if (null === $withdrawal) {
return 0;
}
$journals = TransactionJournal::whereNotNull('bill_id')->where('transaction_type_id', '!=', $withdrawal->id)->get();
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$this->friendlyWarning(sprintf('Transaction journal #%d will be unlinked from bill #%d.', $journal->id, $journal->bill_id));

View File

@@ -23,7 +23,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Correction;
use DB;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
@@ -41,8 +40,6 @@ class RenameMetaFields extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -69,18 +66,16 @@ class RenameMetaFields extends Command
if (0 !== $this->count) {
$this->friendlyInfo(sprintf('Renamed %d meta field(s).', $this->count));
}
return 0;
}
/**
* @param string $original
* @param string $update
*/
private function rename(string $original, string $update): void
{
$total = DB::table('journal_meta')
->where('name', '=', $original)
->update(['name' => $update]);
$total = \DB::table('journal_meta')
->where('name', '=', $original)
->update(['name' => $update])
;
$this->count += $total;
}
}

View File

@@ -40,24 +40,24 @@ class TransferBudgets extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$set = TransactionJournal::distinct()
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->leftJoin('budget_transaction_journal', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id')
->whereNotIn('transaction_types.type', [TransactionType::WITHDRAWAL])
->whereNotNull('budget_transaction_journal.budget_id')->get(['transaction_journals.*']);
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->leftJoin('budget_transaction_journal', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id')
->whereNotIn('transaction_types.type', [TransactionType::WITHDRAWAL])
->whereNotNull('budget_transaction_journal.budget_id')->get(['transaction_journals.*'])
;
$count = 0;
/** @var TransactionJournal $entry */
foreach ($set as $entry) {
$message = sprintf('Transaction journal #%d is a %s, so has no longer a budget.', $entry->id, $entry->transactionType->type);
$this->friendlyInfo($message);
app('log')->debug($message);
$entry->budgets()->sync([]);
$count++;
++$count;
}
if (0 === $count) {
$message = 'No invalid budget/journal entries.';
@@ -68,6 +68,7 @@ class TransferBudgets extends Command
app('log')->debug($message);
$this->friendlyInfo($message);
}
return 0;
}
}

View File

@@ -1,6 +1,5 @@
<?php
/*
* TriggerCreditCalculation.php
* Copyright (c) 2023 james@firefly-iii.org
@@ -39,8 +38,6 @@ class TriggerCreditCalculation extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -49,24 +46,17 @@ class TriggerCreditCalculation extends Command
return 0;
}
/**
* @return void
*/
private function processAccounts(): void
{
$accounts = Account::leftJoin('account_types', 'accounts.account_type_id', 'account_types.id')
->whereIn('account_types.type', config('firefly.valid_liabilities'))
->get(['accounts.*']);
->whereIn('account_types.type', config('firefly.valid_liabilities'))
->get(['accounts.*'])
;
foreach ($accounts as $account) {
$this->processAccount($account);
}
}
/**
* @param Account $account
*
* @return void
*/
private function processAccount(Account $account): void
{
/** @var CreditRecalculateService $object */