Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Add support for batch submission.
James Cole8c0a82ac0a13
diff --git a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php b/app/Api/V1/Controllers/Models/Transaction/UpdateController.phpindex 78e60b2562..430bf872e5 100644--- a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php+++ b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php@@ -82,6 +82,9 @@ class UpdateController extends Controller$applyRules = $data['apply_rules'] ?? true;$fireWebhooks = $data['fire_webhooks'] ?? true;$runRecalculations = $oldHash !== $newHash;++ // FIXME responds to a single event.+ // flags in array?event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $runRecalculations));/** @var User $admin */diff --git a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php b/app/Api/V1/Requests/Models/Transaction/StoreRequest.phpindex 62666c1d99..2baf3cff6e 100644--- a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php+++ b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php@@ -64,6 +64,7 @@ class StoreRequest extends FormRequestreturn ['group_title' => $this->convertString('group_title'),'error_if_duplicate_hash' => $this->boolean('error_if_duplicate_hash'),+ 'batch_submission' => $this->boolean('batch_submission'),'apply_rules' => $this->boolean('apply_rules', true),'fire_webhooks' => $this->boolean('fire_webhooks', true),'transactions' => $this->getTransactionData(),diff --git a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.phpindex 9e34449ab9..eb491be76d 100644--- a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php+++ b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php@@ -113,7 +113,9 @@ class UpdateRequest extends FormRequest];$this->booleanFields = ['reconciled'];$this->arrayFields = ['tags'];- $data = [];+ $data = [+ 'batch_submission' => false,+ ];if ($this->has('transactions')) {$data['transactions'] = $this->getTransactionData();}@@ -123,6 +125,9 @@ class UpdateRequest extends FormRequestif ($this->has('fire_webhooks')) {$data['fire_webhooks'] = $this->boolean('fire_webhooks', true);}+ if ($this->has('batch_submission')) {+ $data['batch_submission'] = $this->boolean('batch_submission');+ }if ($this->has('group_title')) {$data['group_title'] = $this->convertString('group_title');}diff --git a/app/Console/Commands/Correction/CorrectsGroupAccounts.php b/app/Console/Commands/Correction/CorrectsGroupAccounts.phpindex 5a836584bb..2c82f4cfc7 100644--- a/app/Console/Commands/Correction/CorrectsGroupAccounts.php+++ b/app/Console/Commands/Correction/CorrectsGroupAccounts.php@@ -57,6 +57,7 @@ class CorrectsGroupAccounts extends Commandforeach ($groups as $groupId) {$group = TransactionGroup::find($groupId);// TODO in theory the "unifyAccounts" method could lead to the need for run recalculations.+ // FIXME needs to be a collection.$event = new UpdatedTransactionGroup($group, true, true, false);$handler->unifyAccounts($event);}diff --git a/app/Events/Model/TransactionGroup/CreatedTransactionGroupBatch.php b/app/Events/Model/TransactionGroup/CreatedTransactionGroupBatch.phpnew file mode 100644index 0000000000..bbbca184d5--- /dev/null+++ b/app/Events/Model/TransactionGroup/CreatedTransactionGroupBatch.php@@ -0,0 +1,36 @@+<?php+/*+ * CreatedTransactionGroupBatch.php+ * Copyright (c) 2026 [email protected]+ *+ * 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/>.+ */++namespace FireflyIII\Events\Model\TransactionGroup;++use FireflyIII\Events\Event;+use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Collection;++class CreatedTransactionGroupBatch extends Event+{+ use SerializesModels;++ /**+ * Create a new event instance.+ */+ public function __construct(public Collection $collection, public array $flags) {}+}diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.phpindex 53923e6a92..a52370249d 100644--- a/app/Factory/TransactionJournalFactory.php+++ b/app/Factory/TransactionJournalFactory.php@@ -50,13 +50,11 @@ use FireflyIII\Services\Internal\Destroy\JournalDestroyService;use FireflyIII\Services\Internal\Support\JournalServiceTrait;use FireflyIII\Support\Facades\Amount;use FireflyIII\Support\Facades\FireflyConfig;-use FireflyIII\Support\NullArrayObject;use FireflyIII\User;use FireflyIII\Validation\AccountValidator;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Log;use JsonException;-use function Safe\json_encode;/**@@ -68,17 +66,17 @@ class TransactionJournalFactory{use JournalServiceTrait;- private AccountRepositoryInterface $accountRepository;- private AccountValidator $accountValidator;- private BillRepositoryInterface $billRepository;- private CurrencyRepositoryInterface $currencyRepository;- private bool $errorOnHash = false;- private array $fields;- private PiggyBankEventFactory $piggyEventFactory;- private PiggyBankRepositoryInterface $piggyRepository;+ private AccountRepositoryInterface $accountRepository;+ private AccountValidator $accountValidator;+ private BillRepositoryInterface $billRepository;+ private CurrencyRepositoryInterface $currencyRepository;+ private bool $errorOnHash = false;+ private array $fields;+ private PiggyBankEventFactory $piggyEventFactory;+ private PiggyBankRepositoryInterface $piggyRepository;private TransactionTypeRepositoryInterface $typeRepository;- private User $user;- private UserGroup $userGroup;+ private User $user;+ private UserGroup $userGroup;/*** Constructor.@@ -110,22 +108,24 @@ class TransactionJournalFactory{Log::debug('Now in TransactionJournalFactory::create()');// convert to special object.- $dataObject = new NullArrayObject($data);+ //$dataObject = new NullArrayObject($data);Log::debug('Start of TransactionJournalFactory::create()');$collection = new Collection();- $transactions = $dataObject['transactions'] ?? [];+ $transactions = $data['transactions'] ?? [];if (0 === count($transactions)) {Log::error('There are no transactions in the array, the TransactionJournalFactory cannot continue.');return new Collection();}+ $batchSubmission = $data['batch_submission'] ?? false;try {/** @var array $row */foreach ($transactions as $index => $row) {+ $row['batch_submission'] = $batchSubmission;Log::debug(sprintf('Now creating journal %d/%d', $index + 1, count($transactions)));- $journal = $this->createJournal(new NullArrayObject($row));+ $journal = $this->createJournal($row);if ($journal instanceof TransactionJournal) {$collection->push($journal);}@@ -161,7 +161,7 @@ class TransactionJournalFactory** @SuppressWarnings("PHPMD.ExcessiveMethodLength")*/- private function createJournal(NullArrayObject $row): ?TransactionJournal+ private function createJournal(array $row): ?TransactionJournal{Log::debug('Now in TransactionJournalFactory::createJournal()');$row['import_hash_v2'] = $this->hashArray($row);@@ -169,18 +169,18 @@ class TransactionJournalFactory$this->errorIfDuplicate($row['import_hash_v2']);// Some basic fields- $type = $this->typeRepository->findTransactionType(null, $row['type']);- $carbon = $row['date'] ?? today(config('app.timezone'));- $order = $row['order'] ?? 0;+ $type = $this->typeRepository->findTransactionType(null, $row['type']);+ $carbon = $row['date'] ?? today(config('app.timezone'));+ $order = $row['order'] ?? 0;Log::debug('Find currency or return default.');- $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']);+ $currency = $this->currencyRepository->findCurrency((int)$row['currency_id'], $row['currency_code']);Log::debug('Find foreign currency or return NULL.');- $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);- $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']);- $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && $bill instanceof Bill ? $bill->id : null;- $description = (string) $row['description'];+ $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);+ $bill = $this->billRepository->findBill((int)$row['bill_id'], $row['bill_name']);+ $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && $bill instanceof Bill ? $bill->id : null;+ $description = (string)$row['description'];// Manipulate basic fields$carbon->setTimezone(config('app.timezone'));@@ -202,7 +202,7 @@ class TransactionJournalFactory}/** create or get source and destination accounts */- $sourceInfo = [+ $sourceInfo = ['id' => $row['source_id'],'name' => $row['source_name'],'iban' => $row['source_iban'],@@ -211,7 +211,7 @@ class TransactionJournalFactory'currency_id' => $currency->id,];- $destInfo = [+ $destInfo = ['id' => $row['destination_id'],'name' => $row['destination_name'],'iban' => $row['destination_iban'],@@ -221,8 +221,8 @@ class TransactionJournalFactory];Log::debug('Source info:', $sourceInfo);Log::debug('Destination info:', $destInfo);- $destinationAccount = null;- $sourceAccount = null;+ $destinationAccount = null;+ $sourceAccount = null;if (TransactionTypeEnum::DEPOSIT->value === $type->type) {Log::debug('Transaction type is deposit, start with destination first.');$destinationAccount = $this->getAccount($type->type, 'destination', $destInfo);@@ -247,38 +247,38 @@ class TransactionJournalFactory[$sourceAccount, $destinationAccount] = $this->reconciliationSanityCheck($sourceAccount, $destinationAccount);}- $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount);- $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency);- $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount);- $description = $this->getDescription($description);+ $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount);+ $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency);+ $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount);+ $description = $this->getDescription($description);Log::debug(sprintf(- 'Currency is #%d "%s", foreign currency is #%d "%s"',- $currency->id,- $currency->code,- $foreignCurrency?->id,- $foreignCurrency?->code- ));+ 'Currency is #%d "%s", foreign currency is #%d "%s"',+ $currency->id,+ $currency->code,+ $foreignCurrency?->id,+ $foreignCurrency?->code+ ));Log::debug(sprintf('Date: %s (%s)', $carbon->toW3cString(), $carbon->getTimezone()->getName()));/** Create a basic journal. */- $journal = TransactionJournal::create([- 'user_id' => $this->user->id,- 'user_group_id' => $this->userGroup->id,- 'transaction_type_id' => $type->id,- 'bill_id' => $billId,- 'transaction_currency_id' => $currency->id,- 'description' => substr($description, 0, 1000),- 'date' => $carbon,- 'date_tz' => $carbon->format('e'),- 'order' => $order,- 'tag_count' => 0,- 'completed' => 0,- ]);+ $journal = TransactionJournal::create([+ 'user_id' => $this->user->id,+ 'user_group_id' => $this->userGroup->id,+ 'transaction_type_id' => $type->id,+ 'bill_id' => $billId,+ 'transaction_currency_id' => $currency->id,+ 'description' => substr($description, 0, 1000),+ 'date' => $carbon,+ 'date_tz' => $carbon->format('e'),+ 'order' => $order,+ 'tag_count' => 0,+ 'completed' => !$row['batch_submission'],+ ]);Log::debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description));/** Create two transactions. */- $transactionFactory = app(TransactionFactory::class);+ $transactionFactory = app(TransactionFactory::class);$transactionFactory->setJournal($journal);$transactionFactory->setAccount($sourceAccount);$transactionFactory->setCurrency($currency);@@ -287,7 +287,7 @@ class TransactionJournalFactory$transactionFactory->setReconciled($row['reconciled'] ?? false);try {- $negative = $transactionFactory->createNegative((string) $row['amount'], (string) $row['foreign_amount']);+ $negative = $transactionFactory->createNegative((string)$row['amount'], (string)$row['foreign_amount']);} catch (FireflyException $e) {Log::error(sprintf('Exception creating negative transaction: %s', $e->getMessage()));$this->forceDeleteOnError(new Collection()->push($journal));@@ -296,7 +296,7 @@ class TransactionJournalFactory}/** @var TransactionFactory $transactionFactory */- $transactionFactory = app(TransactionFactory::class);+ $transactionFactory = app(TransactionFactory::class);$transactionFactory->setJournal($journal);$transactionFactory->setAccount($destinationAccount);$transactionFactory->setAccountInformation($destInfo);@@ -308,8 +308,8 @@ class TransactionJournalFactory// Firefly III will save the foreign currency information in such a way that both// asset accounts can look at the "amount" and "transaction_currency_id" column and// see the currency they expect to see.- $amount = (string) $row['amount'];- $foreignAmount = (string) $row['foreign_amount'];+ $amount = (string)$row['amount'];+ $foreignAmount = (string)$row['foreign_amount'];if ($foreignCurrency instanceof TransactionCurrency&& $foreignCurrency->id !== $currency->id@@ -317,8 +317,8 @@ class TransactionJournalFactory) {$transactionFactory->setCurrency($foreignCurrency);$transactionFactory->setForeignCurrency($currency);- $amount = (string) $row['foreign_amount'];- $foreignAmount = (string) $row['amount'];+ $amount = (string)$row['foreign_amount'];+ $foreignAmount = (string)$row['amount'];Log::debug('Swap primary/foreign amounts in transfer for new save method.');}@@ -331,7 +331,7 @@ class TransactionJournalFactorythrow new FireflyException($e->getMessage(), 0, $e);}- $journal->completed = true;+ Log::debug(sprintf('Is part of a batch submission? %s', var_export($row['batch_submission'], true)));$journal->save();$this->storeBudget($journal, $row);$this->storeCategory($journal, $row);@@ -344,20 +344,18 @@ class TransactionJournalFactoryreturn $journal;}- private function hashArray(NullArrayObject $row): string+ private function hashArray(array $row): string{- $dataRow = $row->getArrayCopy();-- unset($dataRow['import_hash_v2'], $dataRow['original_source']);+ unset($row['import_hash_v2'], $row['original_source']);try {- $json = json_encode($dataRow, JSON_THROW_ON_ERROR);+ $json = json_encode($row, JSON_THROW_ON_ERROR);} catch (JsonException $e) {Log::error(sprintf('Could not encode dataRow: %s', $e->getMessage()));$json = microtime();}- $hash = hash('sha256', $json);- Log::debug(sprintf('The hash is: %s', $hash), $dataRow);+ $hash = hash('sha256', $json);+ Log::debug(sprintf('The hash is: %s', $hash), $row);return $hash;}@@ -379,18 +377,17 @@ class TransactionJournalFactory/** @var null|TransactionJournalMeta $result */$result = TransactionJournalMeta::withTrashed()- ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id')- ->whereNotNull('transaction_journals.id')- ->where('transaction_journals.user_id', $this->user->id)- ->where('data', json_encode($hash, JSON_THROW_ON_ERROR))- ->with(['transactionJournal', 'transactionJournal.transactionGroup'])- ->first(['journal_meta.*'])- ;+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id')+ ->whereNotNull('transaction_journals.id')+ ->where('transaction_journals.user_id', $this->user->id)+ ->where('data', json_encode($hash, JSON_THROW_ON_ERROR))+ ->with(['transactionJournal', 'transactionJournal.transactionGroup'])+ ->first(['journal_meta.*']);if (null !== $result) {Log::warning(sprintf('Found a duplicate in errorIfDuplicate because hash %s is not unique!', $hash));$journal = $result->transactionJournal()->withTrashed()->first();$group = $journal?->transactionGroup()->withTrashed()->first();- $groupId = (int) $group?->id;+ $groupId = (int)$group?->id;throw new DuplicateTransactionException(sprintf('Duplicate of transaction #%d.', $groupId));}@@ -399,21 +396,21 @@ class TransactionJournalFactory/*** @throws FireflyException*/- private function validateAccounts(NullArrayObject $data): void+ private function validateAccounts(array $data): void{Log::debug(sprintf('Now in %s', __METHOD__));- $transactionType = $data['type'] ?? 'invalid';+ $transactionType = $data['type'] ?? 'invalid';$this->accountValidator->setUser($this->user);$this->accountValidator->setTransactionType($transactionType);// validate source account.- $array = [- 'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null,- 'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null,- 'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null,- 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null,+ $array = [+ 'id' => null !== $data['source_id'] ? (int)$data['source_id'] : null,+ 'name' => null !== $data['source_name'] ? (string)$data['source_name'] : null,+ 'iban' => null !== $data['source_iban'] ? (string)$data['source_iban'] : null,+ 'number' => null !== $data['source_number'] ? (string)$data['source_number'] : null,];- $validSource = $this->accountValidator->validateSource($array);+ $validSource = $this->accountValidator->validateSource($array);// do something with result:if (false === $validSource) {@@ -422,11 +419,11 @@ class TransactionJournalFactoryLog::debug('Source seems valid.');// validate destination account- $array = [- 'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null,- 'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null,- 'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null,- 'number' => null !== $data['destination_number'] ? (string) $data['destination_number'] : null,+ $array = [+ 'id' => null !== $data['destination_id'] ? (int)$data['destination_id'] : null,+ 'name' => null !== $data['destination_name'] ? (string)$data['destination_name'] : null,+ 'iban' => null !== $data['destination_iban'] ? (string)$data['destination_iban'] : null,+ 'number' => null !== $data['destination_number'] ? (string)$data['destination_number'] : null,];$validDestination = $this->accountValidator->validateDestination($array);@@ -511,7 +508,7 @@ class TransactionJournalFactory// return user's default:return Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);}- $result = $preference ?? $currency;+ $result = $preference ?? $currency;Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name));return $result;@@ -577,11 +574,11 @@ class TransactionJournalFactory/*** Link a piggy bank to this journal.*/- private function storePiggyEvent(TransactionJournal $journal, NullArrayObject $data): void+ private function storePiggyEvent(TransactionJournal $journal, array $data): void{Log::debug('Will now store piggy event.');- $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']);+ $piggyBank = $this->piggyRepository->findPiggyBank((int)$data['piggy_bank_id'], $data['piggy_bank_name']);if ($piggyBank instanceof PiggyBank) {$this->piggyEventFactory->create($journal, $piggyBank);@@ -592,17 +589,17 @@ class TransactionJournalFactoryLog::debug('Create no piggy event');}- private function storeMetaFields(TransactionJournal $journal, NullArrayObject $transaction): void+ private function storeMetaFields(TransactionJournal $journal, array $transaction): void{foreach ($this->fields as $field) {$this->storeMeta($journal, $transaction, $field);}}- protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void+ protected function storeMeta(TransactionJournal $journal, array $data, string $field): void{- $set = ['journal' => $journal, 'name' => $field, 'data' => (string) ($data[$field] ?? '')];- if ($data[$field] instanceof Carbon) {+ $set = ['journal' => $journal, 'name' => $field, 'data' => (string)($data[$field] ?? '')];+ if (array_key_exists($field, $data) && $data[$field] instanceof Carbon) {$data[$field]->setTimezone(config('app.timezone'));Log::debug(sprintf('%s Date: %s (%s)', $field, $data[$field], $data[$field]->timezone->getName()));$set['data'] = $data[$field]->format('Y-m-d H:i:s');@@ -615,7 +612,7 @@ class TransactionJournalFactory$factory->updateOrCreate($set);}- private function storeLocation(TransactionJournal $journal, NullArrayObject $data): void+ private function storeLocation(TransactionJournal $journal, array $data): void{if (!in_array(null, [$data['longitude'], $data['latitude'], $data['zoom_level']], true)) {$location = new Location();diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.phpindex 36e7fbb737..bf9fcacb31 100644--- a/app/Helpers/Collector/GroupCollector.php+++ b/app/Helpers/Collector/GroupCollector.php@@ -441,7 +441,7 @@ class GroupCollector implements GroupCollectorInterface$this->query->orWhereIn('transaction_journals.transaction_group_id', $groupIds);}$result = $this->query->get($this->fields);- $this->dumpQueryInLogs();+ // $this->dumpQueryInLogs();Log::debug(sprintf('Count of result is %d', $result->count()));// now to parse this into an array.$collection = $this->parseArray($result);diff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.phpindex 0566be1ce1..e446f30952 100644--- a/app/Services/Internal/Support/JournalServiceTrait.php+++ b/app/Services/Internal/Support/JournalServiceTrait.php@@ -378,7 +378,7 @@ trait JournalServiceTraitreturn $amount;}- protected function storeBudget(TransactionJournal $journal, NullArrayObject $data): void+ protected function storeBudget(TransactionJournal $journal, array $data): void{if (TransactionTypeEnum::WITHDRAWAL->value !== $journal->transactionType->type) {$journal->budgets()->sync([]);@@ -396,7 +396,7 @@ trait JournalServiceTrait$journal->budgets()->sync([]);}- protected function storeCategory(TransactionJournal $journal, NullArrayObject $data): void+ protected function storeCategory(TransactionJournal $journal, array $data): void{$category = $this->categoryRepository->findCategory($data['category_id'], $data['category_name']);if (null !== $category) {