Only trigger running balance when amount actually changes.

This commit is contained in:
James Cole
2025-05-31 07:22:42 +02:00
parent 3344d2e5f3
commit d465b51da8
14 changed files with 188 additions and 155 deletions

View File

@@ -34,6 +34,7 @@ use FireflyIII\Support\JsonApi\Enrichments\TransactionGroupEnrichment;
use FireflyIII\Transformers\TransactionGroupTransformer; use FireflyIII\Transformers\TransactionGroupTransformer;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use League\Fractal\Resource\Item; use League\Fractal\Resource\Item;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -53,7 +54,7 @@ class UpdateController extends Controller
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
/** @var User $admin */ /** @var User $admin */
$admin = auth()->user(); $admin = auth()->user();
$this->groupRepository = app(TransactionGroupRepositoryInterface::class); $this->groupRepository = app(TransactionGroupRepositoryInterface::class);
$this->groupRepository->setUser($admin); $this->groupRepository->setUser($admin);
@@ -72,43 +73,47 @@ class UpdateController extends Controller
public function update(UpdateRequest $request, TransactionGroup $transactionGroup): JsonResponse public function update(UpdateRequest $request, TransactionGroup $transactionGroup): JsonResponse
{ {
app('log')->debug('Now in update routine for transaction group'); app('log')->debug('Now in update routine for transaction group');
$data = $request->getAll(); $data = $request->getAll();
$oldAmount = $this->groupRepository->getTotalAmount($transactionGroup);
$transactionGroup = $this->groupRepository->update($transactionGroup, $data); $transactionGroup = $this->groupRepository->update($transactionGroup, $data);
$manager = $this->getManager(); $newAmount = $this->groupRepository->getTotalAmount($transactionGroup);
$manager = $this->getManager();
Log::debug(sprintf('Old amount: %s, new amount: %s', $oldAmount, $newAmount));
app('preferences')->mark(); app('preferences')->mark();
$applyRules = $data['apply_rules'] ?? true; $applyRules = $data['apply_rules'] ?? true;
$fireWebhooks = $data['fire_webhooks'] ?? true; $fireWebhooks = $data['fire_webhooks'] ?? true;
event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks)); $amountChanged = 0 !== bccomp($oldAmount, $newAmount);
event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $amountChanged));
/** @var User $admin */ /** @var User $admin */
$admin = auth()->user(); $admin = auth()->user();
// use new group collector: // use new group collector:
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector $collector
->setUser($admin) ->setUser($admin)
// filter on transaction group. // filter on transaction group.
->setTransactionGroup($transactionGroup) ->setTransactionGroup($transactionGroup)
// all info needed for the API: // all info needed for the API:
->withAPIInformation() ->withAPIInformation();
;
$selectedGroup = $collector->getGroups()->first(); $selectedGroup = $collector->getGroups()->first();
if (null === $selectedGroup) { if (null === $selectedGroup) {
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }
// enrich // enrich
$enrichment = new TransactionGroupEnrichment(); $enrichment = new TransactionGroupEnrichment();
$enrichment->setUser($admin); $enrichment->setUser($admin);
$selectedGroup = $enrichment->enrichSingle($selectedGroup); $selectedGroup = $enrichment->enrichSingle($selectedGroup);
/** @var TransactionGroupTransformer $transformer */ /** @var TransactionGroupTransformer $transformer */
$transformer = app(TransactionGroupTransformer::class); $transformer = app(TransactionGroupTransformer::class);
$transformer->setParameters($this->parameters); $transformer->setParameters($this->parameters);
$resource = new Item($selectedGroup, $transformer, 'transactions'); $resource = new Item($selectedGroup, $transformer, 'transactions');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
} }

View File

@@ -69,8 +69,9 @@ class UpdateController extends Controller
$transactionGroup = $this->groupRepository->update($transactionGroup, $data); $transactionGroup = $this->groupRepository->update($transactionGroup, $data);
$applyRules = $data['apply_rules'] ?? true; $applyRules = $data['apply_rules'] ?? true;
$fireWebhooks = $data['fire_webhooks'] ?? true; $fireWebhooks = $data['fire_webhooks'] ?? true;
$amountChanged = true;
event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks)); event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $amountChanged));
app('preferences')->mark(); app('preferences')->mark();
/** @var User $admin */ /** @var User $admin */

View File

@@ -58,7 +58,7 @@ class CorrectsGroupAccounts extends Command
$handler = new UpdatedGroupEventHandler(); $handler = new UpdatedGroupEventHandler();
foreach ($groups as $groupId) { foreach ($groups as $groupId) {
$group = TransactionGroup::find($groupId); $group = TransactionGroup::find($groupId);
$event = new UpdatedTransactionGroup($group, true, true); $event = new UpdatedTransactionGroup($group, true, true, false);
$handler->unifyAccounts($event); $handler->unifyAccounts($event);
} }

View File

@@ -37,5 +37,5 @@ class UpdatedTransactionGroup extends Event
/** /**
* Create a new event instance. * Create a new event instance.
*/ */
public function __construct(public TransactionGroup $transactionGroup, public bool $applyRules, public bool $fireWebhooks) {} public function __construct(public TransactionGroup $transactionGroup, public bool $applyRules, public bool $fireWebhooks, public bool $amountChanged) {}
} }

View File

@@ -49,7 +49,9 @@ class UpdatedGroupEventHandler
$this->processRules($event); $this->processRules($event);
$this->recalculateCredit($event); $this->recalculateCredit($event);
$this->triggerWebhooks($event); $this->triggerWebhooks($event);
$this->updateRunningBalance($event); if ($event->amountChanged) {
$this->updateRunningBalance($event);
}
} }
@@ -58,20 +60,19 @@ class UpdatedGroupEventHandler
*/ */
public function unifyAccounts(UpdatedTransactionGroup $updatedGroupEvent): void public function unifyAccounts(UpdatedTransactionGroup $updatedGroupEvent): void
{ {
$group = $updatedGroupEvent->transactionGroup; $group = $updatedGroupEvent->transactionGroup;
if (1 === $group->transactionJournals->count()) { if (1 === $group->transactionJournals->count()) {
return; return;
} }
// first journal: // first journal:
/** @var null|TransactionJournal $first */ /** @var null|TransactionJournal $first */
$first = $group->transactionJournals() $first = $group->transactionJournals()
->orderBy('transaction_journals.date', 'DESC') ->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.id', 'DESC')
->orderBy('transaction_journals.description', 'DESC') ->orderBy('transaction_journals.description', 'DESC')
->first() ->first();
;
if (null === $first) { if (null === $first) {
Log::warning(sprintf('Group #%d has no transaction journals.', $group->id)); Log::warning(sprintf('Group #%d has no transaction journals.', $group->id));
@@ -79,26 +80,24 @@ class UpdatedGroupEventHandler
return; return;
} }
$all = $group->transactionJournals()->get()->pluck('id')->toArray(); $all = $group->transactionJournals()->get()->pluck('id')->toArray();
/** @var Account $sourceAccount */ /** @var Account $sourceAccount */
$sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account; $sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account;
/** @var Account $destAccount */ /** @var Account $destAccount */
$destAccount = $first->transactions()->where('amount', '>', '0')->first()->account; $destAccount = $first->transactions()->where('amount', '>', '0')->first()->account;
$type = $first->transactionType->type; $type = $first->transactionType->type;
if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::WITHDRAWAL->value === $type) { if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::WITHDRAWAL->value === $type) {
// set all source transactions to source account: // set all source transactions to source account:
Transaction::whereIn('transaction_journal_id', $all) Transaction::whereIn('transaction_journal_id', $all)
->where('amount', '<', 0)->update(['account_id' => $sourceAccount->id]) ->where('amount', '<', 0)->update(['account_id' => $sourceAccount->id]);
;
} }
if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::DEPOSIT->value === $type) { if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::DEPOSIT->value === $type) {
// set all destination transactions to destination account: // set all destination transactions to destination account:
Transaction::whereIn('transaction_journal_id', $all) Transaction::whereIn('transaction_journal_id', $all)
->where('amount', '>', 0)->update(['account_id' => $destAccount->id]) ->where('amount', '>', 0)->update(['account_id' => $destAccount->id]);
;
} }
} }
@@ -113,24 +112,24 @@ class UpdatedGroupEventHandler
return; return;
} }
$journals = $updatedGroupEvent->transactionGroup->transactionJournals; $journals = $updatedGroupEvent->transactionGroup->transactionJournals;
$array = []; $array = [];
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
$array[] = $journal->id; $array[] = $journal->id;
} }
$journalIds = implode(',', $array); $journalIds = implode(',', $array);
Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds)); Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds));
// collect rules: // collect rules:
$ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
$ruleGroupRepository->setUser($updatedGroupEvent->transactionGroup->user); $ruleGroupRepository->setUser($updatedGroupEvent->transactionGroup->user);
$groups = $ruleGroupRepository->getRuleGroupsWithRules('update-journal'); $groups = $ruleGroupRepository->getRuleGroupsWithRules('update-journal');
// file rule engine. // file rule engine.
$newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine = app(RuleEngineInterface::class);
$newRuleEngine->setUser($updatedGroupEvent->transactionGroup->user); $newRuleEngine->setUser($updatedGroupEvent->transactionGroup->user);
$newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]);
$newRuleEngine->setRuleGroups($groups); $newRuleEngine->setRuleGroups($groups);
@@ -139,7 +138,7 @@ class UpdatedGroupEventHandler
private function recalculateCredit(UpdatedTransactionGroup $event): void private function recalculateCredit(UpdatedTransactionGroup $event): void
{ {
$group = $event->transactionGroup; $group = $event->transactionGroup;
/** @var CreditRecalculateService $object */ /** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class); $object = app(CreditRecalculateService::class);
@@ -150,13 +149,13 @@ class UpdatedGroupEventHandler
private function triggerWebhooks(UpdatedTransactionGroup $updatedGroupEvent): void private function triggerWebhooks(UpdatedTransactionGroup $updatedGroupEvent): void
{ {
Log::debug(__METHOD__); Log::debug(__METHOD__);
$group = $updatedGroupEvent->transactionGroup; $group = $updatedGroupEvent->transactionGroup;
if (false === $updatedGroupEvent->fireWebhooks) { if (false === $updatedGroupEvent->fireWebhooks) {
Log::info(sprintf('Will not fire webhooks for transaction group #%d', $group->id)); Log::info(sprintf('Will not fire webhooks for transaction group #%d', $group->id));
return; return;
} }
$user = $group->user; $user = $group->user;
/** @var MessageGeneratorInterface $engine */ /** @var MessageGeneratorInterface $engine */
$engine = app(MessageGeneratorInterface::class); $engine = app(MessageGeneratorInterface::class);

View File

@@ -118,7 +118,7 @@ class BulkController extends Controller
// run rules on changed journals: // run rules on changed journals:
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($collection as $journal) { foreach ($collection as $journal) {
event(new UpdatedTransactionGroup($journal->transactionGroup, true, true)); event(new UpdatedTransactionGroup($journal->transactionGroup, true, true, false));
} }
app('preferences')->mark(); app('preferences')->mark();

View File

@@ -292,7 +292,7 @@ class ConvertController extends Controller
$group->refresh(); $group->refresh();
session()->flash('success', (string) trans('firefly.converted_to_'.$destinationType->type)); session()->flash('success', (string) trans('firefly.converted_to_'.$destinationType->type));
event(new UpdatedTransactionGroup($group, true, true)); event(new UpdatedTransactionGroup($group, true, true, false));
return redirect(route('transactions.show', [$group->id])); return redirect(route('transactions.show', [$group->id]));
} }

View File

@@ -217,7 +217,8 @@ class MassController extends Controller
$service->setData($data); $service->setData($data);
$service->update(); $service->update();
// trigger rules // trigger rules
event(new UpdatedTransactionGroup($journal->transactionGroup, true, true)); $amountChanged = $service->isAmountChanged();
event(new UpdatedTransactionGroup($journal->transactionGroup, true, true, $amountChanged));
} }
private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon

View File

@@ -432,4 +432,19 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
return $service->update($transactionGroup, $data); return $service->update($transactionGroup, $data);
} }
public function getTotalAmount(TransactionGroup $group): string
{
$sum = '0';
/** @var TransactionJournal $journal */
foreach($group->transactionJournals as $journal) {
/** @var Transaction $transaction */
foreach($journal->transactions as $transaction) {
if(-1 === bccomp('0', (string) $transaction->amount)) {
$sum = bcadd($sum, $transaction->amount);
}
}
}
return $sum;
}
} }

View File

@@ -49,6 +49,8 @@ interface TransactionGroupRepositoryInterface
{ {
public function countAttachments(int $journalId): int; public function countAttachments(int $journalId): int;
public function getTotalAmount(TransactionGroup $group): string;
public function destroy(TransactionGroup $group): void; public function destroy(TransactionGroup $group): void;
/** /**

View File

@@ -58,36 +58,37 @@ class JournalUpdateService
{ {
use JournalServiceTrait; use JournalServiceTrait;
private BillRepositoryInterface $billRepository; private BillRepositoryInterface $billRepository;
private CurrencyRepositoryInterface $currencyRepository; private CurrencyRepositoryInterface $currencyRepository;
private array $data; private array $data;
private ?Account $destinationAccount; private ?Account $destinationAccount;
private ?Transaction $destinationTransaction; private ?Transaction $destinationTransaction;
private array $metaDate; private array $metaDate;
private array $metaString; private array $metaString;
private ?Account $sourceAccount; private ?Account $sourceAccount;
private ?Transaction $sourceTransaction; private ?Transaction $sourceTransaction;
private ?TransactionGroup $transactionGroup; private ?TransactionGroup $transactionGroup;
private ?TransactionJournal $transactionJournal; private ?TransactionJournal $transactionJournal;
private bool $amountChanged = false;
/** /**
* JournalUpdateService constructor. * JournalUpdateService constructor.
*/ */
public function __construct() public function __construct()
{ {
$this->destinationAccount = null; $this->destinationAccount = null;
$this->destinationTransaction = null; $this->destinationTransaction = null;
$this->sourceAccount = null; $this->sourceAccount = null;
$this->sourceTransaction = null; $this->sourceTransaction = null;
$this->transactionGroup = null; $this->transactionGroup = null;
$this->transactionJournal = null; $this->transactionJournal = null;
$this->billRepository = app(BillRepositoryInterface::class); $this->billRepository = app(BillRepositoryInterface::class);
$this->categoryRepository = app(CategoryRepositoryInterface::class); $this->categoryRepository = app(CategoryRepositoryInterface::class);
$this->budgetRepository = app(BudgetRepositoryInterface::class); $this->budgetRepository = app(BudgetRepositoryInterface::class);
$this->tagFactory = app(TagFactory::class); $this->tagFactory = app(TagFactory::class);
$this->accountRepository = app(AccountRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class);
$this->currencyRepository = app(CurrencyRepositoryInterface::class); $this->currencyRepository = app(CurrencyRepositoryInterface::class);
$this->metaString = [ $this->metaString = [
'sepa_cc', 'sepa_cc',
'sepa_ct_op', 'sepa_ct_op',
'sepa_ct_id', 'sepa_ct_id',
@@ -102,8 +103,8 @@ class JournalUpdateService
'external_id', 'external_id',
'external_url', 'external_url',
]; ];
$this->metaDate = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', $this->metaDate = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date',
'invoice_date', ]; 'invoice_date',];
} }
public function setData(array $data): void public function setData(array $data): void
@@ -113,16 +114,16 @@ 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);
$this->tagFactory->setUser($transactionGroup->user); $this->tagFactory->setUser($transactionGroup->user);
$this->accountRepository->setUser($transactionGroup->user); $this->accountRepository->setUser($transactionGroup->user);
$this->destinationAccount = null; $this->destinationAccount = null;
$this->destinationTransaction = null; $this->destinationTransaction = null;
$this->sourceAccount = null; $this->sourceAccount = null;
$this->sourceTransaction = null; $this->sourceTransaction = null;
} }
public function setTransactionJournal(TransactionJournal $transactionJournal): void public function setTransactionJournal(TransactionJournal $transactionJournal): void
@@ -182,14 +183,14 @@ 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'])) {
$origSourceAccount = $this->getOriginalSourceAccount(); $origSourceAccount = $this->getOriginalSourceAccount();
$sourceId = $origSourceAccount->id; $sourceId = $origSourceAccount->id;
$sourceName = $origSourceAccount->name; $sourceName = $origSourceAccount->name;
} }
// make new account validator. // make new account validator.
@@ -198,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))
); );
@@ -227,7 +228,7 @@ class JournalUpdateService
private function getOriginalSourceAccount(): Account private function getOriginalSourceAccount(): Account
{ {
if (!$this->sourceAccount instanceof Account) { if (!$this->sourceAccount instanceof Account) {
$source = $this->getSourceTransaction(); $source = $this->getSourceTransaction();
$this->sourceAccount = $source->account; $this->sourceAccount = $source->account;
} }
@@ -238,7 +239,7 @@ class JournalUpdateService
{ {
if (!$this->sourceTransaction instanceof Transaction) { if (!$this->sourceTransaction instanceof Transaction) {
/** @var null|Transaction $result */ /** @var null|Transaction $result */
$result = $this->transactionJournal->transactions()->with(['account'])->where('amount', '<', 0)->first(); $result = $this->transactionJournal->transactions()->with(['account'])->where('amount', '<', 0)->first();
$this->sourceTransaction = $result; $this->sourceTransaction = $result;
} }
Log::debug(sprintf('getSourceTransaction: %s', $this->sourceTransaction->amount)); Log::debug(sprintf('getSourceTransaction: %s', $this->sourceTransaction->amount));
@@ -266,27 +267,27 @@ 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.');
$destination = $this->getOriginalDestinationAccount(); $destination = $this->getOriginalDestinationAccount();
$destId = $destination->id; $destId = $destination->id;
$destName = $destination->name; $destName = $destination->name;
} }
// 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();
$result = $validator->validateDestination(['id' => $destId, 'name' => $destName]); $result = $validator->validateDestination(['id' => $destId, 'name' => $destName]);
Log::debug( Log::debug(
sprintf( sprintf(
'hasValidDestinationAccount(%d, "%s") will return %s', 'hasValidDestinationAccount(%d, "%s") will return %s',
@@ -305,7 +306,7 @@ class JournalUpdateService
private function getOriginalDestinationAccount(): Account private function getOriginalDestinationAccount(): Account
{ {
if (!$this->destinationAccount instanceof Account) { if (!$this->destinationAccount instanceof Account) {
$destination = $this->getDestinationTransaction(); $destination = $this->getDestinationTransaction();
$this->destinationAccount = $destination->account; $this->destinationAccount = $destination->account;
} }
@@ -319,7 +320,7 @@ class JournalUpdateService
{ {
if (!$this->destinationTransaction instanceof Transaction) { if (!$this->destinationTransaction instanceof Transaction) {
/** @var null|Transaction $result */ /** @var null|Transaction $result */
$result = $this->transactionJournal->transactions()->where('amount', '>', 0)->first(); $result = $this->transactionJournal->transactions()->where('amount', '>', 0)->first();
$this->destinationTransaction = $result; $this->destinationTransaction = $result;
} }
@@ -337,12 +338,12 @@ 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,
'number' => $this->data['source_number'] ?? null, 'number' => $this->data['source_number'] ?? null,
'bic' => $this->data['source_bic'] ?? null, 'bic' => $this->data['source_bic'] ?? null,
]; ];
$expectedType = $this->getExpectedType(); $expectedType = $this->getExpectedType();
@@ -365,8 +366,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) {
@@ -379,7 +380,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();
@@ -401,12 +402,12 @@ 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,
'number' => $this->data['destination_number'] ?? null, 'number' => $this->data['destination_number'] ?? null,
'bic' => $this->data['destination_bic'] ?? null, 'bic' => $this->data['destination_bic'] ?? null,
]; ];
// make new account validator. // make new account validator.
@@ -430,7 +431,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.',
@@ -442,7 +443,7 @@ class JournalUpdateService
/** @var TransactionTypeFactory $typeFactory */ /** @var TransactionTypeFactory $typeFactory */
$typeFactory = app(TransactionTypeFactory::class); $typeFactory = app(TransactionTypeFactory::class);
$result = $typeFactory->find($this->data['type']); $result = $typeFactory->find($this->data['type']);
if (null !== $result) { if (null !== $result) {
Log::debug('Changed transaction type!'); Log::debug('Changed transaction type!');
$this->transactionJournal->transaction_type_id = $result->id; $this->transactionJournal->transaction_type_id = $result->id;
@@ -463,14 +464,14 @@ 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);
$billName = (string) ($this->data['bill_name'] ?? ''); $billName = (string)($this->data['bill_name'] ?? '');
$bill = $this->billRepository->findBill($billId, $billName); $bill = $this->billRepository->findBill($billId, $billName);
$this->transactionJournal->bill_id = $bill?->id; $this->transactionJournal->bill_id = $bill?->id;
Log::debug('Updated bill ID'); Log::debug('Updated bill ID');
} }
@@ -481,8 +482,8 @@ 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) {
@@ -557,7 +558,7 @@ class JournalUpdateService
{ {
// update notes. // update notes.
if ($this->hasFields(['notes'])) { if ($this->hasFields(['notes'])) {
$notes = '' === (string) $this->data['notes'] ? null : $this->data['notes']; $notes = '' === (string)$this->data['notes'] ? null : $this->data['notes'];
$this->storeNotes($this->transactionJournal, $notes); $this->storeNotes($this->transactionJournal, $notes);
} }
} }
@@ -587,10 +588,10 @@ 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,
]; ];
$factory->updateOrCreate($set); $factory->updateOrCreate($set);
} }
@@ -605,7 +606,7 @@ class JournalUpdateService
foreach ($this->metaDate as $field) { foreach ($this->metaDate as $field) {
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()));
@@ -614,15 +615,15 @@ class JournalUpdateService
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,
]; ];
$factory->updateOrCreate($set); $factory->updateOrCreate($set);
// also set date with timezone. // also set date with timezone.
$set = [ $set = [
'journal' => $this->transactionJournal, 'journal' => $this->transactionJournal,
'name' => sprintf('%s_tz', $field), 'name' => sprintf('%s_tz', $field),
'data' => $value?->format('e'), 'data' => $value?->format('e'),
]; ];
$factory->updateOrCreate($set); $factory->updateOrCreate($set);
} }
@@ -635,19 +636,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.
@@ -663,7 +664,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 {
@@ -673,14 +674,14 @@ class JournalUpdateService
return; return;
} }
$origSourceTransaction = $this->getSourceTransaction();
$origSourceTransaction = $this->getSourceTransaction(); $this->amountChanged = 0 !== bccomp($origSourceTransaction->amount, app('steam')->negative($amount));
$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); $destTransaction->amount = app('steam')->positive($amount);
$destTransaction->balance_dirty = true; $destTransaction->balance_dirty = true;
$destTransaction->save(); $destTransaction->save();
// refresh transactions. // refresh transactions.
$this->sourceTransaction->refresh(); $this->sourceTransaction->refresh();
@@ -695,17 +696,17 @@ class JournalUpdateService
return; return;
} }
$amount = $this->data['foreign_amount'] ?? null; $amount = $this->data['foreign_amount'] ?? null;
$foreignAmount = $this->getForeignAmount($amount); $foreignAmount = $this->getForeignAmount($amount);
$source = $this->getSourceTransaction(); $source = $this->getSourceTransaction();
$dest = $this->getDestinationTransaction(); $dest = $this->getDestinationTransaction();
$foreignCurrency = $source->foreignCurrency; $foreignCurrency = $source->foreignCurrency;
// find currency in data array // find currency in data array
$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) {
@@ -717,26 +718,26 @@ class JournalUpdateService
// add foreign currency info to source and destination if possible. // add foreign currency info to source and destination if possible.
if (null !== $foreignCurrency && null !== $foreignAmount) { if (null !== $foreignCurrency && null !== $foreignAmount) {
$source->foreign_currency_id = $foreignCurrency->id; $source->foreign_currency_id = $foreignCurrency->id;
$source->foreign_amount = app('steam')->negative($foreignAmount); $source->foreign_amount = app('steam')->negative($foreignAmount);
$source->save(); $source->save();
// 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');
$dest->transaction_currency_id = $foreignCurrency->id; $dest->transaction_currency_id = $foreignCurrency->id;
$dest->amount = app('steam')->positive($foreignAmount); $dest->amount = app('steam')->positive($foreignAmount);
$dest->foreign_amount = app('steam')->positive($source->amount); $dest->foreign_amount = app('steam')->positive($source->amount);
$dest->foreign_currency_id = $source->transaction_currency_id; $dest->foreign_currency_id = $source->transaction_currency_id;
} }
if (!$isTransfer && !$isBetween) { if (!$isTransfer && !$isBetween) {
$dest->foreign_currency_id = $foreignCurrency->id; $dest->foreign_currency_id = $foreignCurrency->id;
$dest->foreign_amount = app('steam')->positive($foreignAmount); $dest->foreign_amount = app('steam')->positive($foreignAmount);
} }
$dest->save(); $dest->save();
@@ -758,11 +759,11 @@ class JournalUpdateService
} }
if ('0' === $amount) { if ('0' === $amount) {
$source->foreign_currency_id = null; $source->foreign_currency_id = null;
$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));
} }
@@ -776,7 +777,7 @@ class JournalUpdateService
private function isBetweenAssetAndLiability(): bool private function isBetweenAssetAndLiability(): bool
{ {
/** @var Transaction $sourceTransaction */ /** @var Transaction $sourceTransaction */
$sourceTransaction = $this->transactionJournal->transactions()->where('amount', '<', 0)->first(); $sourceTransaction = $this->transactionJournal->transactions()->where('amount', '<', 0)->first();
/** @var Transaction $destinationTransaction */ /** @var Transaction $destinationTransaction */
$destinationTransaction = $this->transactionJournal->transactions()->where('amount', '>', 0)->first(); $destinationTransaction = $this->transactionJournal->transactions()->where('amount', '>', 0)->first();
@@ -791,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) {
@@ -816,4 +817,10 @@ class JournalUpdateService
return false; return false;
} }
public function isAmountChanged(): bool
{
return $this->amountChanged;
}
} }

View File

@@ -29,7 +29,7 @@ export default class Get {
* @returns {Promise<AxiosResponse<any>>} * @returns {Promise<AxiosResponse<any>>}
*/ */
list(params) { list(params) {
return api.get('/api/v2/budgets', {params: params}); return api.get('/api/v1/budgets', {params: params});
} }
} }

View File

@@ -490,8 +490,10 @@ let transactions = function () {
// addedSplit, is called from the HTML // addedSplit, is called from the HTML
// for source account // for source account
const renderAccount = function (item, b, c) { const renderAccount = function (item, b, c) {
return item.title + '<br><small class="text-muted">' + i18next.t('firefly.account_type_' + item.meta.type) + '</small>'; console.log('render account');
return item.name_with_balance + '<br><small class="text-muted">' + i18next.t('firefly.account_type_' + item.type) + '</small>';
}; };
console.log('here we are in');
addAutocomplete({ addAutocomplete({
selector: 'input.ac-source', selector: 'input.ac-source',
serverUrl: urls.account, serverUrl: urls.account,

View File

@@ -38,7 +38,7 @@ export function addAutocomplete(options) {
'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content 'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content
} }
}, },
queryParam: 'filter[query]', queryParam: 'query',
hiddenInput: true, hiddenInput: true,
// preventBrowserAutocomplete: true, // preventBrowserAutocomplete: true,
highlightTyped: true, highlightTyped: true,
@@ -48,6 +48,7 @@ export function addAutocomplete(options) {
params.serverParams['filter[account_types]'] = options.account_types; params.serverParams['filter[account_types]'] = options.account_types;
} }
if (typeof options.onRenderItem !== 'undefined' && null !== options.onRenderItem) { if (typeof options.onRenderItem !== 'undefined' && null !== options.onRenderItem) {
console.log('overrule onRenderItem.');
params.onRenderItem = options.onRenderItem; params.onRenderItem = options.onRenderItem;
} }
if (options.valueField) { if (options.valueField) {