Add amount event.

This commit is contained in:
James Cole
2025-12-07 16:47:04 +01:00
parent f6037318f4
commit 346f2dfaea
2 changed files with 88 additions and 81 deletions

View File

@@ -78,9 +78,7 @@ class GroupUpdateService
if (1 === count($transactions) && 1 === $transactionGroup->transactionJournals()->count()) { if (1 === count($transactions) && 1 === $transactionGroup->transactionJournals()->count()) {
/** @var TransactionJournal $first */ /** @var TransactionJournal $first */
$first = $transactionGroup->transactionJournals()->first(); $first = $transactionGroup->transactionJournals()->first();
Log::debug( Log::debug(sprintf('Will now update journal #%d (only journal in group #%d)', $first->id, $transactionGroup->id));
sprintf('Will now update journal #%d (only journal in group #%d)', $first->id, $transactionGroup->id)
);
$this->updateTransactionJournal($transactionGroup, $first, reset($transactions)); $this->updateTransactionJournal($transactionGroup, $first, reset($transactions));
$transactionGroup->touch(); $transactionGroup->touch();
$transactionGroup->refresh(); $transactionGroup->refresh();

View File

@@ -24,7 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Update; namespace FireflyIII\Services\Internal\Update;
use FireflyIII\Support\Facades\Preferences;
use Carbon\Carbon; use Carbon\Carbon;
use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidDateException;
use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidFormatException;
@@ -47,6 +46,7 @@ use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface;
use FireflyIII\Services\Internal\Support\JournalServiceTrait; use FireflyIII\Services\Internal\Support\JournalServiceTrait;
use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\FireflyConfig;
use FireflyIII\Support\Facades\Preferences;
use FireflyIII\Support\NullArrayObject; use FireflyIII\Support\NullArrayObject;
use FireflyIII\Validation\AccountValidator; use FireflyIII\Validation\AccountValidator;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
@@ -60,34 +60,36 @@ class JournalUpdateService
{ {
use JournalServiceTrait; use JournalServiceTrait;
private BillRepositoryInterface $billRepository; private BillRepositoryInterface $billRepository;
private CurrencyRepositoryInterface $currencyRepository; private CurrencyRepositoryInterface $currencyRepository;
private TransactionGroupRepositoryInterface $transactionGroupRepository; private TransactionGroupRepositoryInterface $transactionGroupRepository;
private array $data; private array $data;
private ?Account $destinationAccount = null; private ?Account $destinationAccount = null;
private ?Transaction $destinationTransaction = null; private ?Transaction $destinationTransaction = null;
private array $metaDate = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', private array $metaDate
'invoice_date', ]; = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date',
private array $metaString = [ 'invoice_date',];
'sepa_cc', private array $metaString
'sepa_ct_op', = [
'sepa_ct_id', 'sepa_cc',
'sepa_db', 'sepa_ct_op',
'sepa_country', 'sepa_ct_id',
'sepa_ep', 'sepa_db',
'sepa_ci', 'sepa_country',
'sepa_batch_id', 'sepa_ep',
'recurrence_id', 'sepa_ci',
'internal_reference', 'sepa_batch_id',
'bunq_payment_id', 'recurrence_id',
'external_id', 'internal_reference',
'external_url', 'bunq_payment_id',
]; 'external_id',
private ?Account $sourceAccount = null; 'external_url',
private ?Transaction $sourceTransaction = null; ];
private ?TransactionGroup $transactionGroup = null; private ?Account $sourceAccount = null;
private ?TransactionJournal $transactionJournal = null; private ?Transaction $sourceTransaction = null;
private string $startCompareHash = ''; private ?TransactionGroup $transactionGroup = null;
private ?TransactionJournal $transactionJournal = null;
private string $startCompareHash = '';
/** /**
* JournalUpdateService constructor. * JournalUpdateService constructor.
@@ -110,7 +112,7 @@ class JournalUpdateService
public function setTransactionGroup(TransactionGroup $transactionGroup): void public function setTransactionGroup(TransactionGroup $transactionGroup): void
{ {
$this->transactionGroup = $transactionGroup; $this->transactionGroup = $transactionGroup;
$this->billRepository->setUser($transactionGroup->user); $this->billRepository->setUser($transactionGroup->user);
$this->categoryRepository->setUser($transactionGroup->user); $this->categoryRepository->setUser($transactionGroup->user);
$this->budgetRepository->setUser($transactionGroup->user); $this->budgetRepository->setUser($transactionGroup->user);
@@ -181,8 +183,8 @@ class JournalUpdateService
private function hasValidSourceAccount(): bool private function hasValidSourceAccount(): bool
{ {
$sourceId = $this->data['source_id'] ?? null; $sourceId = $this->data['source_id'] ?? null;
$sourceName = $this->data['source_name'] ?? null; $sourceName = $this->data['source_name'] ?? null;
Log::debug(sprintf('Now in hasValidSourceAccount("%s","%s").', $sourceId, $sourceName)); Log::debug(sprintf('Now in hasValidSourceAccount("%s","%s").', $sourceId, $sourceName));
if (!$this->hasFields(['source_id', 'source_name'])) { if (!$this->hasFields(['source_id', 'source_name'])) {
@@ -197,11 +199,11 @@ class JournalUpdateService
// make a new validator. // make a new validator.
/** @var AccountValidator $validator */ /** @var AccountValidator $validator */
$validator = app(AccountValidator::class); $validator = app(AccountValidator::class);
$validator->setTransactionType($expectedType); $validator->setTransactionType($expectedType);
$validator->setUser($this->transactionJournal->user); $validator->setUser($this->transactionJournal->user);
$result = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); $result = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
Log::debug( Log::debug(
sprintf('hasValidSourceAccount(%d, "%s") will return %s', $sourceId, $sourceName, var_export($result, true)) sprintf('hasValidSourceAccount(%d, "%s") will return %s', $sourceId, $sourceName, var_export($result, true))
); );
@@ -214,7 +216,7 @@ class JournalUpdateService
private function hasFields(array $fields): bool private function hasFields(array $fields): bool
{ {
return array_any($fields, fn ($field): bool => array_key_exists($field, $this->data)); return array_any($fields, fn($field): bool => array_key_exists($field, $this->data));
} }
private function getOriginalSourceAccount(): Account private function getOriginalSourceAccount(): Account
@@ -259,8 +261,8 @@ class JournalUpdateService
private function hasValidDestinationAccount(): bool private function hasValidDestinationAccount(): bool
{ {
Log::debug('Now in hasValidDestinationAccount().'); Log::debug('Now in hasValidDestinationAccount().');
$destId = $this->data['destination_id'] ?? null; $destId = $this->data['destination_id'] ?? null;
$destName = $this->data['destination_name'] ?? null; $destName = $this->data['destination_name'] ?? null;
if (!$this->hasFields(['destination_id', 'destination_name'])) { if (!$this->hasFields(['destination_id', 'destination_name'])) {
Log::debug('No destination info submitted, grab the original data.'); Log::debug('No destination info submitted, grab the original data.');
@@ -270,12 +272,12 @@ class JournalUpdateService
} }
// make new account validator. // make new account validator.
$expectedType = $this->getExpectedType(); $expectedType = $this->getExpectedType();
Log::debug(sprintf('(b) Expected type (new or unchanged) is %s', $expectedType)); Log::debug(sprintf('(b) Expected type (new or unchanged) is %s', $expectedType));
// make a new validator. // make a new validator.
/** @var AccountValidator $validator */ /** @var AccountValidator $validator */
$validator = app(AccountValidator::class); $validator = app(AccountValidator::class);
$validator->setTransactionType($expectedType); $validator->setTransactionType($expectedType);
$validator->setUser($this->transactionJournal->user); $validator->setUser($this->transactionJournal->user);
$validator->source = $this->getValidSourceAccount(); $validator->source = $this->getValidSourceAccount();
@@ -330,7 +332,7 @@ class JournalUpdateService
return $this->getOriginalSourceAccount(); return $this->getOriginalSourceAccount();
} }
$sourceInfo = [ $sourceInfo = [
'id' => (int)($this->data['source_id'] ?? null), 'id' => (int)($this->data['source_id'] ?? null),
'name' => $this->data['source_name'] ?? null, 'name' => $this->data['source_name'] ?? null,
'iban' => $this->data['source_iban'] ?? null, 'iban' => $this->data['source_iban'] ?? null,
@@ -358,8 +360,8 @@ class JournalUpdateService
*/ */
private function updateAccounts(): void private function updateAccounts(): void
{ {
$source = $this->getValidSourceAccount(); $source = $this->getValidSourceAccount();
$destination = $this->getValidDestinationAccount(); $destination = $this->getValidDestinationAccount();
// cowardly refuse to update if both accounts are the same. // cowardly refuse to update if both accounts are the same.
if ($source->id === $destination->id) { if ($source->id === $destination->id) {
@@ -372,7 +374,7 @@ class JournalUpdateService
$origSourceTransaction->account()->associate($source); $origSourceTransaction->account()->associate($source);
$origSourceTransaction->save(); $origSourceTransaction->save();
$destTransaction = $this->getDestinationTransaction(); $destTransaction = $this->getDestinationTransaction();
$destTransaction->account()->associate($destination); $destTransaction->account()->associate($destination);
$destTransaction->save(); $destTransaction->save();
@@ -394,7 +396,7 @@ class JournalUpdateService
return $this->getOriginalDestinationAccount(); return $this->getOriginalDestinationAccount();
} }
$destInfo = [ $destInfo = [
'id' => (int)($this->data['destination_id'] ?? null), 'id' => (int)($this->data['destination_id'] ?? null),
'name' => $this->data['destination_name'] ?? null, 'name' => $this->data['destination_name'] ?? null,
'iban' => $this->data['destination_iban'] ?? null, 'iban' => $this->data['destination_iban'] ?? null,
@@ -423,7 +425,7 @@ class JournalUpdateService
{ {
Log::debug('Now in updateType()'); Log::debug('Now in updateType()');
if ($this->hasFields(['type'])) { if ($this->hasFields(['type'])) {
$type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type']; $type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type'];
Log::debug( Log::debug(
sprintf( sprintf(
'Trying to change journal #%d from a %s to a %s.', 'Trying to change journal #%d from a %s to a %s.',
@@ -456,9 +458,9 @@ class JournalUpdateService
{ {
$type = $this->transactionJournal->transactionType->type; $type = $this->transactionJournal->transactionType->type;
if (( if ((
array_key_exists('bill_id', $this->data) array_key_exists('bill_id', $this->data)
|| array_key_exists('bill_name', $this->data) || array_key_exists('bill_name', $this->data)
) )
&& TransactionTypeEnum::WITHDRAWAL->value === $type && TransactionTypeEnum::WITHDRAWAL->value === $type
) { ) {
$billId = (int)($this->data['bill_id'] ?? 0); $billId = (int)($this->data['bill_id'] ?? 0);
@@ -475,7 +477,7 @@ class JournalUpdateService
private function updateField(string $fieldName): void private function updateField(string $fieldName): void
{ {
if (array_key_exists($fieldName, $this->data) && '' !== (string)$this->data[$fieldName]) { if (array_key_exists($fieldName, $this->data) && '' !== (string)$this->data[$fieldName]) {
$value = $this->data[$fieldName]; $value = $this->data[$fieldName];
if ('date' === $fieldName) { if ('date' === $fieldName) {
if (!$value instanceof Carbon) { if (!$value instanceof Carbon) {
@@ -492,15 +494,7 @@ class JournalUpdateService
Log::debug(sprintf('Create date value from string "%s".', $value)); Log::debug(sprintf('Create date value from string "%s".', $value));
$this->transactionJournal->date_tz = $value->format('e'); $this->transactionJournal->date_tz = $value->format('e');
} }
event( event(new TriggeredAuditLog($this->transactionJournal->user, $this->transactionJournal, sprintf('update_%s', $fieldName), $this->transactionJournal->{$fieldName}, $value));
new TriggeredAuditLog(
$this->transactionJournal->user,
$this->transactionJournal,
sprintf('update_%s', $fieldName),
$this->transactionJournal->{$fieldName}, // @phpstan-ignore-line
$value
)
);
$this->transactionJournal->{$fieldName} = $value; // @phpstan-ignore-line $this->transactionJournal->{$fieldName} = $value; // @phpstan-ignore-line
Log::debug(sprintf('Updated %s', $fieldName)); Log::debug(sprintf('Updated %s', $fieldName));
@@ -580,7 +574,7 @@ class JournalUpdateService
if ($this->hasFields([$field])) { if ($this->hasFields([$field])) {
$value = '' === $this->data[$field] ? null : $this->data[$field]; $value = '' === $this->data[$field] ? null : $this->data[$field];
Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value)); Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value));
$set = [ $set = [
'journal' => $this->transactionJournal, 'journal' => $this->transactionJournal,
'name' => $field, 'name' => $field,
'data' => $value, 'data' => $value,
@@ -599,7 +593,7 @@ class JournalUpdateService
if ($this->hasFields([$field])) { if ($this->hasFields([$field])) {
try { try {
$value = '' === (string)$this->data[$field] ? null : new Carbon($this->data[$field]); $value = '' === (string)$this->data[$field] ? null : new Carbon($this->data[$field]);
} catch (InvalidDateException|InvalidFormatException $e) { // @phpstan-ignore-line } catch (InvalidDateException | InvalidFormatException $e) { // @phpstan-ignore-line
Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage())); Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage()));
return; return;
@@ -628,19 +622,19 @@ class JournalUpdateService
if (!$this->hasFields(['currency_id', 'currency_code'])) { if (!$this->hasFields(['currency_id', 'currency_code'])) {
return; return;
} }
$currencyId = $this->data['currency_id'] ?? null; $currencyId = $this->data['currency_id'] ?? null;
$currencyCode = $this->data['currency_code'] ?? null; $currencyCode = $this->data['currency_code'] ?? null;
$currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode); $currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode);
// update currency everywhere. // update currency everywhere.
$this->transactionJournal->transaction_currency_id = $currency->id; $this->transactionJournal->transaction_currency_id = $currency->id;
$this->transactionJournal->save(); $this->transactionJournal->save();
$source = $this->getSourceTransaction(); $source = $this->getSourceTransaction();
$source->transaction_currency_id = $currency->id; $source->transaction_currency_id = $currency->id;
$source->save(); $source->save();
$dest = $this->getDestinationTransaction(); $dest = $this->getDestinationTransaction();
$dest->transaction_currency_id = $currency->id; $dest->transaction_currency_id = $currency->id;
$dest->save(); $dest->save();
// refresh transactions. // refresh transactions.
@@ -656,7 +650,7 @@ class JournalUpdateService
return; return;
} }
$value = $this->data['amount'] ?? ''; $value = $this->data['amount'] ?? '';
Log::debug(sprintf('Amount is now "%s"', $value)); Log::debug(sprintf('Amount is now "%s"', $value));
try { try {
@@ -670,14 +664,29 @@ class JournalUpdateService
$origSourceTransaction->amount = app('steam')->negative($amount); $origSourceTransaction->amount = app('steam')->negative($amount);
$origSourceTransaction->balance_dirty = true; $origSourceTransaction->balance_dirty = true;
$origSourceTransaction->save(); $origSourceTransaction->save();
$destTransaction = $this->getDestinationTransaction(); $destTransaction = $this->getDestinationTransaction();
$destTransaction->amount = app('steam')->positive($amount); $originalAmount = $destTransaction->amount;
$destTransaction->balance_dirty = true; $destTransaction->amount = app('steam')->positive($amount);
$destTransaction->balance_dirty = true;
$destTransaction->save(); $destTransaction->save();
// refresh transactions. // refresh transactions.
$this->sourceTransaction->refresh(); $this->sourceTransaction->refresh();
$this->destinationTransaction->refresh(); $this->destinationTransaction->refresh();
Log::debug(sprintf('Updated amount to "%s"', $amount)); Log::debug(sprintf('Updated amount to "%s"', $amount));
event(new TriggeredAuditLog($this->transactionGroup->user, $this->transactionGroup, 'update_amount',
[
'currency_symbol' => $destTransaction->transactionCurrency->symbol,
'decimal_places' => $destTransaction->transactionCurrency->decimal_places,
'amount' => $originalAmount,
],
[
'currency_symbol' => $destTransaction->transactionCurrency->symbol,
'decimal_places' => $destTransaction->transactionCurrency->decimal_places,
'amount' => $value,
]
));
} }
private function updateForeignAmount(): void private function updateForeignAmount(): void
@@ -697,7 +706,7 @@ class JournalUpdateService
$newForeignId = $this->data['foreign_currency_id'] ?? null; $newForeignId = $this->data['foreign_currency_id'] ?? null;
$newForeignCode = $this->data['foreign_currency_code'] ?? null; $newForeignCode = $this->data['foreign_currency_code'] ?? null;
$foreignCurrency = $this->currencyRepository->findCurrencyNull($newForeignId, $newForeignCode) $foreignCurrency = $this->currencyRepository->findCurrencyNull($newForeignId, $newForeignCode)
?? $foreignCurrency; ?? $foreignCurrency;
// not the same as normal currency // not the same as normal currency
if (null !== $foreignCurrency && $foreignCurrency->id === $this->transactionJournal->transaction_currency_id) { if (null !== $foreignCurrency && $foreignCurrency->id === $this->transactionJournal->transaction_currency_id) {
@@ -715,9 +724,9 @@ class JournalUpdateService
// if the transaction is a TRANSFER, and the foreign amount and currency are set (like they seem to be) // if the transaction is a TRANSFER, and the foreign amount and currency are set (like they seem to be)
// the correct fields to update in the destination transaction are NOT the foreign amount and currency // the correct fields to update in the destination transaction are NOT the foreign amount and currency
// but rather the normal amount and currency. This is new behavior. // but rather the normal amount and currency. This is new behavior.
$isTransfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; $isTransfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type;
// also check if it is not between an asset account and a liability, because then the same rule applies. // also check if it is not between an asset account and a liability, because then the same rule applies.
$isBetween = $this->isBetweenAssetAndLiability(); $isBetween = $this->isBetweenAssetAndLiability();
if ($isTransfer || $isBetween) { if ($isTransfer || $isBetween) {
Log::debug('Switch amounts, store in amount and not foreign_amount'); Log::debug('Switch amounts, store in amount and not foreign_amount');
@@ -753,8 +762,8 @@ class JournalUpdateService
$source->foreign_amount = null; $source->foreign_amount = null;
$source->save(); $source->save();
$dest->foreign_currency_id = null; $dest->foreign_currency_id = null;
$dest->foreign_amount = null; $dest->foreign_amount = null;
$dest->save(); $dest->save();
Log::debug(sprintf('Foreign amount is "%s" so remove foreign amount info.', $amount)); Log::debug(sprintf('Foreign amount is "%s" so remove foreign amount info.', $amount));
} }
@@ -768,7 +777,7 @@ class JournalUpdateService
private function isBetweenAssetAndLiability(): bool private function isBetweenAssetAndLiability(): bool
{ {
/** @var null|Transaction $sourceTransaction */ /** @var null|Transaction $sourceTransaction */
$sourceTransaction = $this->transactionJournal->transactions()->where('amount', '<', 0)->first(); $sourceTransaction = $this->transactionJournal->transactions()->where('amount', '<', 0)->first();
/** @var null|Transaction $destinationTransaction */ /** @var null|Transaction $destinationTransaction */
$destinationTransaction = $this->transactionJournal->transactions()->where('amount', '>', 0)->first(); $destinationTransaction = $this->transactionJournal->transactions()->where('amount', '>', 0)->first();
@@ -783,15 +792,15 @@ class JournalUpdateService
return false; return false;
} }
$source = $sourceTransaction->account; $source = $sourceTransaction->account;
$destination = $destinationTransaction->account; $destination = $destinationTransaction->account;
if (null === $source || null === $destination) { if (null === $source || null === $destination) {
Log::warning('Either is false, stop.'); Log::warning('Either is false, stop.');
return false; return false;
} }
$sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
// source is liability, destination is asset // source is liability, destination is asset
if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) { if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) {