Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Fix meta services for recurrences.
James Colea0b46d9d8a0a
diff --git a/app/Services/Internal/Destroy/AccountDestroyService.php b/app/Services/Internal/Destroy/AccountDestroyService.phpindex 80c8b1d301..b54bc98ded 100644--- a/app/Services/Internal/Destroy/AccountDestroyService.php+++ b/app/Services/Internal/Destroy/AccountDestroyService.php@@ -76,28 +76,6 @@ class AccountDestroyService}}- /**- * @param Account $account- */- private function destroyJournals(Account $account): void- {-- /** @var JournalDestroyService $service */- $service = app(JournalDestroyService::class);-- Log::debug('Now trigger account delete response #' . $account->id);- /** @var Transaction $transaction */- foreach ($account->transactions()->get() as $transaction) {- Log::debug('Now at transaction #' . $transaction->id);- /** @var TransactionJournal $journal */- $journal = $transaction->transactionJournal()->first();- if (null !== $journal) {- Log::debug('Call for deletion of journal #' . $journal->id);- $service->destroy($journal);- }- }- }-/*** @param Account $account*/@@ -135,6 +113,47 @@ class AccountDestroyService}}+ /**+ * @param Account $account+ * @param Account $moveTo+ */+ private function moveTransactions(Account $account, Account $moveTo): void+ {+ DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]);+ }++ /**+ * @param Account $account+ * @param Account $moveTo+ */+ private function updateRecurrences(Account $account, Account $moveTo): void+ {+ DB::table('recurrences_transactions')->where('source_id', $account->id)->update(['source_id' => $moveTo->id]);+ DB::table('recurrences_transactions')->where('destination_id', $account->id)->update(['destination_id' => $moveTo->id]);+ }++ /**+ * @param Account $account+ */+ private function destroyJournals(Account $account): void+ {++ /** @var JournalDestroyService $service */+ $service = app(JournalDestroyService::class);++ Log::debug('Now trigger account delete response #' . $account->id);+ /** @var Transaction $transaction */+ foreach ($account->transactions()->get() as $transaction) {+ Log::debug('Now at transaction #' . $transaction->id);+ /** @var TransactionJournal $journal */+ $journal = $transaction->transactionJournal()->first();+ if (null !== $journal) {+ Log::debug('Call for deletion of journal #' . $journal->id);+ $service->destroy($journal);+ }+ }+ }+/*** @param Account $account*/@@ -155,24 +174,4 @@ class AccountDestroyService}}-- /**- * @param Account $account- * @param Account $moveTo- */- private function moveTransactions(Account $account, Account $moveTo): void- {- DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]);- }-- /**- * @param Account $account- * @param Account $moveTo- */- private function updateRecurrences(Account $account, Account $moveTo): void- {- DB::table('recurrences_transactions')->where('source_id', $account->id)->update(['source_id' => $moveTo->id]);- DB::table('recurrences_transactions')->where('destination_id', $account->id)->update(['destination_id' => $moveTo->id]);- }-}diff --git a/app/Services/Internal/Destroy/BudgetDestroyService.php b/app/Services/Internal/Destroy/BudgetDestroyService.phpindex 41280b83fb..3fb5897e05 100644--- a/app/Services/Internal/Destroy/BudgetDestroyService.php+++ b/app/Services/Internal/Destroy/BudgetDestroyService.php@@ -30,6 +30,7 @@ use Log;/*** Class BudgetDestroyService+ ** @codeCoverageIgnore*/class BudgetDestroyServicediff --git a/app/Services/Internal/Destroy/CategoryDestroyService.php b/app/Services/Internal/Destroy/CategoryDestroyService.phpindex 75ae8e5010..a161b16770 100644--- a/app/Services/Internal/Destroy/CategoryDestroyService.php+++ b/app/Services/Internal/Destroy/CategoryDestroyService.php@@ -30,6 +30,7 @@ use Log;/*** Class CategoryDestroyService+ ** @codeCoverageIgnore*/class CategoryDestroyServicediff --git a/app/Services/Internal/Destroy/CurrencyDestroyService.php b/app/Services/Internal/Destroy/CurrencyDestroyService.phpindex bdec425c5d..358f223246 100644--- a/app/Services/Internal/Destroy/CurrencyDestroyService.php+++ b/app/Services/Internal/Destroy/CurrencyDestroyService.php@@ -29,6 +29,7 @@ use Log;/*** Class CurrencyDestroyService+ ** @codeCoverageIgnore*/class CurrencyDestroyServicediff --git a/app/Services/Internal/Destroy/RecurrenceDestroyService.php b/app/Services/Internal/Destroy/RecurrenceDestroyService.phpindex 6e704bbb2b..3f7ce76bc7 100644--- a/app/Services/Internal/Destroy/RecurrenceDestroyService.php+++ b/app/Services/Internal/Destroy/RecurrenceDestroyService.php@@ -34,6 +34,21 @@ use Log;*/class RecurrenceDestroyService{+ /**+ * Delete recurrence by ID+ *+ * @param int $recurrenceId+ */+ public function destroyById(int $recurrenceId): void+ {+ $recurrence = Recurrence::find($recurrenceId);+ if (null === $recurrence) {+ return;+ }+ $this->destroy($recurrence);++ }+/*** Delete recurrence.*@@ -69,19 +84,4 @@ class RecurrenceDestroyService}}- /**- * Delete recurrence by ID- *- * @param int $recurrenceId- */- public function destroyById(int $recurrenceId): void- {- $recurrence = Recurrence::find($recurrenceId);- if (null === $recurrence) {- return;- }- $this->destroy($recurrence);-- }-}diff --git a/app/Services/Internal/Destroy/TransactionGroupDestroyService.php b/app/Services/Internal/Destroy/TransactionGroupDestroyService.phpindex f39269d43a..e04736266a 100644--- a/app/Services/Internal/Destroy/TransactionGroupDestroyService.php+++ b/app/Services/Internal/Destroy/TransactionGroupDestroyService.php@@ -28,6 +28,7 @@ use FireflyIII\Models\TransactionGroup;/*** Class TransactionGroupDestroyService+ ** @codeCoverageIgnore*/class TransactionGroupDestroyServicediff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.phpindex 563d2b89aa..a7ca109c2f 100644--- a/app/Services/Internal/Support/AccountServiceTrait.php+++ b/app/Services/Internal/Support/AccountServiceTrait.php@@ -71,6 +71,32 @@ trait AccountServiceTraitreturn $iban;}+ /**+ * Returns true if the data in the array is submitted but empty.+ *+ * @param array $data+ *+ * @return bool+ */+ public function isEmptyOBData(array $data): bool+ {+ if (!array_key_exists('opening_balance', $data)+ && !array_key_exists('opening_balance_date', $data)+ ) {+ // not set, so false.+ return false;+ }+ // if isset, but is empty:+ if (+ (array_key_exists('opening_balance', $data) && '' === $data['opening_balance'])+ || (array_key_exists('opening_balance_date', $data) && '' === $data['opening_balance_date'])+ ) {+ return true;+ }++ return false;+ }+/*** Update meta data for account. Depends on type which fields are valid.*@@ -172,123 +198,6 @@ trait AccountServiceTraitreturn false;}- /**- * Returns true if the data in the array is submitted but empty.- *- * @param array $data- *- * @return bool- */- public function isEmptyOBData(array $data): bool- {- if (!array_key_exists('opening_balance', $data)- && !array_key_exists('opening_balance_date', $data)- ) {- // not set, so false.- return false;- }- // if isset, but is empty:- if (- (array_key_exists('opening_balance', $data) && '' === $data['opening_balance'])- || (array_key_exists('opening_balance_date', $data) && '' === $data['opening_balance_date'])- ) {- return true;- }-- return false;- }-- /**- * @param Account $account- * @param array $data- *- * @return TransactionGroup|null- */- protected function createOBGroup(Account $account, array $data): ?TransactionGroup- {- Log::debug('Now going to create an OB group.');- $language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data;- $sourceId = null;- $sourceName = null;- $destId = null;- $destName = null;- $amount = $data['opening_balance'];- if (1 === bccomp($amount, '0')) {- Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id));- // amount is positive.- $sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);- $destId = $account->id;- }- if (-1 === bccomp($amount, '0')) {- Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id));- // amount is not positive- $destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);- $sourceId = $account->id;- }- if (0 === bccomp($amount, '0')) {- // @codeCoverageIgnoreStart- Log::debug('Amount is zero, so will not make an OB group.');-- return null;- // @codeCoverageIgnoreEnd- }- $amount = app('steam')->positive($amount);- if (!array_key_exists('currency_id', $data)) {- $currency = $this->accountRepository->getAccountCurrency($account);- if (null === $currency) {- $currency = app('default')->getDefaultCurrencyByUser($account->user);- }- $data['currency_id'] = $currency->id;- }-- $submission = [- 'group_title' => null,- 'user' => $account->user_id,- 'transactions' => [- [- 'type' => 'Opening balance',- 'date' => $data['opening_balance_date'],- 'source_id' => $sourceId,- 'source_name' => $sourceName,- 'destination_id' => $destId,- 'destination_name' => $destName,- 'user' => $account->user_id,- 'currency_id' => $data['currency_id'],- 'order' => 0,- 'amount' => $amount,- 'foreign_amount' => null,- 'description' => trans('firefly.initial_balance_description', ['account' => $account->name]),- 'budget_id' => null,- 'budget_name' => null,- 'category_id' => null,- 'category_name' => null,- 'piggy_bank_id' => null,- 'piggy_bank_name' => null,- 'reconciled' => false,- 'notes' => null,- 'tags' => [],- ],- ],- ];- Log::debug('Going for submission', $submission);- $group = null;- /** @var TransactionGroupFactory $factory */- $factory = app(TransactionGroupFactory::class);- $factory->setUser($account->user);-- try {- $group = $factory->create($submission);- // @codeCoverageIgnoreStart- } catch (FireflyException $e) {- Log::error($e->getMessage());- Log::error($e->getTraceAsString());- }-- // @codeCoverageIgnoreEnd-- return $group;- }-/*** Delete TransactionGroup with opening balance in it.*@@ -308,6 +217,18 @@ trait AccountServiceTrait}}+ /**+ * Returns the opening balance group, or NULL if it does not exist.+ *+ * @param Account $account+ *+ * @return TransactionGroup|null+ */+ protected function getOBGroup(Account $account): ?TransactionGroup+ {+ return $this->accountRepository->getOpeningBalanceGroup($account);+ }+/*** @param int $currencyId* @param string $currencyCode@@ -332,18 +253,6 @@ trait AccountServiceTraitreturn $currency;}- /**- * Returns the opening balance group, or NULL if it does not exist.- *- * @param Account $account- *- * @return TransactionGroup|null- */- protected function getOBGroup(Account $account): ?TransactionGroup- {- return $this->accountRepository->getOpeningBalanceGroup($account);- }-/*** Update or create the opening balance group. Assumes valid data in $data.*@@ -407,4 +316,95 @@ trait AccountServiceTraitreturn $obGroup;}++ /**+ * @param Account $account+ * @param array $data+ *+ * @return TransactionGroup|null+ */+ protected function createOBGroup(Account $account, array $data): ?TransactionGroup+ {+ Log::debug('Now going to create an OB group.');+ $language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data;+ $sourceId = null;+ $sourceName = null;+ $destId = null;+ $destName = null;+ $amount = $data['opening_balance'];+ if (1 === bccomp($amount, '0')) {+ Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id));+ // amount is positive.+ $sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);+ $destId = $account->id;+ }+ if (-1 === bccomp($amount, '0')) {+ Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id));+ // amount is not positive+ $destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);+ $sourceId = $account->id;+ }+ if (0 === bccomp($amount, '0')) {+ // @codeCoverageIgnoreStart+ Log::debug('Amount is zero, so will not make an OB group.');++ return null;+ // @codeCoverageIgnoreEnd+ }+ $amount = app('steam')->positive($amount);+ if (!array_key_exists('currency_id', $data)) {+ $currency = $this->accountRepository->getAccountCurrency($account);+ if (null === $currency) {+ $currency = app('default')->getDefaultCurrencyByUser($account->user);+ }+ $data['currency_id'] = $currency->id;+ }++ $submission = [+ 'group_title' => null,+ 'user' => $account->user_id,+ 'transactions' => [+ [+ 'type' => 'Opening balance',+ 'date' => $data['opening_balance_date'],+ 'source_id' => $sourceId,+ 'source_name' => $sourceName,+ 'destination_id' => $destId,+ 'destination_name' => $destName,+ 'user' => $account->user_id,+ 'currency_id' => $data['currency_id'],+ 'order' => 0,+ 'amount' => $amount,+ 'foreign_amount' => null,+ 'description' => trans('firefly.initial_balance_description', ['account' => $account->name]),+ 'budget_id' => null,+ 'budget_name' => null,+ 'category_id' => null,+ 'category_name' => null,+ 'piggy_bank_id' => null,+ 'piggy_bank_name' => null,+ 'reconciled' => false,+ 'notes' => null,+ 'tags' => [],+ ],+ ],+ ];+ Log::debug('Going for submission', $submission);+ $group = null;+ /** @var TransactionGroupFactory $factory */+ $factory = app(TransactionGroupFactory::class);+ $factory->setUser($account->user);++ try {+ $group = $factory->create($submission);+ // @codeCoverageIgnoreStart+ } catch (FireflyException $e) {+ Log::error($e->getMessage());+ Log::error($e->getTraceAsString());+ }++ // @codeCoverageIgnoreEnd++ return $group;+ }}diff --git a/app/Services/Internal/Support/BillServiceTrait.php b/app/Services/Internal/Support/BillServiceTrait.phpindex b5b32ecbca..652fe9117d 100644--- a/app/Services/Internal/Support/BillServiceTrait.php+++ b/app/Services/Internal/Support/BillServiceTrait.php@@ -32,6 +32,7 @@ use Log;/*** Trait BillServiceTrait+ ** @codeCoverageIgnore*/trait BillServiceTraitdiff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.phpindex 7269164502..c7387435bc 100644--- a/app/Services/Internal/Support/JournalServiceTrait.php+++ b/app/Services/Internal/Support/JournalServiceTrait.php@@ -49,35 +49,6 @@ trait JournalServiceTraitprivate CategoryRepositoryInterface $categoryRepository;private TagFactory $tagFactory;-- /**- * @param string|null $amount- *- * @return string- * @codeCoverageIgnore- */- protected function getForeignAmount(?string $amount): ?string- {- if (null === $amount) {- Log::debug('No foreign amount info in array. Return NULL');-- return null;- }- if ('' === $amount) {- Log::debug('Foreign amount is empty string, return NULL.');-- return null;- }- if (0 === bccomp('0', $amount)) {- Log::debug('Foreign amount is 0.0, return NULL.');-- return null;- }- Log::debug(sprintf('Foreign amount is %s', $amount));-- return $amount;- }-/*** @param string $transactionType* @param string $direction@@ -113,136 +84,6 @@ trait JournalServiceTraitreturn $this->getCashAccount($result, $data, $expectedTypes[$transactionType]);}- /**- * @param string $amount- *- * @return string- * @throws FireflyException- * @codeCoverageIgnore- */- protected function getAmount(string $amount): string- {- if ('' === $amount) {- throw new FireflyException(sprintf('The amount cannot be an empty string: "%s"', $amount));- }- if (0 === bccomp('0', $amount)) {- throw new FireflyException(sprintf('The amount seems to be zero: "%s"', $amount));- }-- return $amount;- }-- /**- * @param TransactionJournal $journal- * @param NullArrayObject $data- *- * @codeCoverageIgnore- */- protected function storeBudget(TransactionJournal $journal, NullArrayObject $data): void- {- if (TransactionType::WITHDRAWAL !== $journal->transactionType->type) {- $journal->budgets()->sync([]);-- return;- }- $budget = $this->budgetRepository->findBudget($data['budget_id'], $data['budget_name']);- if (null !== $budget) {- Log::debug(sprintf('Link budget #%d to journal #%d', $budget->id, $journal->id));- $journal->budgets()->sync([$budget->id]);-- return;- }- // if the budget is NULL, sync empty.- $journal->budgets()->sync([]);- }-- /**- * @param TransactionJournal $journal- * @param NullArrayObject $data- *- * @codeCoverageIgnore- */- protected function storeCategory(TransactionJournal $journal, NullArrayObject $data): void- {- $category = $this->categoryRepository->findCategory($data['category_id'], $data['category_name']);- if (null !== $category) {- Log::debug(sprintf('Link category #%d to journal #%d', $category->id, $journal->id));- $journal->categories()->sync([$category->id]);-- return;- }- // if the category is NULL, sync empty.- $journal->categories()->sync([]);- }-- /**- * @param TransactionJournal $journal- * @param string $notes- *- * @codeCoverageIgnore- */- protected function storeNotes(TransactionJournal $journal, ?string $notes): void- {- $notes = (string)$notes;- $note = $journal->notes()->first();- if ('' !== $notes) {- if (null === $note) {- $note = new Note;- $note->noteable()->associate($journal);- }- $note->text = $notes;- $note->save();- Log::debug(sprintf('Stored notes for journal #%d', $journal->id));-- return;- }- if ('' === $notes && null !== $note) {- // try to delete existing notes.- try {- $note->delete();- // @codeCoverageIgnoreStart- } catch (Exception $e) {- Log::debug(sprintf('Could not delete journal notes: %s', $e->getMessage()));- }- // @codeCoverageIgnoreEnd- }- }-- /**- * Link tags to journal.- *- * @param TransactionJournal $journal- * @param array $tags- *- * @codeCoverageIgnore- */- protected function storeTags(TransactionJournal $journal, ?array $tags): void- {- Log::debug('Now in storeTags()', $tags ?? []);- $this->tagFactory->setUser($journal->user);- $set = [];- if (!is_array($tags)) {- Log::debug('Tags is not an array, break.');-- return;- }- Log::debug('Start of loop.');- foreach ($tags as $string) {- $string = (string)$string;- Log::debug(sprintf('Now at tag "%s"', $string));- if ('' !== $string) {- $tag = $this->tagFactory->findOrCreate($string);- if (null !== $tag) {- $set[] = $tag->id;- }- }- }- Log::debug('End of loop.');- Log::debug(sprintf('Total nr. of tags: %d', count($tags)), $tags);- $journal->tags()->sync($set);- Log::debug('Done!');- }-/*** @param array $data* @param array $types@@ -319,24 +160,6 @@ trait JournalServiceTraitreturn $account;}- /**- * @param Account|null $account- * @param array $data- * @param array $types- *- * @return Account|null- */- private function getCashAccount(?Account $account, array $data, array $types): ?Account- {- // return cash account.- if (null === $account && null === $data['name']- && in_array(AccountType::CASH, $types, true)) {- $account = $this->accountRepository->getCashAccount();- }-- return $account;- }-/*** @param Account|null $account* @param array $data@@ -401,4 +224,180 @@ trait JournalServiceTraitreturn $account;}++ /**+ * @param Account|null $account+ * @param array $data+ * @param array $types+ *+ * @return Account|null+ */+ private function getCashAccount(?Account $account, array $data, array $types): ?Account+ {+ // return cash account.+ if (null === $account && null === $data['name']+ && in_array(AccountType::CASH, $types, true)) {+ $account = $this->accountRepository->getCashAccount();+ }++ return $account;+ }++ /**+ * @param string $amount+ *+ * @return string+ * @throws FireflyException+ * @codeCoverageIgnore+ */+ protected function getAmount(string $amount): string+ {+ if ('' === $amount) {+ throw new FireflyException(sprintf('The amount cannot be an empty string: "%s"', $amount));+ }+ if (0 === bccomp('0', $amount)) {+ throw new FireflyException(sprintf('The amount seems to be zero: "%s"', $amount));+ }++ return $amount;+ }++ /**+ * @param string|null $amount+ *+ * @return string+ * @codeCoverageIgnore+ */+ protected function getForeignAmount(?string $amount): ?string+ {+ if (null === $amount) {+ Log::debug('No foreign amount info in array. Return NULL');++ return null;+ }+ if ('' === $amount) {+ Log::debug('Foreign amount is empty string, return NULL.');++ return null;+ }+ if (0 === bccomp('0', $amount)) {+ Log::debug('Foreign amount is 0.0, return NULL.');++ return null;+ }+ Log::debug(sprintf('Foreign amount is %s', $amount));++ return $amount;+ }++ /**+ * @param TransactionJournal $journal+ * @param NullArrayObject $data+ *+ * @codeCoverageIgnore+ */+ protected function storeBudget(TransactionJournal $journal, NullArrayObject $data): void+ {+ if (TransactionType::WITHDRAWAL !== $journal->transactionType->type) {+ $journal->budgets()->sync([]);++ return;+ }+ $budget = $this->budgetRepository->findBudget($data['budget_id'], $data['budget_name']);+ if (null !== $budget) {+ Log::debug(sprintf('Link budget #%d to journal #%d', $budget->id, $journal->id));+ $journal->budgets()->sync([$budget->id]);++ return;+ }+ // if the budget is NULL, sync empty.+ $journal->budgets()->sync([]);+ }++ /**+ * @param TransactionJournal $journal+ * @param NullArrayObject $data+ *+ * @codeCoverageIgnore+ */+ protected function storeCategory(TransactionJournal $journal, NullArrayObject $data): void+ {+ $category = $this->categoryRepository->findCategory($data['category_id'], $data['category_name']);+ if (null !== $category) {+ Log::debug(sprintf('Link category #%d to journal #%d', $category->id, $journal->id));+ $journal->categories()->sync([$category->id]);++ return;+ }+ // if the category is NULL, sync empty.+ $journal->categories()->sync([]);+ }++ /**+ * @param TransactionJournal $journal+ * @param string $notes+ *+ * @codeCoverageIgnore+ */+ protected function storeNotes(TransactionJournal $journal, ?string $notes): void+ {+ $notes = (string)$notes;+ $note = $journal->notes()->first();+ if ('' !== $notes) {+ if (null === $note) {+ $note = new Note;+ $note->noteable()->associate($journal);+ }+ $note->text = $notes;+ $note->save();+ Log::debug(sprintf('Stored notes for journal #%d', $journal->id));++ return;+ }+ if ('' === $notes && null !== $note) {+ // try to delete existing notes.+ try {+ $note->delete();+ // @codeCoverageIgnoreStart+ } catch (Exception $e) {+ Log::debug(sprintf('Could not delete journal notes: %s', $e->getMessage()));+ }+ // @codeCoverageIgnoreEnd+ }+ }++ /**+ * Link tags to journal.+ *+ * @param TransactionJournal $journal+ * @param array $tags+ *+ * @codeCoverageIgnore+ */+ protected function storeTags(TransactionJournal $journal, ?array $tags): void+ {+ Log::debug('Now in storeTags()', $tags ?? []);+ $this->tagFactory->setUser($journal->user);+ $set = [];+ if (!is_array($tags)) {+ Log::debug('Tags is not an array, break.');++ return;+ }+ Log::debug('Start of loop.');+ foreach ($tags as $string) {+ $string = (string)$string;+ Log::debug(sprintf('Now at tag "%s"', $string));+ if ('' !== $string) {+ $tag = $this->tagFactory->findOrCreate($string);+ if (null !== $tag) {+ $set[] = $tag->id;+ }+ }+ }+ Log::debug('End of loop.');+ Log::debug(sprintf('Total nr. of tags: %d', count($tags)), $tags);+ $journal->tags()->sync($set);+ Log::debug('Done!');+ }}diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.phpindex 41b03e5407..1699ed945d 100644--- a/app/Services/Internal/Support/RecurringTransactionTrait.php+++ b/app/Services/Internal/Support/RecurringTransactionTrait.php@@ -51,29 +51,7 @@ trait RecurringTransactionTrait{/*** @param Recurrence $recurrence- * @param array $repetitions- */- protected function createRepetitions(Recurrence $recurrence, array $repetitions): void- {- /** @var array $array */- foreach ($repetitions as $array) {- RecurrenceRepetition::create(- [- 'recurrence_id' => $recurrence->id,- 'repetition_type' => $array['type'],- 'repetition_moment' => $array['moment'] ?? '',- 'repetition_skip' => $array['skip'] ?? 0,- 'weekend' => $array['weekend'] ?? 1,- ]- );-- }- }--- /**- * @param Recurrence $recurrence- * @param string $note+ * @param string $note** @return bool*/@@ -102,6 +80,27 @@ trait RecurringTransactionTraitreturn true;}+ /**+ * @param Recurrence $recurrence+ * @param array $repetitions+ */+ protected function createRepetitions(Recurrence $recurrence, array $repetitions): void+ {+ /** @var array $array */+ foreach ($repetitions as $array) {+ RecurrenceRepetition::create(+ [+ 'recurrence_id' => $recurrence->id,+ 'repetition_type' => $array['type'],+ 'repetition_moment' => $array['moment'] ?? '',+ 'repetition_skip' => $array['skip'] ?? 0,+ 'weekend' => $array['weekend'] ?? 1,+ ]+ );++ }+ }+/*** Store transactions of a recurring transactions. It's complex but readable.*@@ -138,7 +137,7 @@ trait RecurringTransactionTraitif (!$validator->validateDestination($destination->id, null, null)) {throw new FireflyException(sprintf('Destination invalid: %s', $validator->destError)); // @codeCoverageIgnore}- if(array_key_exists('foreign_amount', $array) && '' === (string)$array['foreign_amount']) {+ if (array_key_exists('foreign_amount', $array) && '' === (string)$array['foreign_amount']) {unset($array['foreign_amount']);}// TODO typeOverrule: the account validator may have another opinion on the transaction type.@@ -156,20 +155,11 @@ trait RecurringTransactionTrait);$transaction->save();- $budget = null;if (array_key_exists('budget_id', $array)) {- /** @var BudgetFactory $budgetFactory */- $budgetFactory = app(BudgetFactory::class);- $budgetFactory->setUser($recurrence->user);- $budget = $budgetFactory->find($array['budget_id'], null);+ $this->setBudget($transaction, (int)$array['budget_id']);}-- $category = null;if (array_key_exists('category_id', $array)) {- /** @var CategoryFactory $categoryFactory */- $categoryFactory = app(CategoryFactory::class);- $categoryFactory->setUser($recurrence->user);- $category = $categoryFactory->findOrCreate($array['category_id'], null);+ $this->setCategory($transaction, (int)$array['category_id']);}// same for piggy bank@@ -177,57 +167,10 @@ trait RecurringTransactionTrait$this->updatePiggyBank($transaction, (int)$array['piggy_bank_id']);}- if(array_key_exists('tags', $array)) {+ if (array_key_exists('tags', $array)) {$this->updateTags($transaction, $array['tags']);}- // create recurrence transaction meta:- if (null !== $budget) {- RecurrenceTransactionMeta::create(- [- 'rt_id' => $transaction->id,- 'name' => 'budget_id',- 'value' => $budget->id,- ]- );- }- if (null !== $category) {- RecurrenceTransactionMeta::create(- [- 'rt_id' => $transaction->id,- 'name' => 'category_name',- 'value' => $category->name,- ]- );- }- }- }-- /**- * @param Recurrence $recurrence- *- * @codeCoverageIgnore- */- protected function deleteRepetitions(Recurrence $recurrence): void- {- $recurrence->recurrenceRepetitions()->delete();- }-- /**- * @param Recurrence $recurrence- *- * @codeCoverageIgnore- */- protected function deleteTransactions(Recurrence $recurrence): void- {- /** @var RecurrenceTransaction $transaction */- foreach ($recurrence->recurrenceTransactions as $transaction) {- $transaction->recurrenceTransactionMeta()->delete();- try {- $transaction->delete();- } catch (Exception $e) {- Log::debug($e->getMessage());- }}}@@ -283,6 +226,52 @@ trait RecurringTransactionTraitreturn $result ?? $repository->getCashAccount();}+ /**+ * @param RecurrenceTransaction $transaction+ * @param int $budgetId+ */+ private function setBudget(RecurrenceTransaction $transaction, int $budgetId): void+ {+ $budgetFactory = app(BudgetFactory::class);+ $budgetFactory->setUser($transaction->recurrence->user);+ $budget = $budgetFactory->find($budgetId, null);+ if (null === $budget) {+ return;+ }++ $meta = $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->first();+ if (null === $meta) {+ $meta = new RecurrenceTransactionMeta;+ $meta->rt_id = $transaction->id;+ $meta->name = 'budget_id';+ }+ $meta->value = $budget->id;+ $meta->save();+ }++ /**+ * @param RecurrenceTransaction $transaction+ * @param int $categoryId+ */+ private function setCategory(RecurrenceTransaction $transaction, int $categoryId): void+ {+ $categoryFactory = app(CategoryFactory::class);+ $categoryFactory->setUser($transaction->recurrence->user);+ $category = $categoryFactory->findOrCreate($categoryId, null);+ if (null === $category) {+ return;+ }++ $meta = $transaction->recurrenceTransactionMeta()->where('name', 'category_id')->first();+ if (null === $meta) {+ $meta = new RecurrenceTransactionMeta;+ $meta->rt_id = $transaction->id;+ $meta->name = 'category_id';+ }+ $meta->value = $category->id;+ $meta->save();+ }+/*** @param RecurrenceTransaction $transaction* @param int $piggyId@@ -328,4 +317,32 @@ trait RecurringTransactionTrait$transaction->recurrenceTransactionMeta()->where('name', 'tags')->delete();}}++ /**+ * @param Recurrence $recurrence+ *+ * @codeCoverageIgnore+ */+ protected function deleteRepetitions(Recurrence $recurrence): void+ {+ $recurrence->recurrenceRepetitions()->delete();+ }++ /**+ * @param Recurrence $recurrence+ *+ * @codeCoverageIgnore+ */+ protected function deleteTransactions(Recurrence $recurrence): void+ {+ /** @var RecurrenceTransaction $transaction */+ foreach ($recurrence->recurrenceTransactions as $transaction) {+ $transaction->recurrenceTransactionMeta()->delete();+ try {+ $transaction->delete();+ } catch (Exception $e) {+ Log::debug($e->getMessage());+ }+ }+ }}diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.phpindex 1cad40408f..5749cfae57 100644--- a/app/Services/Internal/Update/BillUpdateService.php+++ b/app/Services/Internal/Update/BillUpdateService.php@@ -56,7 +56,8 @@ class BillUpdateServiceif (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {$factory = app(TransactionCurrencyFactory::class);- $currency = $factory->find((int) ($data['currency_id'] ?? null), $data['currency_code'] ?? null) ?? app('amount')->getDefaultCurrencyByUser($bill->user);+ $currency = $factory->find((int)($data['currency_id'] ?? null), $data['currency_code'] ?? null) ??+ app('amount')->getDefaultCurrencyByUser($bill->user);// enable the currency if it isn't.$currency->enabled = true;diff --git a/app/Services/Internal/Update/CategoryUpdateService.php b/app/Services/Internal/Update/CategoryUpdateService.phpindex 819db8b38d..4d51a254cd 100644--- a/app/Services/Internal/Update/CategoryUpdateService.php+++ b/app/Services/Internal/Update/CategoryUpdateService.php@@ -67,8 +67,8 @@ class CategoryUpdateService*/public function update(Category $category, array $data): Category{- $oldName = $category->name;- if(array_key_exists('name', $data)) {+ $oldName = $category->name;+ if (array_key_exists('name', $data)) {$category->name = $data['name'];$category->save();// update triggers and actionsdiff --git a/app/Services/Internal/Update/CurrencyUpdateService.php b/app/Services/Internal/Update/CurrencyUpdateService.phpindex b1d99f0e05..f84a1b78f2 100644--- a/app/Services/Internal/Update/CurrencyUpdateService.php+++ b/app/Services/Internal/Update/CurrencyUpdateService.php@@ -24,7 +24,6 @@ declare(strict_types=1);namespace FireflyIII\Services\Internal\Update;use FireflyIII\Models\TransactionCurrency;-use Log;/*** Class CurrencyUpdateServicediff --git a/app/Services/Internal/Update/RecurrenceUpdateService.php b/app/Services/Internal/Update/RecurrenceUpdateService.phpindex f4bacda0a6..c3d04b8bd7 100644--- a/app/Services/Internal/Update/RecurrenceUpdateService.php+++ b/app/Services/Internal/Update/RecurrenceUpdateService.php@@ -114,63 +114,6 @@ class RecurrenceUpdateServicereturn $recurrence;}- /**- * TODO this method is way too complex.- *- * @param Recurrence $recurrence- * @param array $transactions- *- * @throws FireflyException- */- private function updateTransactions(Recurrence $recurrence, array $transactions): void- {- $originalCount = $recurrence->recurrenceTransactions()->count();- if (0 === count($transactions)) {- // wont drop transactions, rather avoid.- return;- }- // user added or removed repetitions, delete all and recreate:- if ($originalCount !== count($transactions)) {- Log::debug('Del + recreate');- $this->deleteTransactions($recurrence);- $this->createTransactions($recurrence, $transactions);-- return;- }- // loop all and try to match them:- if ($originalCount === count($transactions)) {- Log::debug('Loop and find');- foreach ($transactions as $current) {- $match = $this->matchTransaction($recurrence, $current);- if (null === $match) {- throw new FireflyException('Cannot match recurring transaction to existing transaction. Not sure what to do. Break.');- }- // TODO find currency- // TODO find foreign currency-- // update fields- $fields = [- 'source_id' => 'source_id',- 'destination_id' => 'destination_id',- 'amount' => 'amount',- 'foreign_amount' => 'foreign_amount',- 'description' => 'description',- ];- foreach ($fields as $field => $column) {- if (array_key_exists($field, $current)) {- $match->$column = $current[$field];- $match->save();- }- }- // update meta data- // budget_id- // category_id- // tags- // piggy_bank_id- }- }- }-/*** @param Recurrence $recurrence* @param string $text@@ -272,6 +215,71 @@ class RecurrenceUpdateServicereturn $query->first();}+ /**+ * TODO this method is way too complex.+ *+ * @param Recurrence $recurrence+ * @param array $transactions+ *+ * @throws FireflyException+ */+ private function updateTransactions(Recurrence $recurrence, array $transactions): void+ {+ $originalCount = $recurrence->recurrenceTransactions()->count();+ if (0 === count($transactions)) {+ // wont drop transactions, rather avoid.+ return;+ }+ // user added or removed repetitions, delete all and recreate:+ if ($originalCount !== count($transactions)) {+ Log::debug('Del + recreate');+ $this->deleteTransactions($recurrence);+ $this->createTransactions($recurrence, $transactions);++ return;+ }+ // loop all and try to match them:+ if ($originalCount === count($transactions)) {+ Log::debug('Loop and find');+ foreach ($transactions as $current) {+ $match = $this->matchTransaction($recurrence, $current);+ if (null === $match) {+ throw new FireflyException('Cannot match recurring transaction to existing transaction. Not sure what to do. Break.');+ }+ // TODO find currency+ // TODO find foreign currency++ // update fields+ $fields = [+ 'source_id' => 'source_id',+ 'destination_id' => 'destination_id',+ 'amount' => 'amount',+ 'foreign_amount' => 'foreign_amount',+ 'description' => 'description',+ ];+ foreach ($fields as $field => $column) {+ if (array_key_exists($field, $current)) {+ $match->$column = $current[$field];+ $match->save();+ }+ }+ // update meta data+ if (array_key_exists('budget_id', $current)) {+ $this->setBudget($match, (int)$current['budget_id']);+ }+ if (array_key_exists('category_id', $current)) {+ $this->setCategory($match, (int)$current['category_id']);+ }+ if (array_key_exists('tags', $current)) {+ $this->updateTags($match, $current['tags']);+ }+ if (array_key_exists('piggy_bank_id', $current)) {+ $this->updatePiggyBank($match, (int)$current['piggy_bank_id']);+ }+ }+ }+ }+/*** @param array $data*