Files
firefly-iii/app/Console/Commands/Correction/FixUnevenAmount.php

293 lines
11 KiB
PHP
Raw Normal View History

2019-03-23 08:10:59 +01:00
<?php
/**
* FixUnevenAmount.php
2020-01-23 20:35:02 +01:00
* Copyright (c) 2020 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
2019-08-17 12:09:03 +02:00
declare(strict_types=1);
2019-03-23 08:10:59 +01:00
namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
2019-03-23 08:10:59 +01:00
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
2024-07-30 18:04:39 +02:00
use FireflyIII\Models\TransactionType;
use FireflyIII\Support\Models\AccountBalanceCalculator;
2019-03-23 08:10:59 +01:00
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
2019-03-23 08:10:59 +01:00
/**
* Class FixUnevenAmount
*/
class FixUnevenAmount extends Command
{
use ShowsFriendlyMessages;
2024-07-31 08:31:20 +02:00
protected $description = 'Fix journals with uneven amounts.';
protected $signature = 'firefly-iii:fix-uneven-amount';
2024-07-30 18:04:39 +02:00
private int $count;
2019-03-23 08:10:59 +01:00
/**
* Execute the console command.
*/
public function handle(): int
{
2024-07-30 18:04:39 +02:00
$this->count = 0;
$this->convertOldStyleTransfers();
$this->fixUnevenAmounts();
$this->matchCurrencies();
2024-07-31 13:09:55 +02:00
AccountBalanceCalculator::forceRecalculateAll();
return 0;
}
private function fixJournal(int $param): void
{
// one of the transactions is bad.
2024-07-31 08:31:20 +02:00
$journal = TransactionJournal::find($param);
if (null === $journal) {
return;
}
/** @var null|Transaction $source */
2024-07-31 08:31:20 +02:00
$source = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $source) {
$this->friendlyError(
sprintf(
'Journal #%d ("%s") has no source transaction. It will be deleted to maintain database consistency.',
$journal->id ?? 0,
$journal->description ?? ''
)
);
Transaction::where('transaction_journal_id', $journal->id ?? 0)->forceDelete();
TransactionJournal::where('id', $journal->id ?? 0)->forceDelete();
2024-07-30 18:04:39 +02:00
++$this->count;
2024-07-31 08:31:20 +02:00
return;
}
2024-07-31 08:31:20 +02:00
$amount = bcmul('-1', $source->amount);
// fix amount of destination:
/** @var null|Transaction $destination */
2024-07-31 08:31:20 +02:00
$destination = $journal->transactions()->where('amount', '>', 0)->first();
if (null === $destination) {
$this->friendlyError(
sprintf(
'Journal #%d ("%s") has no destination transaction. It will be deleted to maintain database consistency.',
$journal->id ?? 0,
$journal->description ?? ''
)
);
Transaction::where('transaction_journal_id', $journal->id ?? 0)->forceDelete();
TransactionJournal::where('id', $journal->id ?? 0)->forceDelete();
2024-07-30 18:04:39 +02:00
++$this->count;
2024-07-31 08:31:20 +02:00
2024-07-30 18:04:39 +02:00
return;
}
2024-07-30 18:04:39 +02:00
// may still be able to salvage this journal if it is a transfer with foreign currency info
if ($this->isForeignCurrencyTransfer($journal)) {
2024-07-30 18:04:39 +02:00
Log::debug(sprintf('Can skip foreign currency transfer #%d.', $journal->id));
2024-07-31 08:31:20 +02:00
return;
}
2024-07-31 08:31:20 +02:00
$message = sprintf('Sum of journal #%d is not zero, journal is broken and now fixed.', $journal->id);
2024-07-30 18:04:39 +02:00
$this->friendlyWarning($message);
app('log')->warning($message);
$destination->amount = $amount;
$destination->save();
2024-07-31 08:31:20 +02:00
$message = sprintf('Corrected amount in transaction journal #%d', $param);
$this->friendlyInfo($message);
2024-07-30 18:04:39 +02:00
++$this->count;
}
private function fixUnevenAmounts(): void
2019-03-23 08:10:59 +01:00
{
2023-12-20 19:35:52 +01:00
$journals = \DB::table('transactions')
2024-07-31 08:31:20 +02:00
->groupBy('transaction_journal_id')
->whereNull('deleted_at')
->get(['transaction_journal_id', \DB::raw('SUM(amount) AS the_sum')])
;
2023-12-20 19:35:52 +01:00
/** @var \stdClass $entry */
2019-03-23 08:10:59 +01:00
foreach ($journals as $entry) {
$sum = (string) $entry->the_sum;
2023-12-20 19:35:52 +01:00
if (!is_numeric($sum)
|| '' === $sum // @phpstan-ignore-line
|| str_contains($sum, 'e')
|| str_contains($sum, ',')) {
2023-06-21 06:07:35 +02:00
$message = sprintf(
'Journal #%d has an invalid sum ("%s"). No sure what to do.',
$entry->transaction_journal_id,
$entry->the_sum
);
$this->friendlyWarning($message);
2023-06-12 06:24:30 +02:00
app('log')->warning($message);
2024-07-30 18:04:39 +02:00
++$this->count;
2023-12-20 19:35:52 +01:00
2023-06-12 06:24:30 +02:00
continue;
}
$res = -1;
2023-12-20 19:35:52 +01:00
try {
$res = bccomp($sum, '0');
2023-12-20 19:35:52 +01:00
} catch (\ValueError $e) {
$this->friendlyError(sprintf('Could not bccomp("%s", "0").', $sum));
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
}
if (0 !== $res) {
2023-11-05 19:41:37 +01:00
$this->fixJournal($entry->transaction_journal_id);
2019-03-23 08:10:59 +01:00
}
}
2024-07-30 18:04:39 +02:00
if (0 === $this->count) {
$this->friendlyPositive('Database amount integrity is OK');
2019-03-23 08:10:59 +01:00
}
}
private function matchCurrencies(): void
2019-03-23 08:10:59 +01:00
{
$journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', 'transactions.transaction_journal_id')
2024-07-31 08:31:20 +02:00
->where('transactions.transaction_currency_id', '!=', \DB::raw('transaction_journals.transaction_currency_id'))
->get(['transaction_journals.*'])
;
$count = 0;
2024-07-30 18:04:39 +02:00
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
if (!$this->isForeignCurrencyTransfer($journal)) {
2024-07-30 18:04:39 +02:00
Transaction::where('transaction_journal_id', $journal->id)->update(['transaction_currency_id' => $journal->transaction_currency_id]);
2024-07-31 08:31:20 +02:00
++$count;
2024-07-30 18:04:39 +02:00
continue;
}
Log::debug(sprintf('Can skip foreign currency transfer #%d.', $journal->id));
}
if (0 === $count) {
$this->friendlyPositive('Journal currency integrity is OK');
return;
2019-03-23 08:10:59 +01:00
}
$this->friendlyPositive(sprintf('Fixed %d journal(s) with mismatched currencies.', $journals->count()));
2019-03-23 08:10:59 +01:00
}
2024-07-30 18:04:39 +02:00
private function isForeignCurrencyTransfer(TransactionJournal $journal): bool
{
if (TransactionType::TRANSFER !== $journal->transactionType->type) {
2024-07-30 18:04:39 +02:00
return false;
}
2024-07-31 08:31:20 +02:00
2024-07-30 18:04:39 +02:00
/** @var Transaction $destination */
$destination = $journal->transactions()->where('amount', '>', 0)->first();
2024-07-31 08:31:20 +02:00
2024-07-30 18:04:39 +02:00
/** @var Transaction $source */
2024-07-31 08:31:20 +02:00
$source = $journal->transactions()->where('amount', '<', 0)->first();
2024-07-30 18:04:39 +02:00
// safety catch on NULL should not be necessary, we just had that catch.
// source amount = dest foreign amount
// source currency = dest foreign currency
// dest amount = source foreign currency
// dest currency = source foreign currency
2024-07-31 08:31:20 +02:00
// Log::debug(sprintf('[a] %s', bccomp(app('steam')->positive($source->amount), app('steam')->positive($destination->foreign_amount))));
// Log::debug(sprintf('[b] %s', bccomp(app('steam')->positive($destination->amount), app('steam')->positive($source->foreign_amount))));
// Log::debug(sprintf('[c] %s', var_export($source->transaction_currency_id === $destination->foreign_currency_id,true)));
// Log::debug(sprintf('[d] %s', var_export((int) $destination->transaction_currency_id ===(int) $source->foreign_currency_id, true)));
2024-07-30 18:04:39 +02:00
2024-07-31 08:31:20 +02:00
if (0 === bccomp(app('steam')->positive($source->amount), app('steam')->positive($destination->foreign_amount))
&& $source->transaction_currency_id === $destination->foreign_currency_id
&& 0 === bccomp(app('steam')->positive($destination->amount), app('steam')->positive($source->foreign_amount))
&& (int) $destination->transaction_currency_id === (int) $source->foreign_currency_id
2024-07-30 18:04:39 +02:00
) {
return true;
}
2024-07-31 08:31:20 +02:00
return false;
2024-07-30 18:04:39 +02:00
}
private function convertOldStyleTransfers(): void
{
Log::debug('convertOldStyleTransfers()');
// select transactions with a foreign amount and a foreign currency. and it's a transfer. and they are different.
$transactions = Transaction::distinct()
2024-07-31 08:31:20 +02:00
->whereNotNull('foreign_currency_id')
->whereNotNull('foreign_amount')->get(['transactions.transaction_journal_id'])
;
$count = 0;
Log::debug(sprintf('Found %d potential journal(s)', $transactions->count()));
2024-07-31 08:31:20 +02:00
/** @var Transaction $transaction */
foreach ($transactions as $transaction) {
2024-07-31 08:31:20 +02:00
/** @var null|TransactionJournal $journal */
$journal = TransactionJournal::find($transaction->transaction_journal_id);
if (null === $journal) {
Log::debug('Found no journal, continue.');
2024-07-31 08:31:20 +02:00
continue;
}
// needs to be a transfer.
if (TransactionType::TRANSFER !== $journal->transactionType->type) {
Log::debug('Must be a transfer, continue.');
2024-07-31 08:31:20 +02:00
continue;
}
2024-07-31 08:31:20 +02:00
/** @var null|Transaction $destination */
$destination = $journal->transactions()->where('amount', '>', 0)->first();
2024-07-31 08:31:20 +02:00
/** @var null|Transaction $source */
$source = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $destination || null === $source) {
Log::debug('Source or destination transaction is NULL, continue.');
2024-07-31 08:31:20 +02:00
// will be picked up later.
continue;
}
if ($source->transaction_currency_id === $destination->transaction_currency_id) {
Log::debug('Ready to swap data between transactions.');
$destination->foreign_currency_id = $source->transaction_currency_id;
$destination->foreign_amount = app('steam')->positive($source->amount);
$destination->transaction_currency_id = $source->foreign_currency_id;
$destination->amount = app('steam')->positive($source->foreign_amount);
$destination->balance_dirty = true;
$source->balance_dirty = true;
$destination->save();
$source->save();
$this->friendlyWarning(sprintf('Corrected foreign amounts of transfer #%d.', $journal->id));
2024-07-31 08:31:20 +02:00
++$count;
}
}
if (0 === $count) {
$this->friendlyPositive('No "old style" foreign currency transfers.');
return;
}
}
2019-03-23 08:10:59 +01:00
}