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 */

View File

@@ -25,7 +25,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Export;
use Carbon\Carbon;
use Exception;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Console\Commands\VerifiesAccessToken;
use FireflyIII\Exceptions\FireflyException;
@@ -36,7 +35,6 @@ use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Support\Export\ExportDataGenerator;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use InvalidArgumentException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
@@ -48,7 +46,6 @@ class ExportData extends Command
use ShowsFriendlyMessages;
use VerifiesAccessToken;
protected $description = 'Command to export data from Firefly III.';
protected $signature = 'firefly-iii:export-data
@@ -74,7 +71,6 @@ class ExportData extends Command
/**
* Execute the console command.
*
* @return int
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
@@ -92,6 +88,7 @@ class ExportData extends Command
$user = $this->getUser();
$this->journalRepository->setUser($user);
$this->accountRepository->setUser($user);
// get the options.
try {
$options = $this->parseOptions();
@@ -100,6 +97,7 @@ class ExportData extends Command
return 1;
}
// make export object and configure it.
/** @var ExportDataGenerator $exporter */
$exporter = app(ExportDataGenerator::class);
@@ -139,8 +137,6 @@ class ExportData 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
{
@@ -149,9 +145,8 @@ class ExportData extends Command
}
/**
* @return array
* @throws FireflyException
* @throws Exception
* @throws \Exception
*/
private function parseOptions(): array
{
@@ -181,10 +176,7 @@ class ExportData extends Command
}
/**
* @param string $field
*
* @return Carbon
* @throws Exception
* @throws \Exception
*/
private function getDateParameter(string $field): Carbon
{
@@ -198,13 +190,14 @@ class ExportData extends Command
if (is_string($this->option($field))) {
try {
$date = Carbon::createFromFormat('!Y-m-d', $this->option($field));
} catch (InvalidArgumentException $e) {
} catch (\InvalidArgumentException $e) {
app('log')->error($e->getMessage());
$this->friendlyError(sprintf('%s date "%s" must be formatted YYYY-MM-DD. Field will be ignored.', $field, $this->option('start')));
$error = true;
}
if (false === $date) {
$this->friendlyError(sprintf('%s date "%s" must be formatted YYYY-MM-DD.', $field, $this->option('start')));
throw new FireflyException(sprintf('%s date "%s" must be formatted YYYY-MM-DD.', $field, $this->option('start')));
}
}
@@ -217,12 +210,14 @@ class ExportData extends Command
$journal = $this->journalRepository->firstNull();
$date = null === $journal ? today(config('app.timezone'))->subYear() : $journal->date;
$date->startOfDay();
return $date;
}
// field can only be 'end' at this point, so no need to include it in the check.
if (true === $error) {
$date = today(config('app.timezone'));
$date->endOfDay();
return $date;
}
@@ -234,7 +229,6 @@ class ExportData extends Command
}
/**
* @return Collection
* @throws FireflyException
*/
private function getAccountsParameter(): Collection
@@ -250,6 +244,7 @@ class ExportData extends Command
if ('' === $accountList) {
$accounts = $this->accountRepository->getAccountsByType($types);
}
// filter accounts,
/** @var Account $account */
foreach ($accounts as $account) {
@@ -265,9 +260,7 @@ class ExportData extends Command
}
/**
* @return string
* @throws FireflyException
*
*/
private function getExportDirectory(): string
{
@@ -283,9 +276,6 @@ class ExportData extends Command
}
/**
* @param array $options
* @param array $data
*
* @throws FireflyException
*/
private function exportData(array $options, array $data): void

View File

@@ -47,7 +47,6 @@ class CreateGroupMemberships extends Command
/**
* Execute the console command.
*
* @return int
* @throws FireflyException
*/
public function handle(): int
@@ -58,24 +57,9 @@ class CreateGroupMemberships extends Command
return 0;
}
/**
*
* @throws FireflyException
*/
private function createGroupMemberships(): void
{
$users = User::get();
/** @var User $user */
foreach ($users as $user) {
self::createGroupMembership($user);
}
}
/**
* TODO move to helper.
*
* @param User $user
*
* @throws FireflyException
*/
public static function createGroupMembership(User $user): void
@@ -92,8 +76,9 @@ class CreateGroupMemberships extends Command
throw new FireflyException('Firefly III could not find a user role. Please make sure all migrations have run.');
}
$membership = GroupMembership::where('user_id', $user->id)
->where('user_group_id', $userGroup->id)
->where('user_role_id', $userRole->id)->first();
->where('user_group_id', $userGroup->id)
->where('user_role_id', $userRole->id)->first()
;
if (null === $membership) {
GroupMembership::create(
[
@@ -108,4 +93,17 @@ class CreateGroupMemberships extends Command
$user->save();
}
}
/**
* @throws FireflyException
*/
private function createGroupMemberships(): void
{
$users = User::get();
/** @var User $user */
foreach ($users as $user) {
self::createGroupMembership($user);
}
}
}

View File

@@ -29,7 +29,6 @@ use FireflyIII\Models\Budget;
use FireflyIII\Models\Category;
use FireflyIII\Models\Tag;
use Illuminate\Console\Command;
use stdClass;
/**
* Class ReportEmptyObjects
@@ -38,15 +37,12 @@ class ReportEmptyObjects extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Reports on empty database objects.';
protected $signature = 'firefly-iii:report-empty-objects';
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -65,13 +61,14 @@ class ReportEmptyObjects extends Command
private function reportEmptyBudgets(): void
{
$set = Budget::leftJoin('budget_transaction_journal', 'budgets.id', '=', 'budget_transaction_journal.budget_id')
->leftJoin('users', 'budgets.user_id', '=', 'users.id')
->distinct()
->whereNull('budget_transaction_journal.budget_id')
->whereNull('budgets.deleted_at')
->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email']);
->leftJoin('users', 'budgets.user_id', '=', 'users.id')
->distinct()
->whereNull('budget_transaction_journal.budget_id')
->whereNull('budgets.deleted_at')
->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email'])
;
/** @var stdClass $entry */
/** @var \stdClass $entry */
foreach ($set as $entry) {
$line = sprintf(
'User #%d (%s) has budget #%d ("%s") which has no transaction journals.',
@@ -90,13 +87,14 @@ class ReportEmptyObjects extends Command
private function reportEmptyCategories(): void
{
$set = Category::leftJoin('category_transaction_journal', 'categories.id', '=', 'category_transaction_journal.category_id')
->leftJoin('users', 'categories.user_id', '=', 'users.id')
->distinct()
->whereNull('category_transaction_journal.category_id')
->whereNull('categories.deleted_at')
->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email']);
->leftJoin('users', 'categories.user_id', '=', 'users.id')
->distinct()
->whereNull('category_transaction_journal.category_id')
->whereNull('categories.deleted_at')
->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email'])
;
/** @var stdClass $entry */
/** @var \stdClass $entry */
foreach ($set as $entry) {
$line = sprintf(
'User #%d (%s) has category #%d ("%s") which has no transaction journals.',
@@ -109,19 +107,17 @@ class ReportEmptyObjects extends Command
}
}
/**
*
*/
private function reportEmptyTags(): void
{
$set = Tag::leftJoin('tag_transaction_journal', 'tags.id', '=', 'tag_transaction_journal.tag_id')
->leftJoin('users', 'tags.user_id', '=', 'users.id')
->distinct()
->whereNull('tag_transaction_journal.tag_id')
->whereNull('tags.deleted_at')
->get(['tags.id', 'tags.tag', 'tags.user_id', 'users.email']);
->leftJoin('users', 'tags.user_id', '=', 'users.id')
->distinct()
->whereNull('tag_transaction_journal.tag_id')
->whereNull('tags.deleted_at')
->get(['tags.id', 'tags.tag', 'tags.user_id', 'users.email'])
;
/** @var stdClass $entry */
/** @var \stdClass $entry */
foreach ($set as $entry) {
$line = sprintf(
'User #%d (%s) has tag #%d ("%s") which has no transaction journals.',
@@ -140,14 +136,15 @@ class ReportEmptyObjects extends Command
private function reportAccounts(): void
{
$set = Account::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id')
->leftJoin('users', 'accounts.user_id', '=', 'users.id')
->groupBy(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email'])
->whereNull('transactions.account_id')
->get(
['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email']
);
->leftJoin('users', 'accounts.user_id', '=', 'users.id')
->groupBy(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email'])
->whereNull('transactions.account_id')
->get(
['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email']
)
;
/** @var stdClass $entry */
/** @var \stdClass $entry */
foreach ($set as $entry) {
$line = 'User #%d (%s) has account #%d ("%s") which has no transactions.';
$line = sprintf($line, $entry->user_id, $entry->email, $entry->id, $entry->name);
@@ -161,10 +158,11 @@ class ReportEmptyObjects extends Command
private function reportBudgetLimits(): void
{
$set = Budget::leftJoin('budget_limits', 'budget_limits.budget_id', '=', 'budgets.id')
->leftJoin('users', 'budgets.user_id', '=', 'users.id')
->groupBy(['budgets.id', 'budgets.name', 'budgets.encrypted', 'budgets.user_id', 'users.email'])
->whereNull('budget_limits.id')
->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'budgets.encrypted', 'users.email']);
->leftJoin('users', 'budgets.user_id', '=', 'users.id')
->groupBy(['budgets.id', 'budgets.name', 'budgets.encrypted', 'budgets.user_id', 'users.email'])
->whereNull('budget_limits.id')
->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'budgets.encrypted', 'users.email'])
;
/** @var Budget $entry */
foreach ($set as $entry) {

View File

@@ -25,18 +25,14 @@ namespace FireflyIII\Console\Commands\Integrity;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
use Schema;
/**
* Class ReportIntegrity
*
*/
class ReportIntegrity extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Will report on the integrity of your database.';
protected $signature = 'firefly-iii:report-integrity';
@@ -47,7 +43,7 @@ class ReportIntegrity extends Command
public function handle(): int
{
// if table does not exist, return false
if (!Schema::hasTable('users')) {
if (!\Schema::hasTable('users')) {
return 1;
}
$commands = [

View File

@@ -40,8 +40,6 @@ class ReportSum extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -64,6 +62,7 @@ class ReportSum extends Command
if (!is_numeric($sum)) {
$message = sprintf('Error: Transactions for user #%d (%s) have an invalid sum ("%s").', $user->id, $user->email, $sum);
$this->friendlyError($message);
continue;
}
if (0 !== bccomp($sum, '0')) {

View File

@@ -40,8 +40,6 @@ class RestoreOAuthKeys extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -50,9 +48,6 @@ class RestoreOAuthKeys extends Command
return 0;
}
/**
*
*/
private function restoreOAuthKeys(): void
{
if (!$this->keysInDatabase() && !$this->keysOnDrive()) {
@@ -84,41 +79,26 @@ class RestoreOAuthKeys extends Command
$this->friendlyPositive('OAuth keys are OK');
}
/**
* @return bool
*/
private function keysInDatabase(): bool
{
return OAuthKeys::keysInDatabase();
}
/**
* @return bool
*/
private function keysOnDrive(): bool
{
return OAuthKeys::hasKeyFiles();
}
/**
*
*/
private function generateKeys(): void
{
OAuthKeys::generateKeys();
}
/**
*
*/
private function storeKeysInDB(): void
{
OAuthKeys::storeKeysInDB();
}
/**
*
*/
private function restoreKeysFromDB(): bool
{
return OAuthKeys::restoreKeysFromDB();

View File

@@ -66,6 +66,7 @@ class UpdateGroupInformation extends Command
// recurrences, rule groups, rules, tags, transaction groups, transaction journals, webhooks
$users = User::get();
/** @var User $user */
foreach ($users as $user) {
$this->updateGroupInfo($user);
@@ -74,11 +75,6 @@ class UpdateGroupInformation extends Command
return 0;
}
/**
* @param User $user
*
* @return void
*/
private function updateGroupInfo(User $user): void
{
$group = $user->userGroup;
@@ -109,13 +105,6 @@ class UpdateGroupInformation extends Command
}
}
/**
* @param User $user
* @param UserGroup $group
* @param string $className
*
* @return void
*/
private function updateGroupInfoForObject(User $user, UserGroup $group, string $className): void
{
try {

View File

@@ -1,6 +1,5 @@
<?php
/*
* ShowsFriendlyMessages.php
* Copyright (c) 2023 james@firefly-iii.org
@@ -30,64 +29,33 @@ namespace FireflyIII\Console\Commands;
*/
trait ShowsFriendlyMessages
{
/**
* @param string $message
*
* @return void
*/
public function friendlyError(string $message): void
{
$this->error(sprintf(' [x] %s', trim($message)));
}
/**
* @param string $message
*
* @return void
*/
public function friendlyInfo(string $message): void
{
$this->friendlyNeutral($message);
}
/**
* @param string $message
*
* @return void
*/
public function friendlyNeutral(string $message): void
{
$this->line(sprintf(' [i] %s', trim($message)));
}
/**
* @param string $message
*
* @return void
*/
public function friendlyLine(string $message): void
{
$this->line(sprintf(' %s', trim($message)));
}
/**
* @param string $message
*
* @return void
*/
public function friendlyPositive(string $message): void
{
$this->info(sprintf(' [✓] %s', trim($message)));
}
/**
* @param string $message
*
* @return void
*/
public function friendlyWarning(string $message): void
{
$this->warn(sprintf(' [!] %s', trim($message)));
}
}

View File

@@ -27,7 +27,6 @@ namespace FireflyIII\Console\Commands\System;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
use PDO;
use PDOException;
/**
* Class CreateDatabase
@@ -36,15 +35,12 @@ class CreateDatabase extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Tries to create the database if it doesn\'t exist yet.';
protected $signature = 'firefly-iii:create-database';
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -63,16 +59,17 @@ class CreateDatabase extends Command
$this->friendlyLine(sprintf('DSN is %s', $dsn));
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
// when it fails, display error
try {
$pdo = new PDO($dsn, env('DB_USERNAME'), env('DB_PASSWORD'), $options);
} catch (PDOException $e) {
$pdo = new \PDO($dsn, env('DB_USERNAME'), env('DB_PASSWORD'), $options);
} catch (\PDOException $e) {
$this->friendlyError(sprintf('Error when connecting to DB: %s', $e->getMessage()));
return 1;
}

View File

@@ -28,18 +28,14 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Str;
/**
* Class CreateFirstUser
*
* @package FireflyIII\Console\Commands
*/
class CreateFirstUser 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}';
@@ -47,8 +43,6 @@ class CreateFirstUser extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -70,11 +64,11 @@ class CreateFirstUser extends Command
'email' => $this->argument('email'),
'role' => 'owner',
];
$password = Str::random(24);
$password = \Str::random(24);
$user = $this->repository->store($data);
$user->password = Hash::make($password);
$user->save();
$user->setRememberToken(Str::random(60));
$user->setRememberToken(\Str::random(60));
$this->friendlyInfo(sprintf('Created new admin user (ID #%d) with email address "%s" and password "%s".', $user->id, $user->email, $password));
$this->friendlyWarning('Change this password.');
@@ -86,8 +80,6 @@ class CreateFirstUser 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

@@ -58,17 +58,17 @@ class ForceDecimalSize extends Command
private string $cast;
private array $classes
= [
'accounts' => Account::class,
'auto_budgets' => AutoBudget::class,
'available_budgets' => AvailableBudget::class,
'bills' => Bill::class,
'budget_limits' => BudgetLimit::class,
'piggy_bank_events' => PiggyBankEvent::class,
'piggy_bank_repetitions' => PiggyBankRepetition::class,
'piggy_banks' => PiggyBank::class,
'recurrences_transactions' => RecurrenceTransaction::class,
'transactions' => Transaction::class,
];
'accounts' => Account::class,
'auto_budgets' => AutoBudget::class,
'available_budgets' => AvailableBudget::class,
'bills' => Bill::class,
'budget_limits' => BudgetLimit::class,
'piggy_bank_events' => PiggyBankEvent::class,
'piggy_bank_repetitions' => PiggyBankRepetition::class,
'piggy_banks' => PiggyBank::class,
'recurrences_transactions' => RecurrenceTransaction::class,
'transactions' => Transaction::class,
];
private string $operator;
private string $regularExpression;
@@ -90,7 +90,6 @@ class ForceDecimalSize extends Command
/**
* Execute the console command.
*
*/
public function handle(): int
{
@@ -108,9 +107,6 @@ class ForceDecimalSize extends Command
return 0;
}
/**
* @return void
*/
private function determineDatabaseType(): void
{
// switch stuff based on database connection:
@@ -129,8 +125,6 @@ class ForceDecimalSize extends Command
/**
* This method checks if a basic check can be done or if it needs to be complicated.
*
* @return void
*/
private function correctAmounts(): void
{
@@ -155,13 +149,13 @@ class ForceDecimalSize extends Command
/**
* This method loops all enabled currencies and then calls the method that will fix all objects in this currency.
*
* @return void
* @throws FireflyException
*/
private function correctAmountsByCurrency(): void
{
/** @var Collection $enabled */
$enabled = TransactionCurrency::whereEnabled(1)->get();
/** @var TransactionCurrency $currency */
foreach ($enabled as $currency) {
$this->correctByCurrency($currency);
@@ -171,9 +165,6 @@ class ForceDecimalSize extends Command
/**
* This method loops the available tables that may need fixing, and calls for the right method that can fix them.
*
* @param TransactionCurrency $currency
*
* @return void
* @throws FireflyException
*/
private function correctByCurrency(TransactionCurrency $currency): void
@@ -187,32 +178,46 @@ class ForceDecimalSize extends Command
default:
$message = sprintf('Cannot handle table "%s"', $name);
$this->friendlyError($message);
throw new FireflyException($message);
case 'accounts':
$this->correctAccountAmounts($currency, $fields);
break;
case 'auto_budgets':
case 'available_budgets':
case 'bills':
case 'budget_limits':
case 'recurrences_transactions':
$this->correctGeneric($currency, $name);
break;
case 'currency_exchange_rates':
case 'limit_repetitions':
// do nothing
break;
case 'piggy_bank_events':
$this->correctPiggyEventAmounts($currency, $fields);
break;
case 'piggy_bank_repetitions':
$this->correctPiggyRepetitionAmounts($currency, $fields);
break;
case 'piggy_banks':
$this->correctPiggyAmounts($currency, $fields);
break;
case 'transactions':
$this->correctTransactionAmounts($currency);
break;
}
}
@@ -220,11 +225,6 @@ class ForceDecimalSize extends Command
/**
* This method loops over all accounts and validates the amounts.
*
* @param TransactionCurrency $currency
* @param array $fields
*
* @return void
*/
private function correctAccountAmounts(TransactionCurrency $currency, array $fields): void
{
@@ -234,8 +234,9 @@ class ForceDecimalSize extends Command
/** @var Builder $query */
$query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id));
->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id))
;
$query->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression) {
foreach ($fields as $field) {
$q->orWhere(
@@ -251,11 +252,12 @@ class ForceDecimalSize extends Command
return;
}
/** @var Account $account */
foreach ($result as $account) {
/** @var string $field */
foreach ($fields as $field) {
$value = $account->$field;
$value = $account->{$field};
if (null === $value) {
continue;
}
@@ -270,11 +272,6 @@ class ForceDecimalSize extends Command
/**
* This method fixes all auto budgets in currency $currency.
*
* @param TransactionCurrency $currency
* @param string $table
*
* @return void
*/
private function correctGeneric(TransactionCurrency $currency, string $table): void
{
@@ -304,11 +301,12 @@ class ForceDecimalSize extends Command
return;
}
/** @var Model $item */
foreach ($result as $item) {
/** @var string $field */
foreach ($fields as $field) {
$value = $item->$field;
$value = $item->{$field};
if (null === $value) {
continue;
}
@@ -323,11 +321,6 @@ class ForceDecimalSize extends Command
/**
* This method fixes all piggy bank events in currency $currency.
*
* @param TransactionCurrency $currency
* @param array $fields
*
* @return void
*/
private function correctPiggyEventAmounts(TransactionCurrency $currency, array $fields): void
{
@@ -337,19 +330,20 @@ class ForceDecimalSize extends Command
/** @var Builder $query */
$query = PiggyBankEvent::leftJoin('piggy_banks', 'piggy_bank_events.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id))
->where(static function (Builder $q) use ($fields, $currency, $cast, $operator, $regularExpression) {
foreach ($fields as $field) {
$q->orWhere(
DB::raw(sprintf('CAST(piggy_bank_events.%s AS %s)', $field, $cast)), // @phpstan-ignore-line
$operator,
DB::raw(sprintf($regularExpression, $currency->decimal_places))
);
}
});
->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id))
->where(static function (Builder $q) use ($fields, $currency, $cast, $operator, $regularExpression) {
foreach ($fields as $field) {
$q->orWhere(
DB::raw(sprintf('CAST(piggy_bank_events.%s AS %s)', $field, $cast)), // @phpstan-ignore-line
$operator,
DB::raw(sprintf($regularExpression, $currency->decimal_places))
);
}
})
;
$result = $query->get(['piggy_bank_events.*']);
if (0 === $result->count()) {
@@ -357,11 +351,12 @@ class ForceDecimalSize extends Command
return;
}
/** @var PiggyBankEvent $item */
foreach ($result as $item) {
/** @var string $field */
foreach ($fields as $field) {
$value = $item->$field;
$value = $item->{$field};
if (null === $value) {
continue;
}
@@ -378,33 +373,30 @@ class ForceDecimalSize extends Command
/**
* This method fixes all piggy bank repetitions in currency $currency.
*
* @param TransactionCurrency $currency
* @param array $fields
*
* @return void
*/
private function correctPiggyRepetitionAmounts(TransactionCurrency $currency, array $fields)
{
$operator = $this->operator;
$cast = $this->cast;
$regularExpression = $this->regularExpression;
// select all piggy bank repetitions with this currency and issue.
/** @var Builder $query */
$query = PiggyBankRepetition::leftJoin('piggy_banks', 'piggy_bank_repetitions.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id))
->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression) {
foreach ($fields as $field) {
$q->orWhere(
DB::raw(sprintf('CAST(piggy_bank_repetitions.%s AS %s)', $field, $cast)), // @phpstan-ignore-line
$operator,
DB::raw(sprintf($regularExpression, $currency->decimal_places))
);
}
});
->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id))
->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression) {
foreach ($fields as $field) {
$q->orWhere(
DB::raw(sprintf('CAST(piggy_bank_repetitions.%s AS %s)', $field, $cast)), // @phpstan-ignore-line
$operator,
DB::raw(sprintf($regularExpression, $currency->decimal_places))
);
}
})
;
$result = $query->get(['piggy_bank_repetitions.*']);
if (0 === $result->count()) {
@@ -412,11 +404,12 @@ class ForceDecimalSize extends Command
return;
}
/** @var PiggyBankRepetition $item */
foreach ($result as $item) {
/** @var string $field */
foreach ($fields as $field) {
$value = $item->$field;
$value = $item->{$field};
if (null === $value) {
continue;
}
@@ -433,11 +426,6 @@ class ForceDecimalSize extends Command
/**
* This method fixes all piggy banks in currency $currency.
*
* @param TransactionCurrency $currency
* @param array $fields
*
* @return void
*/
private function correctPiggyAmounts(TransactionCurrency $currency, array $fields): void
{
@@ -447,18 +435,19 @@ class ForceDecimalSize extends Command
/** @var Builder $query */
$query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id))
->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression) {
foreach ($fields as $field) {
$q->orWhere(
DB::raw(sprintf('CAST(piggy_banks.%s AS %s)', $field, $cast)), // @phpstan-ignore-line
$operator,
DB::raw(sprintf($regularExpression, $currency->decimal_places))
);
}
});
->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
->where('account_meta.name', 'currency_id')
->where('account_meta.data', json_encode((string)$currency->id))
->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression) {
foreach ($fields as $field) {
$q->orWhere(
DB::raw(sprintf('CAST(piggy_banks.%s AS %s)', $field, $cast)), // @phpstan-ignore-line
$operator,
DB::raw(sprintf($regularExpression, $currency->decimal_places))
);
}
})
;
$result = $query->get(['piggy_banks.*']);
if (0 === $result->count()) {
@@ -466,11 +455,12 @@ class ForceDecimalSize extends Command
return;
}
/** @var PiggyBank $item */
foreach ($result as $item) {
/** @var string $field */
foreach ($fields as $field) {
$value = $item->$field;
$value = $item->{$field};
if (null === $value) {
continue;
}
@@ -485,10 +475,6 @@ class ForceDecimalSize extends Command
/**
* This method fixes all transactions in currency $currency.
*
* @param TransactionCurrency $currency
*
* @return void
*/
private function correctTransactionAmounts(TransactionCurrency $currency): void
{
@@ -532,6 +518,7 @@ class ForceDecimalSize extends Command
return;
}
/** @var Transaction $item */
foreach ($result as $item) {
$value = $item->foreign_amount;
@@ -548,9 +535,6 @@ class ForceDecimalSize extends Command
}
}
/**
* @return void
*/
private function updateDecimals(): void
{
$this->friendlyInfo('Going to force the size of DECIMAL columns. Please hold.');
@@ -567,15 +551,16 @@ class ForceDecimalSize extends Command
if ('pgsql' === $type) {
DB::select(sprintf('ALTER TABLE %s ALTER COLUMN %s TYPE DECIMAL(32,12);', $name, $field));
sleep(1);
return;
}
if ('mysql' === $type) {
DB::select(sprintf('ALTER TABLE %s CHANGE COLUMN %s %s DECIMAL(32, 12);', $name, $field, $field));
sleep(1);
return;
}
$this->friendlyError(sprintf('Cannot handle database type "%s".', $type));
}
}
}

View File

@@ -40,7 +40,6 @@ class ForceMigration extends Command
use ShowsFriendlyMessages;
use VerifiesAccessToken;
protected $description = 'This command will force-run all database migrations.';
protected $signature = 'firefly-iii:force-migrations
@@ -74,9 +73,6 @@ class ForceMigration extends Command
return 0;
}
/**
* @return void
*/
private function forceMigration(): void
{
DB::commit();

View File

@@ -1,6 +1,5 @@
<?php
/*
* OutputVersion.php
* Copyright (c) 2023 james@firefly-iii.org
@@ -32,7 +31,6 @@ use Illuminate\Console\Command;
*/
class OutputVersion extends Command
{
protected $description = 'Outputs the Firefly III version';
protected $signature = 'firefly-iii:output-version';
@@ -43,6 +41,7 @@ class OutputVersion extends Command
public function handle(): int
{
echo config('firefly.version');
return 0;
}
}

View File

@@ -23,26 +23,20 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\System;
use Crypt;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\Attachment;
use Illuminate\Console\Command;
use Illuminate\Contracts\Encryption\DecryptException;
use Storage;
/**
* Class ScanAttachments.
*
*/
class ScanAttachments extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Rescan all attachments and re-set the correct MD5 hash and mime.';
protected $signature = 'firefly-iii:scan-attachments';
/**
@@ -51,17 +45,20 @@ class ScanAttachments extends Command
public function handle(): int
{
$attachments = Attachment::get();
$disk = Storage::disk('upload');
$disk = \Storage::disk('upload');
/** @var Attachment $attachment */
foreach ($attachments as $attachment) {
$fileName = $attachment->fileName();
$encryptedContent = $disk->get($fileName);
if (null === $encryptedContent) {
app('log')->error(sprintf('No content for attachment #%d under filename "%s"', $attachment->id, $fileName));
continue;
}
try {
$decryptedContent = Crypt::decrypt($encryptedContent); // verified
$decryptedContent = \Crypt::decrypt($encryptedContent); // verified
} catch (DecryptException $e) {
app('log')->error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage()));
$decryptedContent = $encryptedContent;
@@ -69,6 +66,7 @@ class ScanAttachments extends Command
$tempFileName = tempnam(sys_get_temp_dir(), 'FireflyIII');
if (false === $tempFileName) {
app('log')->error(sprintf('Could not create temporary file for attachment #%d', $attachment->id));
exit(1);
}
file_put_contents($tempFileName, $decryptedContent);

View File

@@ -34,15 +34,12 @@ class SetLatestVersion extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Set latest version in DB.';
protected $signature = 'firefly-iii:set-latest-version {--james-is-cool}';
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{

View File

@@ -28,14 +28,11 @@ use Illuminate\Console\Command;
/**
* Class UpgradeFireflyInstructions.
*
*/
class UpgradeFireflyInstructions extends Command
{
use GeneratesInstallationId;
protected $description = 'Instructions in case of upgrade trouble.';
protected $signature = 'firefly:instructions {task}';
@@ -62,9 +59,11 @@ class UpgradeFireflyInstructions extends Command
private function updateInstructions(): void
{
$version = (string)config('firefly.version');
/** @var array $config */
$config = config('upgrade.text.upgrade');
$text = '';
/** @var string $compare */
foreach (array_keys($config) as $compare) {
// if string starts with:
@@ -97,8 +96,6 @@ class UpgradeFireflyInstructions extends Command
/**
* The logo takes up 8 lines of code. So 8 colors can be used.
*
* @return void
*/
private function showLogo(): void
{
@@ -146,27 +143,23 @@ class UpgradeFireflyInstructions extends Command
/**
* Show a nice box.
*
* @param string $text
*/
private function boxed(string $text): void
{
$parts = explode("\n", wordwrap($text));
foreach ($parts as $string) {
$this->line('| ' . sprintf('%-77s', $string) . '|');
$this->line('| '.sprintf('%-77s', $string).'|');
}
}
/**
* Show a nice info box.
*
* @param string $text
*/
private function boxedInfo(string $text): void
{
$parts = explode("\n", wordwrap($text));
foreach ($parts as $string) {
$this->info('| ' . sprintf('%-77s', $string) . '|');
$this->info('| '.sprintf('%-77s', $string).'|');
}
}
@@ -176,9 +169,11 @@ class UpgradeFireflyInstructions extends Command
private function installInstructions(): void
{
$version = (string)config('firefly.version');
/** @var array $config */
$config = config('upgrade.text.install');
$text = '';
/** @var string $compare */
foreach (array_keys($config) as $compare) {
// if string starts with:

View File

@@ -28,7 +28,6 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
use League\Flysystem\FilesystemException;
use Storage;
/**
* Class VerifySecurityAlerts
@@ -37,7 +36,6 @@ class VerifySecurityAlerts extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Verify security alerts';
protected $signature = 'firefly-iii:verify-security-alerts';
@@ -45,7 +43,6 @@ class VerifySecurityAlerts extends Command
/**
* Execute the console command.
*
* @return int
* @throws FilesystemException
*/
public function handle(): int
@@ -54,7 +51,7 @@ class VerifySecurityAlerts extends Command
// check for security advisories.
$version = config('firefly.version');
$disk = Storage::disk('resources');
$disk = \Storage::disk('resources');
// Next line is ignored because it's a Laravel Facade.
if (!$disk->has('alerts.json')) { // @phpstan-ignore-line
app('log')->debug('No alerts.json file present.');
@@ -100,12 +97,10 @@ class VerifySecurityAlerts extends Command
}
app('log')->debug(sprintf('No security alerts for version %s', $version));
$this->friendlyPositive(sprintf('No security alerts for version %s', $version));
return 0;
}
/**
* @return void
*/
private function removeOldAdvisory(): void
{
try {
@@ -116,11 +111,6 @@ class VerifySecurityAlerts extends Command
}
}
/**
* @param array $array
*
* @return void
*/
private function saveSecurityAdvisory(array $array): void
{
try {

View File

@@ -47,7 +47,6 @@ class ApplyRules extends Command
use ShowsFriendlyMessages;
use VerifiesAccessToken;
protected $description = 'This command will apply your rules and rule groups on a selection of your transactions.';
protected $signature
@@ -74,7 +73,6 @@ class ApplyRules extends Command
/**
* Execute the console command.
*
* @return int
* @throws FireflyException
*/
public function handle(): int
@@ -149,8 +147,6 @@ class ApplyRules 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
{
@@ -165,7 +161,6 @@ class ApplyRules extends Command
}
/**
* @return bool
* @throws FireflyException
*/
private function verifyInput(): bool
@@ -188,7 +183,6 @@ class ApplyRules extends Command
}
/**
* @return bool
* @throws FireflyException
*/
private function verifyInputAccounts(): bool
@@ -223,9 +217,6 @@ class ApplyRules extends Command
return true;
}
/**
* @return bool
*/
private function verifyInputRuleGroups(): bool
{
$ruleGroupString = $this->option('rule_groups');
@@ -248,9 +239,6 @@ class ApplyRules extends Command
return true;
}
/**
* @return bool
*/
private function verifyInputRules(): bool
{
$ruleString = $this->option('rules');
@@ -299,6 +287,7 @@ class ApplyRules extends Command
}
if (false === $inputEnd || false === $inputStart) {
Log::error('Could not parse start or end date in verifyInputDate().');
return;
}
@@ -310,22 +299,19 @@ class ApplyRules extends Command
$this->endDate = $inputEnd;
}
/**
*/
private function grabAllRules(): void
{
$this->groups = $this->ruleGroupRepository->getActiveGroups();
}
/**
* @return Collection
*/
private function getRulesToApply(): Collection
{
$rulesToApply = new Collection();
/** @var RuleGroup $group */
foreach ($this->groups as $group) {
$rules = $this->ruleGroupRepository->getActiveStoreRules($group);
/** @var Rule $rule */
foreach ($rules as $rule) {
// if in rule selection, or group in selection or all rules, it's included.
@@ -340,12 +326,6 @@ class ApplyRules extends Command
return $rulesToApply;
}
/**
* @param Rule $rule
* @param RuleGroup $group
*
* @return bool
*/
private function includeRule(Rule $rule, RuleGroup $group): bool
{
return in_array($group->id, $this->ruleGroupSelection, true)

View File

@@ -32,20 +32,16 @@ use FireflyIII\Support\Cronjobs\BillWarningCronjob;
use FireflyIII\Support\Cronjobs\ExchangeRatesCronjob;
use FireflyIII\Support\Cronjobs\RecurringCronjob;
use Illuminate\Console\Command;
use InvalidArgumentException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* Class Cron
*
*/
class Cron extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Runs all Firefly III cron-job related commands. Configure a cron job according to the official Firefly III documentation.';
protected $signature = 'firefly-iii:cron
@@ -54,23 +50,21 @@ class Cron extends Command
';
/**
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function handle(): int
{
$date = null;
try {
$date = new Carbon($this->option('date'));
} catch (InvalidArgumentException $e) {
} catch (\InvalidArgumentException $e) {
$this->friendlyError(sprintf('"%s" is not a valid date', $this->option('date')));
}
$force = (bool)$this->option('force'); // @phpstan-ignore-line
/*
* Fire exchange rates cron job.
*/
// Fire exchange rates cron job.
if (true === config('cer.download_enabled')) {
try {
$this->exchangeRatesCronJob($force, $date);
@@ -81,9 +75,7 @@ class Cron extends Command
}
}
/*
* Fire recurring transaction cron job.
*/
// Fire recurring transaction cron job.
try {
$this->recurringCronJob($force, $date);
} catch (FireflyException $e) {
@@ -92,9 +84,7 @@ class Cron extends Command
$this->friendlyError($e->getMessage());
}
/*
* Fire auto-budget cron job:
*/
// Fire auto-budget cron job:
try {
$this->autoBudgetCronJob($force, $date);
} catch (FireflyException $e) {
@@ -103,9 +93,7 @@ class Cron extends Command
$this->friendlyError($e->getMessage());
}
/*
* Fire bill warning cron job
*/
// Fire bill warning cron job
try {
$this->billWarningCronJob($force, $date);
} catch (FireflyException $e) {
@@ -119,10 +107,6 @@ class Cron extends Command
return 0;
}
/**
* @param bool $force
* @param Carbon|null $date
*/
private function exchangeRatesCronJob(bool $force, ?Carbon $date): void
{
$exchangeRates = new ExchangeRatesCronjob();
@@ -146,9 +130,6 @@ class Cron extends Command
}
/**
* @param bool $force
* @param Carbon|null $date
*
* @throws ContainerExceptionInterface
* @throws FireflyException
* @throws NotFoundExceptionInterface
@@ -175,11 +156,6 @@ class Cron extends Command
}
}
/**
* @param bool $force
* @param Carbon|null $date
*
*/
private function autoBudgetCronJob(bool $force, ?Carbon $date): void
{
$autoBudget = new AutoBudgetCronjob();
@@ -203,9 +179,6 @@ class Cron extends Command
}
/**
* @param bool $force
* @param Carbon|null $date
*
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface

View File

@@ -55,8 +55,6 @@ class AccountCurrencies extends Command
/**
* Each (asset) account must have a reference to a preferred currency. If the account does not have one, it's
* forced upon the account.
*
* @return int
*/
public function handle(): int
{
@@ -84,7 +82,6 @@ class AccountCurrencies 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
{
@@ -94,19 +91,16 @@ class AccountCurrencies extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function isExecuted(): bool
{
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
return (bool)$configVar?->data;
}
/**
*
*/
private function updateAccountCurrencies(): void
{
$users = $this->userRepos->all();
@@ -116,8 +110,6 @@ class AccountCurrencies extends Command
}
/**
* @param User $user
*
* @throws FireflyException
*/
private function updateCurrenciesForUser(User $user): void
@@ -134,10 +126,6 @@ class AccountCurrencies extends Command
}
}
/**
* @param Account $account
* @param TransactionCurrency $currency
*/
private function updateAccount(Account $account, TransactionCurrency $currency): void
{
$this->accountRepos->setUser($account->user);
@@ -150,7 +138,7 @@ class AccountCurrencies extends Command
AccountMeta::where('account_id', $account->id)->where('name', 'currency_id')->forceDelete();
AccountMeta::create(['account_id' => $account->id, 'name' => 'currency_id', 'data' => $currency->id]);
$this->friendlyInfo(sprintf('Account #%d ("%s") now has a currency setting (%s).', $account->id, $account->name, $currency->code));
$this->count++;
++$this->count;
return;
}
@@ -159,7 +147,7 @@ class AccountCurrencies extends Command
if (0 === $accountCurrency && $obCurrency > 0) {
AccountMeta::create(['account_id' => $account->id, 'name' => 'currency_id', 'data' => $obCurrency]);
$this->friendlyInfo(sprintf('Account #%d ("%s") now has a currency setting (#%d).', $account->id, $account->name, $obCurrency));
$this->count++;
++$this->count;
return;
}
@@ -175,13 +163,10 @@ class AccountCurrencies extends Command
}
);
$this->friendlyInfo(sprintf('Account #%d ("%s") now has a correct currency for opening balance.', $account->id, $account->name));
$this->count++;
++$this->count;
}
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -45,7 +45,6 @@ class AppendBudgetLimitPeriods extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -64,7 +63,6 @@ class AppendBudgetLimitPeriods extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -75,21 +73,16 @@ class AppendBudgetLimitPeriods extends Command
return (bool)$configVar->data;
}
/**
*
*/
private function theresNoLimit(): void
{
$limits = BudgetLimit::whereNull('period')->get();
/** @var BudgetLimit $limit */
foreach ($limits as $limit) {
$this->fixLimit($limit);
}
}
/**
* @param BudgetLimit $limit
*/
private function fixLimit(BudgetLimit $limit): void
{
$period = $this->getLimitPeriod($limit);
@@ -119,11 +112,6 @@ class AppendBudgetLimitPeriods extends Command
app('log')->debug($msg);
}
/**
* @param BudgetLimit $limit
*
* @return string|null
*/
private function getLimitPeriod(BudgetLimit $limit): ?string
{
// is daily
@@ -172,9 +160,6 @@ class AppendBudgetLimitPeriods extends Command
return null;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -23,7 +23,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Upgrade;
use DB;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\Budget;
use FireflyIII\Models\Category;
@@ -50,7 +49,6 @@ class BackToJournals extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -68,7 +66,6 @@ class BackToJournals extends Command
$this->friendlyWarning('Forcing the command.');
}
$this->migrateAll();
$this->friendlyInfo('Updated category and budget info for all transaction journals');
$this->markAsExecuted();
@@ -77,7 +74,6 @@ class BackToJournals extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -89,7 +85,6 @@ class BackToJournals extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -100,22 +95,16 @@ class BackToJournals extends Command
return (bool)$configVar->data;
}
/**
*
*/
private function migrateAll(): void
{
$this->migrateBudgets();
$this->migrateCategories();
// empty tables
DB::table('budget_transaction')->delete();
DB::table('category_transaction')->delete();
\DB::table('budget_transaction')->delete();
\DB::table('category_transaction')->delete();
}
/**
*
*/
private function migrateBudgets(): void
{
$journals = new Collection();
@@ -125,45 +114,42 @@ class BackToJournals extends Command
$collected = TransactionJournal::whereIn('id', $journalIds)->with(['transactions', 'budgets', 'transactions.budgets'])->get();
$journals = $journals->merge($collected);
}
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$this->migrateBudgetsForJournal($journal);
}
}
/**
* @return array
*/
private function getIdsForBudgets(): array
{
$transactions = DB::table('budget_transaction')->distinct()->pluck('transaction_id')->toArray();
$transactions = \DB::table('budget_transaction')->distinct()->pluck('transaction_id')->toArray();
$array = [];
$chunks = array_chunk($transactions, 500);
foreach ($chunks as $chunk) {
$set = DB::table('transactions')->whereIn('transactions.id', $chunk)->pluck('transaction_journal_id')->toArray();
$set = \DB::table('transactions')->whereIn('transactions.id', $chunk)->pluck('transaction_journal_id')->toArray();
$array = array_merge($array, $set);
}
return $array;
}
/**
* @param TransactionJournal $journal
*/
private function migrateBudgetsForJournal(TransactionJournal $journal): void
{
// grab category from first transaction
/** @var Transaction|null $transaction */
/** @var null|Transaction $transaction */
$transaction = $journal->transactions->first();
if (null === $transaction) {
$this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id));
return;
}
/** @var Budget|null $budget */
/** @var null|Budget $budget */
$budget = $transaction->budgets->first();
/** @var Budget|null $journalBudget */
/** @var null|Budget $journalBudget */
$journalBudget = $journal->budgets->first();
// both have a budget, but they don't match.
@@ -181,61 +167,55 @@ class BackToJournals extends Command
}
}
/**
*
*/
private function migrateCategories(): void
{
$journals = new Collection();
$allIds = $this->getIdsForCategories();
$chunks = array_chunk($allIds, 500);
foreach ($chunks as $chunk) {
$collected = TransactionJournal::whereIn('id', $chunk)->with(['transactions', 'categories', 'transactions.categories'])->get();
$journals = $journals->merge($collected);
}
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$this->migrateCategoriesForJournal($journal);
}
}
/**
* @return array
*/
private function getIdsForCategories(): array
{
$transactions = DB::table('category_transaction')->distinct()->pluck('transaction_id')->toArray();
$transactions = \DB::table('category_transaction')->distinct()->pluck('transaction_id')->toArray();
$array = [];
$chunks = array_chunk($transactions, 500);
foreach ($chunks as $chunk) {
$set = DB::table('transactions')
->whereIn('transactions.id', $chunk)
->pluck('transaction_journal_id')->toArray();
$set = \DB::table('transactions')
->whereIn('transactions.id', $chunk)
->pluck('transaction_journal_id')->toArray()
;
$array = array_merge($array, $set);
}
return $array;
}
/**
* @param TransactionJournal $journal
*/
private function migrateCategoriesForJournal(TransactionJournal $journal): void
{
// grab category from first transaction
/** @var Transaction|null $transaction */
/** @var null|Transaction $transaction */
$transaction = $journal->transactions->first();
if (null === $transaction) {
$this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id));
return;
}
/** @var Category|null $category */
/** @var null|Category $category */
$category = $transaction->categories->first();
/** @var Category|null $journalCategory */
/** @var null|Category $journalCategory */
$journalCategory = $journal->categories->first();
// both have a category, but they don't match.
@@ -250,9 +230,6 @@ class BackToJournals extends Command
}
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -48,7 +48,6 @@ class BudgetLimitCurrency extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws FireflyException
* @throws NotFoundExceptionInterface
@@ -61,16 +60,16 @@ class BudgetLimitCurrency extends Command
return 0;
}
$count = 0;
$budgetLimits = BudgetLimit::get();
/** @var BudgetLimit $budgetLimit */
foreach ($budgetLimits as $budgetLimit) {
if (null === $budgetLimit->transaction_currency_id) {
/** @var Budget|null $budget */
/** @var null|Budget $budget */
$budget = $budgetLimit->budget;
if (null !== $budget) {
/** @var User|null $user */
/** @var null|User $user */
$user = $budget->user;
if (null !== $user) {
$currency = app('amount')->getDefaultCurrencyByUserGroup($user->userGroup);
@@ -79,7 +78,7 @@ class BudgetLimitCurrency extends Command
$this->friendlyInfo(
sprintf('Budget limit #%d (part of budget "%s") now has a currency setting (%s).', $budgetLimit->id, $budget->name, $currency->name)
);
$count++;
++$count;
}
}
}
@@ -93,7 +92,6 @@ class BudgetLimitCurrency extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -107,9 +105,6 @@ class BudgetLimitCurrency extends Command
return false;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -46,7 +46,6 @@ class CCLiabilities extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws FireflyException
* @throws NotFoundExceptionInterface
@@ -59,7 +58,6 @@ class CCLiabilities extends Command
return 0;
}
$ccType = AccountType::where('type', AccountType::CREDITCARD)->first();
$debtType = AccountType::where('type', AccountType::DEBT)->first();
if (null === $ccType || null === $debtType) {
@@ -68,6 +66,7 @@ class CCLiabilities extends Command
return 0;
}
/** @var Collection $accounts */
$accounts = Account::where('account_type_id', $ccType->id)->get();
foreach ($accounts as $account) {
@@ -89,19 +88,16 @@ class CCLiabilities extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function isExecuted(): bool
{
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
return (bool)$configVar?->data;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -24,17 +24,13 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Upgrade;
use Crypt;
use DB;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Preference;
use Illuminate\Console\Command;
use Illuminate\Contracts\Encryption\DecryptException;
use JsonException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use stdClass;
/**
* Class DecryptDatabase
@@ -49,7 +45,6 @@ class DecryptDatabase extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -68,6 +63,7 @@ class DecryptDatabase extends Command
'transactions' => ['description'],
'journal_links' => ['comment'],
];
/**
* @var string $table
* @var array $fields
@@ -75,13 +71,11 @@ class DecryptDatabase extends Command
foreach ($tables as $table => $fields) {
$this->decryptTable($table, $fields);
}
return 0;
}
/**
* @param string $table
* @param array $fields
*
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -102,9 +96,6 @@ class DecryptDatabase extends Command
}
/**
* @param string $table
*
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -112,6 +103,7 @@ class DecryptDatabase extends Command
{
$configName = sprintf('is_decrypted_%s', $table);
$configVar = null;
try {
$configVar = app('fireflyconfig')->get($configName, false);
} catch (FireflyException $e) {
@@ -124,27 +116,19 @@ class DecryptDatabase extends Command
return false;
}
/**
* @param string $table
* @param string $field
*/
private function decryptField(string $table, string $field): void
{
$rows = DB::table($table)->get(['id', $field]);
/** @var stdClass $row */
$rows = \DB::table($table)->get(['id', $field]);
/** @var \stdClass $row */
foreach ($rows as $row) {
$this->decryptRow($table, $field, $row);
}
}
/**
* @param string $table
* @param string $field
* @param stdClass $row
*/
private function decryptRow(string $table, string $field, stdClass $row): void
private function decryptRow(string $table, string $field, \stdClass $row): void
{
$original = $row->$field;
$original = $row->{$field};
if (null === $original) {
return;
}
@@ -168,7 +152,7 @@ class DecryptDatabase extends Command
}
if ($value !== $original) {
DB::table($table)->where('id', $id)->update([$field => $value]);
\DB::table($table)->where('id', $id)->update([$field => $value]);
}
}
@@ -178,12 +162,13 @@ class DecryptDatabase extends Command
* @param mixed $value
*
* @return string
*
* @throws FireflyException
*/
private function tryDecrypt($value)
{
try {
$value = Crypt::decrypt($value);
$value = \Crypt::decrypt($value);
} catch (DecryptException $e) {
if ('The MAC is invalid.' === $e->getMessage()) {
throw new FireflyException($e->getMessage(), 0, $e);
@@ -193,16 +178,12 @@ class DecryptDatabase extends Command
return $value;
}
/**
* @param int $id
* @param string $value
*/
private function decryptPreferencesRow(int $id, string $value): void
{
// try to json_decrypt the value.
try {
$newValue = json_decode($value, true, 512, JSON_THROW_ON_ERROR) ?? $value;
} catch (JsonException $e) {
} catch (\JsonException $e) {
$message = sprintf('Could not JSON decode preference row #%d: %s. This does not have to be a problem.', $id, $e->getMessage());
$this->friendlyError($message);
app('log')->warning($message);
@@ -212,7 +193,7 @@ class DecryptDatabase extends Command
return;
}
/** @var Preference|null $object */
/** @var null|Preference $object */
$object = Preference::find($id);
if (null !== $object) {
$object->data = $newValue;

View File

@@ -24,7 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Upgrade;
use DB;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
@@ -35,19 +34,16 @@ class FixPostgresSequences extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Fixes issues with PostgreSQL sequences.';
protected $signature = 'firefly-iii:fix-pgsql-sequences';
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
if (DB::connection()->getName() !== 'pgsql') {
if ('pgsql' !== \DB::connection()->getName()) {
return 0;
}
$this->friendlyLine('Going to verify PostgreSQL table sequences.');
@@ -113,17 +109,18 @@ class FixPostgresSequences extends Command
foreach ($tablesToCheck as $tableToCheck) {
$this->friendlyLine(sprintf('Checking the next id sequence for table "%s".', $tableToCheck));
$highestId = DB::table($tableToCheck)->select(DB::raw('MAX(id)'))->first();
$nextId = DB::table($tableToCheck)->select(DB::raw(sprintf('nextval(\'%s_id_seq\')', $tableToCheck)))->first();
$highestId = \DB::table($tableToCheck)->select(\DB::raw('MAX(id)'))->first();
$nextId = \DB::table($tableToCheck)->select(\DB::raw(sprintf('nextval(\'%s_id_seq\')', $tableToCheck)))->first();
if (null === $nextId) {
$this->friendlyInfo(sprintf('nextval is NULL for table "%s", go to next table.', $tableToCheck));
continue;
}
if ($nextId->nextval < $highestId->max) { // @phpstan-ignore-line
DB::select(sprintf('SELECT setval(\'%s_id_seq\', %d)', $tableToCheck, $highestId->max));
$highestId = DB::table($tableToCheck)->select(DB::raw('MAX(id)'))->first();
$nextId = DB::table($tableToCheck)->select(DB::raw(sprintf('nextval(\'%s_id_seq\')', $tableToCheck)))->first();
\DB::select(sprintf('SELECT setval(\'%s_id_seq\', %d)', $tableToCheck, $highestId->max));
$highestId = \DB::table($tableToCheck)->select(\DB::raw('MAX(id)'))->first();
$nextId = \DB::table($tableToCheck)->select(\DB::raw(sprintf('nextval(\'%s_id_seq\')', $tableToCheck)))->first();
if ($nextId->nextval > $highestId->max) { // @phpstan-ignore-line
$this->friendlyInfo(sprintf('Table "%s" autoincrement corrected.', $tableToCheck));
}
@@ -136,7 +133,6 @@ class FixPostgresSequences extends Command
}
}
return 0;
}
}

View File

@@ -47,7 +47,6 @@ class MigrateAttachments extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws FireflyException
* @throws NotFoundExceptionInterface
@@ -61,7 +60,6 @@ class MigrateAttachments extends Command
return 0;
}
$attachments = Attachment::get();
$count = 0;
@@ -84,7 +82,7 @@ class MigrateAttachments extends Command
$att->save();
app('log')->debug(sprintf('Migrated attachment #%s description to note #%d.', $att->id, $note->id));
$count++;
++$count;
}
}
if (0 === $count) {
@@ -101,7 +99,6 @@ class MigrateAttachments extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -115,9 +112,6 @@ class MigrateAttachments extends Command
return false;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -46,7 +46,6 @@ class MigrateJournalNotes extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -62,6 +61,7 @@ class MigrateJournalNotes extends Command
$count = 0;
$set = TransactionJournalMeta::whereName('notes')->get();
/** @var TransactionJournalMeta $meta */
foreach ($set as $meta) {
$journal = $meta->transactionJournal;
@@ -76,7 +76,7 @@ class MigrateJournalNotes extends Command
app('log')->debug(sprintf('Migrated meta note #%d to Note #%d', $meta->id, $note->id));
$meta->delete();
$count++;
++$count;
}
if (0 === $count) {
@@ -94,7 +94,6 @@ class MigrateJournalNotes extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -108,9 +107,6 @@ class MigrateJournalNotes extends Command
return false;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -29,7 +29,6 @@ use FireflyIII\Models\Recurrence;
use FireflyIII\Models\RecurrenceMeta;
use FireflyIII\Models\RecurrenceTransactionMeta;
use Illuminate\Console\Command;
use JsonException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
@@ -49,9 +48,8 @@ class MigrateRecurrenceMeta extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws JsonException
* @throws \JsonException
* @throws NotFoundExceptionInterface
*/
public function handle(): int
@@ -76,7 +74,6 @@ class MigrateRecurrenceMeta extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -91,14 +88,14 @@ class MigrateRecurrenceMeta extends Command
}
/**
* @return int
* @throws JsonException
* @throws \JsonException
*/
private function migrateMetaData(): int
{
$count = 0;
// get all recurrence meta data:
$collection = RecurrenceMeta::with('recurrence')->get();
/** @var RecurrenceMeta $meta */
foreach ($collection as $meta) {
$count += $this->migrateEntry($meta);
@@ -108,14 +105,11 @@ class MigrateRecurrenceMeta extends Command
}
/**
* @param RecurrenceMeta $meta
*
* @return int
* @throws JsonException
* @throws \JsonException
*/
private function migrateEntry(RecurrenceMeta $meta): int
{
/** @var Recurrence|null $recurrence */
/** @var null|Recurrence $recurrence */
$recurrence = $meta->recurrence;
if (null === $recurrence) {
return 0;
@@ -143,9 +137,6 @@ class MigrateRecurrenceMeta extends Command
return 1;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -48,7 +48,6 @@ class MigrateRecurrenceType extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -63,46 +62,39 @@ class MigrateRecurrenceType extends Command
$this->migrateTypes();
$this->markAsExecuted();
return 0;
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function isExecuted(): bool
{
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
return (bool)$configVar?->data;
}
/**
*
*/
private function migrateTypes(): void
{
$set = Recurrence::get();
/** @var Recurrence $recurrence */
foreach ($set as $recurrence) {
if ($recurrence->transactionType->type !== TransactionType::INVALID) {
if (TransactionType::INVALID !== $recurrence->transactionType->type) {
$this->migrateRecurrence($recurrence);
}
}
}
/**
* @param Recurrence $recurrence
*
* @return void
*/
private function migrateRecurrence(Recurrence $recurrence): void
{
$originalType = $recurrence->transaction_type_id;
$newType = $this->getInvalidType();
$recurrence->transaction_type_id = $newType->id;
$recurrence->save();
/** @var RecurrenceTransaction $transaction */
foreach ($recurrence->recurrenceTransactions as $transaction) {
$transaction->transaction_type_id = $originalType;
@@ -111,17 +103,11 @@ class MigrateRecurrenceType extends Command
$this->friendlyInfo(sprintf('Updated recurrence #%d to new transaction type model.', $recurrence->id));
}
/**
*
*/
private function getInvalidType(): TransactionType
{
return TransactionType::whereType(TransactionType::INVALID)->firstOrCreate(['type' => TransactionType::INVALID]);
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -47,7 +47,6 @@ class MigrateTagLocations extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -65,7 +64,6 @@ class MigrateTagLocations extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -79,12 +77,10 @@ class MigrateTagLocations extends Command
return false;
}
/**
* @return void
*/
private function migrateTagLocations(): void
{
$tags = Tag::get();
/** @var Tag $tag */
foreach ($tags as $tag) {
if ($this->hasLocationDetails($tag)) {
@@ -93,19 +89,11 @@ class MigrateTagLocations extends Command
}
}
/**
* @param Tag $tag
*
* @return bool
*/
private function hasLocationDetails(Tag $tag): bool
{
return null !== $tag->latitude && null !== $tag->longitude && null !== $tag->zoomLevel;
}
/**
* @param Tag $tag
*/
private function migrateLocationDetails(Tag $tag): void
{
$location = new Location();
@@ -121,9 +109,6 @@ class MigrateTagLocations extends Command
$tag->save();
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -23,8 +23,6 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Upgrade;
use DB;
use Exception;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Factory\TransactionGroupFactory;
use FireflyIII\Models\Budget;
@@ -62,7 +60,6 @@ class MigrateToGroups extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -80,7 +77,6 @@ class MigrateToGroups extends Command
$this->friendlyWarning('Forcing the migration.');
}
$this->makeGroupsFromSplitJournals();
$this->makeGroupsFromAll();
@@ -99,8 +95,6 @@ class MigrateToGroups 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
{
@@ -112,7 +106,6 @@ class MigrateToGroups extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -127,13 +120,14 @@ class MigrateToGroups extends Command
}
/**
* @throws Exception
* @throws \Exception
*/
private function makeGroupsFromSplitJournals(): void
{
$splitJournals = $this->cliRepository->getSplitJournals();
if ($splitJournals->count() > 0) {
$this->friendlyLine(sprintf('Going to convert %d split transaction(s). Please hold..', $splitJournals->count()));
/** @var TransactionJournal $journal */
foreach ($splitJournals as $journal) {
$this->makeMultiGroup($journal);
@@ -142,9 +136,7 @@ class MigrateToGroups extends Command
}
/**
* @param TransactionJournal $journal
*
* @throws Exception
* @throws \Exception
*/
private function makeMultiGroup(TransactionJournal $journal): void
{
@@ -207,6 +199,7 @@ class MigrateToGroups extends Command
$transaction->id
)
);
continue;
}
@@ -262,7 +255,7 @@ class MigrateToGroups extends Command
// delete the old transaction journal.
$this->service->destroy($journal);
$this->count++;
++$this->count;
// report on result:
app('log')->debug(
@@ -283,11 +276,6 @@ class MigrateToGroups extends Command
);
}
/**
* @param TransactionJournal $journal
*
* @return Collection
*/
private function getDestinationTransactions(TransactionJournal $journal): Collection
{
return $journal->transactions->filter(
@@ -297,12 +285,6 @@ class MigrateToGroups extends Command
);
}
/**
* @param TransactionJournal $journal
* @param Transaction $transaction
*
* @return Transaction|null
*/
private function findOpposingTransaction(TransactionJournal $journal, Transaction $transaction): ?Transaction
{
$set = $journal->transactions->filter(
@@ -319,18 +301,12 @@ class MigrateToGroups extends Command
return $set->first();
}
/**
* @param Transaction $left
* @param Transaction $right
*
* @return int|null
*/
private function getTransactionBudget(Transaction $left, Transaction $right): ?int
{
app('log')->debug('Now in getTransactionBudget()');
// try to get a budget ID from the left transaction:
/** @var Budget|null $budget */
/** @var null|Budget $budget */
$budget = $left->budgets()->first();
if (null !== $budget) {
app('log')->debug(sprintf('Return budget #%d, from transaction #%d', $budget->id, $left->id));
@@ -339,7 +315,7 @@ class MigrateToGroups extends Command
}
// try to get a budget ID from the right transaction:
/** @var Budget|null $budget */
/** @var null|Budget $budget */
$budget = $right->budgets()->first();
if (null !== $budget) {
app('log')->debug(sprintf('Return budget #%d, from transaction #%d', $budget->id, $right->id));
@@ -352,18 +328,12 @@ class MigrateToGroups extends Command
return null;
}
/**
* @param Transaction $left
* @param Transaction $right
*
* @return int|null
*/
private function getTransactionCategory(Transaction $left, Transaction $right): ?int
{
app('log')->debug('Now in getTransactionCategory()');
// try to get a category ID from the left transaction:
/** @var Category|null $category */
/** @var null|Category $category */
$category = $left->categories()->first();
if (null !== $category) {
app('log')->debug(sprintf('Return category #%d, from transaction #%d', $category->id, $left->id));
@@ -372,7 +342,7 @@ class MigrateToGroups extends Command
}
// try to get a category ID from the left transaction:
/** @var Category|null $category */
/** @var null|Category $category */
$category = $right->categories()->first();
if (null !== $category) {
app('log')->debug(sprintf('Return category #%d, from transaction #%d', $category->id, $category->id));
@@ -395,6 +365,7 @@ class MigrateToGroups extends Command
if ($total > 0) {
app('log')->debug(sprintf('Going to convert %d transaction journals. Please hold..', $total));
$this->friendlyInfo(sprintf('Going to convert %d transaction journals. Please hold..', $total));
/** @var array $array */
foreach ($orphanedJournals as $array) {
$this->giveGroup($array);
@@ -405,12 +376,9 @@ class MigrateToGroups extends Command
}
}
/**
* @param array $array
*/
private function giveGroup(array $array): void
{
$groupId = DB::table('transaction_groups')->insertGetId(
$groupId = \DB::table('transaction_groups')->insertGetId(
[
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
@@ -418,13 +386,10 @@ class MigrateToGroups extends Command
'user_id' => $array['user_id'],
]
);
DB::table('transaction_journals')->where('id', $array['id'])->update(['transaction_group_id' => $groupId]);
$this->count++;
\DB::table('transaction_journals')->where('id', $array['id'])->update(['transaction_group_id' => $groupId]);
++$this->count;
}
/**
*
*/
private function markAsMigrated(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -58,7 +58,6 @@ class MigrateToRules extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws FireflyException
* @throws NotFoundExceptionInterface
@@ -73,8 +72,8 @@ class MigrateToRules extends Command
return 0;
}
$users = $this->userRepository->all();
/** @var User $user */
foreach ($users as $user) {
$this->migrateUser($user);
@@ -96,8 +95,6 @@ class MigrateToRules 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
{
@@ -109,7 +106,6 @@ class MigrateToRules extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -126,8 +122,6 @@ class MigrateToRules extends Command
/**
* Migrate bills to new rule structure for a specific user.
*
* @param User $user
*
* @throws FireflyException
*/
private function migrateUser(User $user): void
@@ -159,11 +153,6 @@ class MigrateToRules extends Command
}
}
/**
* @param RuleGroup $ruleGroup
* @param Bill $bill
* @param Preference $language
*/
private function migrateBill(RuleGroup $ruleGroup, Bill $bill, Preference $language): void
{
if ('MIGRATED_TO_RULES' === $bill->match) {
@@ -228,12 +217,9 @@ class MigrateToRules extends Command
'active' => $bill->active,
];
$this->billRepository->update($bill, $newBillData);
$this->count++;
++$this->count;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -56,7 +56,6 @@ class OtherCurrenciesCorrections extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -70,7 +69,6 @@ class OtherCurrenciesCorrections extends Command
return 0;
}
$this->updateOtherJournalsCurrencies();
$this->markAsExecuted();
@@ -83,8 +81,6 @@ class OtherCurrenciesCorrections 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
{
@@ -96,7 +92,6 @@ class OtherCurrenciesCorrections extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -119,7 +114,7 @@ class OtherCurrenciesCorrections extends Command
private function updateOtherJournalsCurrencies(): void
{
$set = $this->cliRepos->getAllJournals(
[TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION,]
[TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION]
);
/** @var TransactionJournal $journal */
@@ -128,9 +123,6 @@ class OtherCurrenciesCorrections extends Command
}
}
/**
* @param TransactionJournal $journal
*/
private function updateJournalCurrency(TransactionJournal $journal): void
{
$this->accountRepos->setUser($journal->user);
@@ -156,7 +148,7 @@ class OtherCurrenciesCorrections extends Command
$journal->id
)
);
$this->count++;
++$this->count;
return;
}
@@ -179,31 +171,33 @@ class OtherCurrenciesCorrections extends Command
);
// also update the journal, of course:
$journal->transaction_currency_id = $currency->id;
$this->count++;
++$this->count;
$journal->save();
}
/**
* Gets the transaction that determines the transaction that "leads" and will determine
* the currency to be used by all transactions, and the journal itself.
*
* @param TransactionJournal $journal
*
* @return Transaction|null
*/
private function getLeadTransaction(TransactionJournal $journal): ?Transaction
{
/** @var Transaction $lead */
$lead = null;
switch ($journal->transactionType->type) {
default:
break;
case TransactionType::WITHDRAWAL:
$lead = $journal->transactions()->where('amount', '<', 0)->first();
break;
case TransactionType::DEPOSIT:
$lead = $journal->transactions()->where('amount', '>', 0)->first();
break;
case TransactionType::OPENING_BALANCE:
// whichever isn't an initial balance account:
$lead = $journal->transactions()->leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id')->leftJoin(
@@ -212,7 +206,9 @@ class OtherCurrenciesCorrections extends Command
'=',
'account_types.id'
)->where('account_types.type', '!=', AccountType::INITIAL_BALANCE)->first(['transactions.*']);
break;
case TransactionType::RECONCILIATION:
// whichever isn't the reconciliation account:
$lead = $journal->transactions()->leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id')->leftJoin(
@@ -221,17 +217,13 @@ class OtherCurrenciesCorrections extends Command
'=',
'account_types.id'
)->where('account_types.type', '!=', AccountType::RECONCILIATION)->first(['transactions.*']);
break;
}
return $lead;
}
/**
* @param Account $account
*
* @return TransactionCurrency|null
*/
private function getCurrency(Account $account): ?TransactionCurrency
{
$accountId = $account->id;
@@ -252,9 +244,6 @@ class OtherCurrenciesCorrections extends Command
return $currency;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -46,7 +46,6 @@ class RenameAccountMeta extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws FireflyException
* @throws NotFoundExceptionInterface
@@ -91,7 +90,6 @@ class RenameAccountMeta extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -105,9 +103,6 @@ class RenameAccountMeta extends Command
return false;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -32,7 +32,6 @@ use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Schema;
/**
* Class TransactionIdentifier
@@ -57,7 +56,6 @@ class TransactionIdentifier extends Command
* When either of these are the same amount, FF3 can't keep them apart: +3/-3, +3/-3, +3/-3. This happens more
* often than you would think. So each set gets a number (1,2,3) to keep them apart.
*
* @return int
* @throws ContainerExceptionInterface
* @throws FireflyException
* @throws NotFoundExceptionInterface
@@ -73,11 +71,12 @@ class TransactionIdentifier extends Command
}
// if table does not exist, return false
if (!Schema::hasTable('transaction_journals')) {
if (!\Schema::hasTable('transaction_journals')) {
return 0;
}
$journals = $this->cliRepository->getSplitJournals();
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$this->updateJournalIdentifiers($journal);
@@ -99,8 +98,6 @@ class TransactionIdentifier 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
{
@@ -109,7 +106,6 @@ class TransactionIdentifier extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -126,8 +122,6 @@ class TransactionIdentifier extends Command
/**
* Grab all positive transactions from this journal that are not deleted. for each one, grab the negative opposing
* one which has 0 as an identifier and give it the same identifier.
*
* @param TransactionJournal $transactionJournal
*/
private function updateJournalIdentifiers(TransactionJournal $transactionJournal): void
{
@@ -146,18 +140,12 @@ class TransactionIdentifier extends Command
$opposing->save();
$exclude[] = $transaction->id;
$exclude[] = $opposing->id;
$this->count++;
++$this->count;
}
++$identifier;
}
}
/**
* @param Transaction $transaction
* @param array $exclude
*
* @return Transaction|null
*/
private function findOpposing(Transaction $transaction, array $exclude): ?Transaction
{
// find opposing:
@@ -166,9 +154,10 @@ class TransactionIdentifier extends Command
try {
/** @var Transaction $opposing */
$opposing = Transaction::where('transaction_journal_id', $transaction->transaction_journal_id)
->where('amount', $amount)->where('identifier', '=', 0)
->whereNotIn('id', $exclude)
->first();
->where('amount', $amount)->where('identifier', '=', 0)
->whereNotIn('id', $exclude)
->first()
;
} catch (QueryException $e) {
app('log')->error($e->getMessage());
$this->friendlyError('Firefly III could not find the "identifier" field in the "transactions" table.');
@@ -182,9 +171,6 @@ class TransactionIdentifier extends Command
return $opposing;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -60,7 +60,6 @@ class TransferCurrenciesCorrections extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -74,16 +73,17 @@ class TransferCurrenciesCorrections extends Command
return 0;
}
$this->startUpdateRoutine();
$this->markAsExecuted();
if (0 === $this->count) {
$this->friendlyPositive('All transfers have correct currency information.');
return 0;
}
$this->friendlyInfo(sprintf('Verified currency information of %d transfer(s).', $this->count));
return 0;
}
@@ -91,8 +91,6 @@ class TransferCurrenciesCorrections 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
{
@@ -105,8 +103,6 @@ class TransferCurrenciesCorrections extends Command
/**
* Reset all the class fields for the current transfer.
*
*/
private function resetInformation(): void
{
@@ -119,7 +115,6 @@ class TransferCurrenciesCorrections extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -144,27 +139,23 @@ class TransferCurrenciesCorrections extends Command
private function startUpdateRoutine(): void
{
$set = $this->cliRepos->getAllJournals([TransactionType::TRANSFER]);
/** @var TransactionJournal $journal */
foreach ($set as $journal) {
$this->updateTransferCurrency($journal);
}
}
/**
* @param TransactionJournal $transfer
*/
private function updateTransferCurrency(TransactionJournal $transfer): void
{
$this->resetInformation();
if ($this->isSplitJournal($transfer)) {
$this->friendlyWarning(sprintf('Transaction journal #%d is a split journal. Cannot continue.', $transfer->id));
return;
}
$this->getSourceInformation($transfer);
$this->getDestinationInformation($transfer);
@@ -186,7 +177,6 @@ class TransferCurrenciesCorrections extends Command
return;
}
// fix source transaction having no currency.
$this->fixSourceNoCurrency();
@@ -215,10 +205,6 @@ class TransferCurrenciesCorrections extends Command
/**
* Is this a split transaction journal?
*
* @param TransactionJournal $transfer
*
* @return bool
*/
private function isSplitJournal(TransactionJournal $transfer): bool
{
@@ -227,10 +213,6 @@ class TransferCurrenciesCorrections extends Command
/**
* Extract source transaction, source account + source account currency from the journal.
*
* @param TransactionJournal $journal
*
*/
private function getSourceInformation(TransactionJournal $journal): void
{
@@ -239,21 +221,11 @@ class TransferCurrenciesCorrections extends Command
$this->sourceCurrency = null === $this->sourceAccount ? null : $this->getCurrency($this->sourceAccount);
}
/**
* @param TransactionJournal $transfer
*
* @return Transaction|null
*/
private function getSourceTransaction(TransactionJournal $transfer): ?Transaction
{
return $transfer->transactions()->where('amount', '<', 0)->first();
}
/**
* @param Account $account
*
* @return TransactionCurrency|null
*/
private function getCurrency(Account $account): ?TransactionCurrency
{
$accountId = $account->id;
@@ -276,10 +248,6 @@ class TransferCurrenciesCorrections extends Command
/**
* Extract destination transaction, destination account + destination account currency from the journal.
*
* @param TransactionJournal $journal
*
*/
private function getDestinationInformation(TransactionJournal $journal): void
{
@@ -288,11 +256,6 @@ class TransferCurrenciesCorrections extends Command
$this->destinationCurrency = null === $this->destinationAccount ? null : $this->getCurrency($this->destinationAccount);
}
/**
* @param TransactionJournal $transfer
*
* @return Transaction|null
*/
private function getDestinationTransaction(TransactionJournal $transfer): ?Transaction
{
return $transfer->transactions()->where('amount', '>', 0)->first();
@@ -300,8 +263,6 @@ class TransferCurrenciesCorrections extends Command
/**
* Is either the source or destination transaction NULL?
*
* @return bool
*/
private function isEmptyTransactions(): bool
{
@@ -310,9 +271,6 @@ class TransferCurrenciesCorrections extends Command
|| null === $this->destinationAccount;
}
/**
* @return bool
*/
private function isNoCurrencyPresent(): bool
{
// source account must have a currency preference.
@@ -349,14 +307,15 @@ class TransferCurrenciesCorrections extends Command
if (null === $this->sourceTransaction->transaction_currency_id && null !== $this->sourceCurrency) {
$this->sourceTransaction
->transaction_currency_id
= $this->sourceCurrency->id;
= $this->sourceCurrency->id
;
$message = sprintf(
'Transaction #%d has no currency setting, now set to %s.',
$this->sourceTransaction->id,
$this->sourceCurrency->code
);
$this->friendlyInfo($message);
$this->count++;
++$this->count;
$this->sourceTransaction->save();
}
}
@@ -379,7 +338,7 @@ class TransferCurrenciesCorrections extends Command
$this->sourceTransaction->amount
);
$this->friendlyWarning($message);
$this->count++;
++$this->count;
$this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id;
$this->sourceTransaction->save();
}
@@ -394,14 +353,15 @@ class TransferCurrenciesCorrections extends Command
if (null === $this->destinationTransaction->transaction_currency_id && null !== $this->destinationCurrency) {
$this->destinationTransaction
->transaction_currency_id
= $this->destinationCurrency->id;
= $this->destinationCurrency->id
;
$message = sprintf(
'Transaction #%d has no currency setting, now set to %s.',
$this->destinationTransaction->id,
$this->destinationCurrency->code
);
$this->friendlyInfo($message);
$this->count++;
++$this->count;
$this->destinationTransaction->save();
}
}
@@ -424,7 +384,7 @@ class TransferCurrenciesCorrections extends Command
$this->destinationTransaction->amount
);
$this->friendlyWarning($message);
$this->count++;
++$this->count;
$this->destinationTransaction->transaction_currency_id = $this->destinationCurrency->id;
$this->destinationTransaction->save();
}
@@ -465,7 +425,7 @@ class TransferCurrenciesCorrections extends Command
$this->sourceTransaction->save();
$this->destinationTransaction->save();
$this->count++;
++$this->count;
$this->friendlyInfo(
sprintf('Verified foreign currency ID of transaction #%d and #%d', $this->sourceTransaction->id, $this->destinationTransaction->id)
);
@@ -481,7 +441,7 @@ class TransferCurrenciesCorrections extends Command
if (null === $this->sourceTransaction->foreign_amount && null !== $this->destinationTransaction->foreign_amount) {
$this->sourceTransaction->foreign_amount = bcmul($this->destinationTransaction->foreign_amount, '-1');
$this->sourceTransaction->save();
$this->count++;
++$this->count;
$this->friendlyInfo(
sprintf(
'Restored foreign amount of source transaction #%d to %s',
@@ -501,7 +461,7 @@ class TransferCurrenciesCorrections extends Command
if (null === $this->destinationTransaction->foreign_amount && null !== $this->sourceTransaction->foreign_amount) {
$this->destinationTransaction->foreign_amount = bcmul($this->sourceTransaction->foreign_amount, '-1');
$this->destinationTransaction->save();
$this->count++;
++$this->count;
$this->friendlyInfo(
sprintf(
'Restored foreign amount of destination transaction #%d to %s',
@@ -514,8 +474,6 @@ class TransferCurrenciesCorrections extends Command
/**
* This method makes sure that the transaction journal uses the currency given in the source transaction.
*
* @param TransactionJournal $journal
*/
private function fixTransactionJournalCurrency(TransactionJournal $journal): void
{
@@ -529,15 +487,12 @@ class TransferCurrenciesCorrections extends Command
$this->sourceCurrency->code,
$oldCurrencyCode
);
$this->count++;
++$this->count;
$this->friendlyInfo($message);
$journal->save();
}
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -1,6 +1,5 @@
<?php
/*
* UpgradeCurrencyPreferences.php
* Copyright (c) 2023 james@firefly-iii.org
@@ -48,8 +47,6 @@ class UpgradeCurrencyPreferences extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -67,9 +64,6 @@ class UpgradeCurrencyPreferences extends Command
return 0;
}
/**
* @return bool
*/
private function isExecuted(): bool
{
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
@@ -83,27 +77,25 @@ class UpgradeCurrencyPreferences extends Command
private function runUpgrade(): void
{
$groups = UserGroup::get();
/** @var UserGroup $group */
foreach ($groups as $group) {
$this->upgradeGroupPreferences($group);
}
$users = User::get();
/** @var User $user */
foreach ($users as $user) {
$this->upgradeUserPreferences($user);
}
}
/**
* @param UserGroup $group
*
* @return void
*/
private function upgradeGroupPreferences(UserGroup $group)
{
$currencies = TransactionCurrency::get();
$enabled = new Collection();
/** @var TransactionCurrency $currency */
foreach ($currencies as $currency) {
if ($currency->enabled) {
@@ -113,15 +105,11 @@ class UpgradeCurrencyPreferences extends Command
$group->currencies()->sync($enabled->pluck('id')->toArray());
}
/**
* @param User $user
*
* @return void
*/
private function upgradeUserPreferences(User $user): void
{
$currencies = TransactionCurrency::get();
$enabled = new Collection();
/** @var TransactionCurrency $currency */
foreach ($currencies as $currency) {
if ($currency->enabled) {
@@ -141,11 +129,6 @@ class UpgradeCurrencyPreferences extends Command
$user->userGroup->currencies()->updateExistingPivot($defaultCurrency->id, ['group_default' => true]);
}
/**
* @param User $user
*
* @return string
*/
private function getPreference(User $user): string
{
$preference = Preference::where('user_id', $user->id)->where('name', 'currencyPreference')->first(['id', 'user_id', 'name', 'data', 'updated_at', 'created_at']);
@@ -157,12 +140,10 @@ class UpgradeCurrencyPreferences extends Command
if (null !== $preference->data && !is_array($preference->data)) {
return (string)$preference->data;
}
return 'EUR';
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -30,8 +30,6 @@ use Illuminate\Console\Command;
/**
* Class UpgradeDatabase
*
*/
class UpgradeDatabase extends Command
{
@@ -42,8 +40,6 @@ class UpgradeDatabase extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
@@ -89,9 +85,6 @@ class UpgradeDatabase extends Command
return 0;
}
/**
* @return void
*/
private function callInitialCommands(): void
{
$this->call('migrate', ['--seed' => true, '--force' => true, '--no-interaction' => true]);

View File

@@ -50,7 +50,6 @@ class UpgradeLiabilities extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -64,11 +63,11 @@ class UpgradeLiabilities extends Command
$this->upgradeLiabilities();
$this->markAsExecuted();
return 0;
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -82,27 +81,24 @@ class UpgradeLiabilities extends Command
return false;
}
/**
*
*/
private function upgradeLiabilities(): void
{
$users = User::get();
/** @var User $user */
foreach ($users as $user) {
$this->upgradeForUser($user);
}
}
/**
* @param User $user
*/
private function upgradeForUser(User $user): void
{
$accounts = $user->accounts()
->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->whereIn('account_types.type', config('firefly.valid_liabilities'))
->get(['accounts.*']);
->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->whereIn('account_types.type', config('firefly.valid_liabilities'))
->get(['accounts.*'])
;
/** @var Account $account */
foreach ($accounts as $account) {
$this->upgradeLiability($account);
@@ -112,9 +108,6 @@ class UpgradeLiabilities extends Command
}
}
/**
* @param Account $account
*/
private function upgradeLiability(Account $account): void
{
/** @var AccountRepositoryInterface $repository */
@@ -137,10 +130,6 @@ class UpgradeLiabilities extends Command
}
}
/**
* @param Account $account
* @param TransactionJournal $openingBalance
*/
private function correctOpeningBalance(Account $account, TransactionJournal $openingBalance): void
{
$source = $this->getSourceTransaction($openingBalance);
@@ -159,29 +148,16 @@ class UpgradeLiabilities extends Command
}
}
/**
* @param TransactionJournal $journal
*
* @return Transaction|null
*/
private function getSourceTransaction(TransactionJournal $journal): ?Transaction
{
return $journal->transactions()->where('amount', '<', 0)->first();
}
/**
* @param TransactionJournal $journal
*
* @return Transaction|null
*/
private function getDestinationTransaction(TransactionJournal $journal): ?Transaction
{
return $journal->transactions()->where('amount', '>', 0)->first();
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -51,7 +51,6 @@ class UpgradeLiabilitiesEight extends Command
/**
* Execute the console command.
*
* @return int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -69,7 +68,6 @@ class UpgradeLiabilitiesEight extends Command
}
/**
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
@@ -83,27 +81,24 @@ class UpgradeLiabilitiesEight extends Command
return false;
}
/**
*
*/
private function upgradeLiabilities(): void
{
$users = User::get();
/** @var User $user */
foreach ($users as $user) {
$this->upgradeForUser($user);
}
}
/**
* @param User $user
*/
private function upgradeForUser(User $user): void
{
$accounts = $user->accounts()
->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->whereIn('account_types.type', config('firefly.valid_liabilities'))
->get(['accounts.*']);
->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->whereIn('account_types.type', config('firefly.valid_liabilities'))
->get(['accounts.*'])
;
/** @var Account $account */
foreach ($accounts as $account) {
$this->upgradeLiability($account);
@@ -113,9 +108,6 @@ class UpgradeLiabilitiesEight extends Command
}
}
/**
* @param Account $account
*/
private function upgradeLiability(Account $account): void
{
/** @var AccountRepositoryInterface $repository */
@@ -136,26 +128,23 @@ class UpgradeLiabilitiesEight extends Command
}
}
/**
* @param Account $account
*
* @return bool
*/
private function hasBadOpening(Account $account): bool
{
$openingBalanceType = TransactionType::whereType(TransactionType::OPENING_BALANCE)->first();
$liabilityType = TransactionType::whereType(TransactionType::LIABILITY_CREDIT)->first();
$openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $openingBalanceType->id)
->first(['transaction_journals.*']);
->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $openingBalanceType->id)
->first(['transaction_journals.*'])
;
if (null === $openingJournal) {
return false;
}
$liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $liabilityType->id)
->first(['transaction_journals.*']);
->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $liabilityType->id)
->first(['transaction_journals.*'])
;
if (null === $liabilityJournal) {
return false;
}
@@ -166,18 +155,14 @@ class UpgradeLiabilitiesEight extends Command
return true;
}
/**
* @param Account $account
*
* @return void
*/
private function deleteCreditTransaction(Account $account): void
{
$liabilityType = TransactionType::whereType(TransactionType::LIABILITY_CREDIT)->first();
$liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $liabilityType->id)
->first(['transaction_journals.*']);
->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $liabilityType->id)
->first(['transaction_journals.*'])
;
if (null !== $liabilityJournal) {
$group = $liabilityJournal->transactionGroup;
$service = new TransactionGroupDestroyService();
@@ -187,22 +172,21 @@ class UpgradeLiabilitiesEight extends Command
}
}
/**
* @param Account $account
*
* @return void
*/
private function reverseOpeningBalance(Account $account): void
{
$openingBalanceType = TransactionType::whereType(TransactionType::OPENING_BALANCE)->first();
/** @var TransactionJournal $openingJournal */
$openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $openingBalanceType->id)
->first(['transaction_journals.*']);
/** @var Transaction|null $source */
->where('transactions.account_id', $account->id)
->where('transaction_journals.transaction_type_id', $openingBalanceType->id)
->first(['transaction_journals.*'])
;
/** @var null|Transaction $source */
$source = $openingJournal->transactions()->where('amount', '<', 0)->first();
/** @var Transaction|null $dest */
/** @var null|Transaction $dest */
$dest = $openingJournal->transactions()->where('amount', '>', 0)->first();
if (null !== $source && null !== $dest) {
$sourceId = $source->account_id;
@@ -217,23 +201,20 @@ class UpgradeLiabilitiesEight extends Command
app('log')->warning('Did not find opening balance.');
}
/**
* @param Account $account
*
* @return int
*/
private function deleteTransactions(Account $account): int
{
$count = 0;
$journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transactions.account_id', $account->id)->get(['transaction_journals.*']);
->where('transactions.account_id', $account->id)->get(['transaction_journals.*'])
;
/** @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();
// $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.
@@ -253,16 +234,13 @@ class UpgradeLiabilitiesEight extends Command
// if ($delete) {
$service = app(TransactionGroupDestroyService::class);
$service->destroy($journal->transactionGroup);
$count++;
++$count;
// }
}
return $count;
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);

View File

@@ -31,18 +31,16 @@ use FireflyIII\User;
* Trait VerifiesAccessToken.
*
* Verifies user access token for sensitive commands.
*
*/
trait VerifiesAccessToken
{
/**
* @return User
* @throws FireflyException
*/
public function getUser(): User
{
$userId = (int)$this->option('user');
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$user = $repository->find($userId);
@@ -56,7 +54,7 @@ trait VerifiesAccessToken
/**
* Abstract method to make sure trait knows about method "option".
*
* @param string|null $key
* @param null|string $key
*
* @return mixed
*/
@@ -65,13 +63,13 @@ trait VerifiesAccessToken
/**
* Returns false when given token does not match given user token.
*
* @return bool
* @throws FireflyException
*/
protected function verifyAccessToken(): bool
{
$userId = (int)$this->option('user');
$token = (string)$this->option('token');
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$user = $repository->find($userId);

View File

@@ -29,8 +29,6 @@ use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
/**
* File to make sure commands work.
*
*/
class Kernel extends ConsoleKernel
{
@@ -39,15 +37,13 @@ class Kernel extends ConsoleKernel
*/
protected function commands(): void
{
$this->load(__DIR__ . '/Commands');
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
/**
* Define the application's command schedule.
*
* @param Schedule $schedule
*/
protected function schedule(Schedule $schedule): void
{