The personal finance app for everyone (by everyone)
Ruby
Keep split parts that are transfer legs intact (#4966)
Niels Eulinkbc0718059986
diff --git a/app/controllers/api/v1/splits_controller.rb b/app/controllers/api/v1/splits_controller.rbindex c27fafc496..f0801a8886 100644--- a/app/controllers/api/v1/splits_controller.rb+++ b/app/controllers/api/v1/splits_controller.rb@@ -79,7 +79,7 @@ class Api::V1::SplitsController < Api::V1::BaseControllerrender_splitrescue NotSplitrender_not_split- rescue ActiveRecord::RecordInvalid => e+ rescue Entry::SplitPartTransferredError, ActiveRecord::RecordInvalid => erender_unprocessable(e.message)end@@ -93,7 +93,7 @@ class Api::V1::SplitsController < Api::V1::BaseControllerhead :no_contentrescue NotSplitrender_not_split- rescue ActiveRecord::RecordInvalid => e+ rescue Entry::SplitPartTransferredError, ActiveRecord::RecordInvalid => erender_unprocessable(e.message)enddiff --git a/app/controllers/api/v1/transactions_controller.rb b/app/controllers/api/v1/transactions_controller.rbindex 73c7e22412..7ab8bdcb58 100644--- a/app/controllers/api/v1/transactions_controller.rb+++ b/app/controllers/api/v1/transactions_controller.rb@@ -218,13 +218,15 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerreturnend- @entry.destroy!+ @entry.destroy_unless_split_part_transferred!@entry.sync_account_laterrender json: {message: "Transaction deleted successfully"}, status: :ok+ rescue Entry::SplitPartTransferredError+ render json: { error: "validation_failed", message: "A part of this split is linked as a transfer. Remove that transfer before you delete the transaction." }, status: :unprocessable_entityrescue => eRails.logger.error "TransactionsController#destroy error: #{e.message}"Rails.logger.error e.backtrace.join("\n")diff --git a/app/controllers/concerns/entryable_resource.rb b/app/controllers/concerns/entryable_resource.rbindex 13f5798d09..aec75f63c8 100644--- a/app/controllers/concerns/entryable_resource.rb+++ b/app/controllers/concerns/entryable_resource.rb@@ -33,10 +33,12 @@ module EntryableResourcedef destroyreturn unless require_account_permission!(@entry.account)- @entry.destroy!+ @entry.destroy_unless_split_part_transferred!@entry.sync_account_laterredirect_back_or_to account_path(@entry.account), notice: t("account.entries.destroy.success")+ rescue Entry::SplitPartTransferredError+ redirect_back_or_to account_path(@entry.account), alert: t("account.entries.destroy.part_transferred")endprivatediff --git a/app/controllers/splits_controller.rb b/app/controllers/splits_controller.rbindex 45ae4510f7..3cb0bc99f5 100644--- a/app/controllers/splits_controller.rb+++ b/app/controllers/splits_controller.rb@@ -56,6 +56,8 @@ class SplitsController < ApplicationController@entry.sync_account_laterredirect_to transactions_path, notice: t("splits.update.success")+ rescue Entry::SplitPartTransferredError+ redirect_to transactions_path, alert: t("splits.edit.part_transferred")rescue ActiveRecord::RecordInvalid => eredirect_to transactions_path, alert: e.messageend@@ -75,6 +77,8 @@ class SplitsController < ApplicationController@entry.sync_account_laterredirect_to transactions_path, notice: t("splits.destroy.success")+ rescue Entry::SplitPartTransferredError+ redirect_to transactions_path, alert: t("splits.edit.part_transferred")endprivatediff --git a/app/controllers/transactions/bulk_deletions_controller.rb b/app/controllers/transactions/bulk_deletions_controller.rbindex 2cf1fc2dfb..f266100d68 100644--- a/app/controllers/transactions/bulk_deletions_controller.rb+++ b/app/controllers/transactions/bulk_deletions_controller.rb@@ -6,8 +6,16 @@ class Transactions::BulkDeletionsController < ApplicationControllerentries_scope = Current.family.entries.where(account_id: writable_account_ids).where(parent_entry_id: nil)- destroyed = entries_scope.destroy_by(id: bulk_delete_params[:entry_ids])+ kept = []+ destroyed = entries_scope.where(id: bulk_delete_params[:entry_ids]).filter_map do |entry|+ entry.destroy_unless_split_part_transferred!+ rescue Entry::SplitPartTransferredError+ kept << entry+ nil+ enddestroyed.map(&:account).uniq.each(&:sync_later)++ flash[:alert] = t(".part_transferred", count: kept.size) if kept.any?redirect_back_or_to transactions_url, notice: "#{destroyed.count} transaction#{destroyed.count == 1 ? "" : "s"} deleted"enddiff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex 22a2f07625..5bde910824 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -826,6 +826,14 @@ class TransactionsController < ApplicationController{} # read_only — no edits allowedend+ # A split part's amount, currency and kind belong to the split; the editor+ # disables them, and a change would make the parts stop adding up to the+ # parent or turn a transfer leg back into a plain transaction.+ if @entry.split_child?+ permitted = permitted.except(:amount, :currency)+ permitted[:entryable_attributes] = permitted[:entryable_attributes].except(:kind) if permitted[:entryable_attributes]+ end+# A matched transfer's category lives on its outflow leg; a category# sent for the inflow leg would look saved but never reach a budget.if permitted[:entryable_attributes]&.key?(:category_id) && @entry.transaction.category_set_on_transfer_outflow?diff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rbindex 498add7a2f..e0fd5f80c2 100644--- a/app/controllers/transfers_controller.rb+++ b/app/controllers/transfers_controller.rb@@ -103,6 +103,9 @@ class TransfersController < ApplicationControllerreturn unless require_account_permission!(inflow_account, redirect_path: transactions_url)Transfer.transaction do+ # The transfer row before any leg, the order unlinking, confirm! and+ # Entry#unsplit! take them in, so an edit racing an unlink cannot deadlock.+ Transfer.lock.find(@transfer.id)update_transfer_statusupdate_transfer_fees_and_amountupdate_transfer_details@@ -420,7 +423,9 @@ class TransfersController < ApplicationControllercurrent_destination_fee = @transfer.derived_destination_fee_amountsource_fee_changed = new_source_fee.present? && new_source_fee.to_d != current_source_feedest_fee_changed = new_destination_fee.present? && new_destination_fee.to_d != current_destination_fee- amount_changed = new_amount.present? && new_amount.to_d != @transfer.amount.to_d+ # A split part's amount belongs to the split: changing it here would make+ # the parts stop adding up to the parent.+ amount_changed = new_amount.present? && new_amount.to_d != @transfer.amount.to_d && !split_part_leg?return unless amount_changed || source_fee_changed || dest_fee_changed@@ -459,6 +464,10 @@ class TransfersController < ApplicationController@transfer.save!end+ def split_part_leg?+ [ @transfer.outflow_transaction, @transfer.inflow_transaction ].any? { |transaction| transaction.entry.split_child? }+ end+def update_fee_transaction(account:, old_fee:, new_fee:, name:)if old_fee > 0 && new_fee > 0fee_tx = @transfer.fee_transactions.find { |t| t.entry.account_id == account.id }diff --git a/app/models/assistant/function/delete_transaction.rb b/app/models/assistant/function/delete_transaction.rbindex f97e034e6e..5eaf52c3ab 100644--- a/app/models/assistant/function/delete_transaction.rb+++ b/app/models/assistant/function/delete_transaction.rb@@ -36,7 +36,8 @@ class Assistant::Function::DeleteTransaction < Assistant::FunctionIt deletes the transaction's root ledger entry, which cascades to thetransaction. It will not delete a split child transaction individually —- delete the split parent instead.+ delete the split parent instead. It will not delete a split while a part+ of it is linked as a transfer; that transfer must be removed first.INSTRUCTIONSendend@@ -69,7 +70,7 @@ class Assistant::Function::DeleteTransaction < Assistant::Function# post-delete account sync (best-effort), and returns a result hash. Returns# { success: true, deleted: true, transaction: } on success (with an optional# :warning if the sync could not be enqueued), or an error hash for- # not_found / split_child / delete_aborted.+ # not_found / split_child / split_part_transferred / delete_aborted.def call(params = {})transaction = find_transaction(params["id"], params["account_id"])return error("not_found", "No transaction with id '#{params["id"]}' in an account you can write to.") unless transaction@@ -84,9 +85,12 @@ class Assistant::Function::DeleteTransaction < Assistant::Function# 1) Destroy. Entry is the delegated_type root record; destroy! cascades# to the Transaction child (delegated_type ... dependent: :destroy) and# wraps itself in a transaction (atomic: fully destroyed or it raises).- # This is the exact record the native destroy action destroys.+ # This is the exact record and the same refusal as the native destroy+ # action: a split whose part is a transfer leg is not deleted.begin- entry.destroy!+ entry.destroy_unless_split_part_transferred!+ rescue Entry::SplitPartTransferredError+ return error("split_part_transferred", "A part of this split is linked as a transfer. Remove that transfer before you delete the transaction.")rescue ActiveRecord::RecordNotDestroyed# A before_destroy guard aborted the destroy (e.g. a split child that# slipped past the pre-check, or another constraint). `throw :abort` indiff --git a/app/models/entry.rb b/app/models/entry.rbindex f335488d81..db0ca98712 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -14,6 +14,12 @@ class Entry < ApplicationRecord# Key in transactions.extra marking a stale pending the sync excluded on its own.AUTO_EXCLUDED_PENDING_KEY = "auto_excluded_stale_pending".freeze+ # Raised when a split would be replaced or removed while one of its parts is+ # a leg of a confirmed transfer. Destroying that part destroys the transfer+ # and leaves the other leg behind as a standalone entry, so the transfer has+ # to be unlinked first.+ class SplitPartTransferredError < StandardError; end+attr_accessor :unsplittingmonetize :amount@@ -705,7 +711,8 @@ class Entry < ApplicationRecord# Replaces the children of a split under the same lock, so a concurrent unsplit can't be undone# and two edits can't both insert children. Returns false when the entry is no longer a split- # parent. Editing an existing split doesn't re-check pending/transfer: it creates no new split.+ # parent. Editing an existing split doesn't re-check whether the parent is pending or a transfer:+ # it creates no new split. Raises SplitPartTransferredError while a part is a leg of a confirmed transfer.def resplit!(splits)with_split_lock donext false unless split_parent?@@ -716,7 +723,8 @@ class Entry < ApplicationRecordendend- # Unsplits under the same lock. Returns false when another caller already did.+ # Unsplits under the same lock. Returns false when another caller already did. Raises+ # SplitPartTransferredError while a part is a leg of a confirmed transfer.def unsplit_once!with_split_lock donext false unless split_parent?@@ -726,6 +734,19 @@ class Entry < ApplicationRecordendend+ # Deletes this entry for a user. A split is refused like unsplit! while a part+ # is a leg of a confirmed transfer: deleting the parent takes the part and its+ # transfer with it and leaves the other leg behind as a standalone entry.+ # Syncs and imports that remove entries call destroy! directly.+ def destroy_unless_split_part_transferred!+ return destroy! unless split_parent?++ with_split_lock do+ refuse_while_split_part_transferred! if split_parent?+ destroy!+ end+ end+def split_child?parent_entry_id.present?end@@ -793,9 +814,20 @@ class Entry < ApplicationRecordupdate!(reconciled_status: next_status)end+ # True when a part of this split is a leg of a confirmed transfer.+ def split_part_transferred?+ part_ids = split_part_transaction_ids++ Transfer.confirmed.where(outflow_transaction_id: part_ids)+ .or(Transfer.confirmed.where(inflow_transaction_id: part_ids))+ .exists?+ end+# Removes split children and restores parent entry.def unsplit!self.class.transaction do+ refuse_while_split_part_transferred!+child_entries.each do |child|child.unsplitting = truechild.destroy!@@ -1060,6 +1092,20 @@ class Entry < ApplicationRecordendend+ # Locks the parts' transfers and then the parts, the order Transfer#confirm!+ # and Transfer#destroy! take them in, so a transfer created, confirmed or+ # removed on a part at the same time waits and the check sees it.+ def refuse_while_split_part_transferred!+ part_ids = split_part_transaction_ids.pluck(:entryable_id)+ Transfer.where(outflow_transaction_id: part_ids).or(Transfer.where(inflow_transaction_id: part_ids)).order(:id).lock.pluck(:id)+ Transaction.where(id: part_ids).order(:id).lock.pluck(:id)+ raise SplitPartTransferredError, "Remove the transfer on a split part before changing the split" if split_part_transferred?+ end++ def split_part_transaction_ids+ child_entries.where(entryable_type: "Transaction").select(:entryable_id)+ end+# Remembers the earliest date this entry had before any save that changed# it, for sync_account_later to use as the sync window start.#diff --git a/app/models/transfer.rb b/app/models/transfer.rbindex b16bc0a402..13928ea424 100644--- a/app/models/transfer.rb+++ b/app/models/transfer.rb@@ -20,6 +20,10 @@ class Transfer < ApplicationRecord# (or its entry) is deleted, so the surviving leg never keeps a transfer kind# without a transfer.before_destroy :release_transactions+ # Destroying locks this row before the fee transactions and the legs, the+ # order confirm! and Entry#unsplit! take them in, so an unlink and a confirm+ # or unsplit do not deadlock each other.+ before_destroy :lock_row, prepend: trueclass << self# The outflow leg's kind for a transfer into this account. Transfer::Creator,@@ -189,6 +193,10 @@ class Transfer < ApplicationRecord# once the user confirms the match.def confirm!Transfer.transaction do+ # Raises RecordNotFound when the transfer was removed in the meantime,+ # for example with an unsplit part, instead of giving its surviving leg a+ # transfer kind.+ Transfer.lock.find(id)update!(status: "confirmed")# The kind is determined by the DESTINATION account (inflow), matching Transfer::Creator logic@@ -232,6 +240,18 @@ class Transfer < ApplicationRecordendprivate+ # Reads the status under the lock. When a confirm committed after the+ # caller loaded this transfer, the legs it loaded are stale too, so they are+ # read again: release_transactions resets the kinds the confirm set.+ def lock_row+ current_status = Transfer.where(id: id).lock.pick(:status)+ return if current_status.nil? || current_status == status++ self.status = current_status+ inflow_transaction&.reload+ outflow_transaction&.reload+ end+def contribution_by_default?to_account.present? && Transfer.kind_for_account(to_account, from_account: from_account) == "investment_contribution"enddiff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.ymlindex 00f96fb023..9f93bc7821 100644--- a/config/locales/views/accounts/en.yml+++ b/config/locales/views/accounts/en.yml@@ -4,6 +4,7 @@ en:entries:destroy:success: "Entry deleted successfully."+ part_transferred: "A part of this split is linked as a transfer. Remove that transfer before you delete the transaction."accounts:reconciliation_indicator:matched: All transactions reconcileddiff --git a/config/locales/views/accounts/nl.yml b/config/locales/views/accounts/nl.ymlindex 7c7c0bfaca..bce8403d90 100644--- a/config/locales/views/accounts/nl.yml+++ b/config/locales/views/accounts/nl.yml@@ -4,6 +4,7 @@ nl:entries:destroy:success: "Item verwijderd."+ part_transferred: "Een deel van deze splitsing is gekoppeld als overboeking. Verwijder die overboeking voordat u de transactie verwijdert."accounts:not_authorized: "U heeft geen toestemming om dit account te beheren"account:diff --git a/config/locales/views/splits/en.yml b/config/locales/views/splits/en.ymlindex c7c2d0da3e..698324ae9a 100644--- a/config/locales/views/splits/en.yml+++ b/config/locales/views/splits/en.yml@@ -41,6 +41,7 @@ en:description: Modify the split entries for this transaction.submit: Update Splitnot_split: This transaction is not split.+ part_transferred: A part of this split is linked as a transfer. Remove that transfer before you edit or unsplit the split.update:success: Split updated successfullychild:diff --git a/config/locales/views/splits/nl.yml b/config/locales/views/splits/nl.ymlindex 92fb2c9975..d0410230a1 100644--- a/config/locales/views/splits/nl.yml+++ b/config/locales/views/splits/nl.yml@@ -41,6 +41,7 @@ nl:description: "Pas de gesplitste boekingen voor deze transactie aan."submit: "Splitsing bijwerken"not_split: "Deze transactie is niet gesplitst."+ part_transferred: "Een deel van deze splitsing is gekoppeld als overboeking. Verwijder die overboeking voordat u de splitsing bewerkt of ongedaan maakt."update:success: "Splitsing succesvol bijgewerkt"child:diff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex 41857b56b6..1981d520b5 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -1,6 +1,11 @@---en:transactions:+ bulk_deletions:+ create:+ part_transferred:+ one: "1 split transaction was not deleted: a part of it is linked as a transfer. Remove that transfer first."+ other: "%{count} split transactions were not deleted: a part of each is linked as a transfer. Remove those transfers first."bulk_updates:new:cancel: Canceldiff --git a/config/locales/views/transactions/nl.yml b/config/locales/views/transactions/nl.ymlindex 98dcbaf8ab..3a45561db3 100644--- a/config/locales/views/transactions/nl.yml+++ b/config/locales/views/transactions/nl.yml@@ -1,6 +1,11 @@---nl:transactions:+ bulk_deletions:+ create:+ part_transferred:+ one: "1 gesplitste transactie is niet verwijderd: een deel ervan is gekoppeld als overboeking. Verwijder eerst die overboeking."+ other: "%{count} gesplitste transacties zijn niet verwijderd: van elk is een deel gekoppeld als overboeking. Verwijder eerst die overboekingen."bulk_updates:new:cancel: "Annuleren"diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 4360e6b380..7b66b997d7 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -10158,6 +10158,9 @@ paths:application/json:schema:"$ref": "#/components/schemas/Split"+ '422':+ description: a part of the split is linked as a transfer; remove that transfer+ firstrequestBody:content:application/json:@@ -10173,6 +10176,9 @@ paths:responses:'204':description: split removed+ '422':+ description: a part of the split is linked as a transfer; remove that transfer+ first'404':description: transaction is not split"/api/v1/syncs":@@ -11112,6 +11118,13 @@ paths:application/json:schema:"$ref": "#/components/schemas/ErrorResponse"+ '422':+ description: the transaction is split and a part is linked as a transfer;+ remove that transfer first+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse""/api/v1/transfers":get:summary: List transfersdiff --git a/spec/requests/api/v1/splits_spec.rb b/spec/requests/api/v1/splits_spec.rbindex e97d47e644..beda3511d3 100644--- a/spec/requests/api/v1/splits_spec.rb+++ b/spec/requests/api/v1/splits_spec.rb@@ -60,6 +60,29 @@ RSpec.describe 'API V1 Transaction Split', type: :request dolet(:transaction_id) { transaction.id }+ let(:loan_account) do+ Account.create!(+ family: family,+ name: 'Mortgage',+ balance: 100_000,+ currency: 'USD',+ accountable: Loan.create!+ )+ end++ # Splits the transaction and links its first part to a loan as a payment.+ def split_with_transferred_part+ part = transaction.entry.split!([ { name: 'Principal', amount: 60 }, { name: 'Interest', amount: 40 } ]).first+ loan_entry = loan_account.entries.create!(+ name: 'Payment',+ date: Date.current,+ amount: -60,+ currency: 'USD',+ entryable: Transaction.new+ )+ Transfer.create!(inflow_transaction: loan_entry.transaction, outflow_transaction: part.transaction, status: 'confirmed', amount: 60)+ end+let(:split_payload) do{split: {@@ -133,6 +156,11 @@ RSpec.describe 'API V1 Transaction Split', type: :request dobefore { transaction.entry.split!([ { name: 'A', amount: 70 }, { name: 'B', amount: 30 } ]) }run_test!end++ response '422', 'a part of the split is linked as a transfer; remove that transfer first' do+ before { split_with_transferred_part }+ run_test!+ endenddelete 'Remove a transaction split' do@@ -145,6 +173,11 @@ RSpec.describe 'API V1 Transaction Split', type: :request dorun_test!end+ response '422', 'a part of the split is linked as a transfer; remove that transfer first' do+ before { split_with_transferred_part }+ run_test!+ end+response '404', 'transaction is not split' dorun_test!enddiff --git a/spec/requests/api/v1/transactions_spec.rb b/spec/requests/api/v1/transactions_spec.rbindex 2b7d101dab..32788b8d5f 100644--- a/spec/requests/api/v1/transactions_spec.rb+++ b/spec/requests/api/v1/transactions_spec.rb@@ -449,6 +449,19 @@ RSpec.describe 'API V1 Transactions', type: :request dorun_test!end++ response '422', 'the transaction is split and a part is linked as a transfer; remove that transfer first' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ before do+ part = another_transaction.entry.split!([ { name: 'Principal', amount: 3 }, { name: 'Interest', amount: 2 } ]).first+ loan_account = Account.create!(family: family, name: 'Mortgage', balance: 100_000, currency: 'USD', accountable: Loan.create!)+ loan_entry = loan_account.entries.create!(name: 'Payment', date: part.date, amount: -3, currency: 'USD', entryable: Transaction.new)+ Transfer.create!(inflow_transaction: loan_entry.transaction, outflow_transaction: part.transaction, status: 'confirmed', amount: 3)+ end++ run_test!+ endendendenddiff --git a/test/controllers/api/v1/splits_controller_test.rb b/test/controllers/api/v1/splits_controller_test.rbindex 19eb6607a1..0e8385ad6e 100644--- a/test/controllers/api/v1/splits_controller_test.rb+++ b/test/controllers/api/v1/splits_controller_test.rb@@ -148,8 +148,29 @@ class Api::V1::SplitsControllerTest < ActionDispatch::IntegrationTestassert_response :not_foundend+ test "update refuses while a part is linked as a transfer" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)++ patch api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ assert_equal %w[Interest Principal], @entry.reload.child_entries.order(:name).pluck(:name)+ end+# DESTROY+ test "destroy refuses while a part is linked as a transfer" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)++ delete api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert @entry.reload.split_parent?+ end+test "unsplits a transaction" dopost api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :jsondiff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rbindex b9b8456a92..0c362fa911 100644--- a/test/controllers/api/v1/transactions_controller_test.rb+++ b/test/controllers/api/v1/transactions_controller_test.rb@@ -1490,6 +1490,19 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTestassert response_data.key?("message")end+ test "should reject destroying a split whose part is linked as a transfer" do+ parent = create_transaction(account: accounts(:depository), amount: 100, name: "Mortgage")+ part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)++ assert_no_difference [ "Entry.count", "Transfer.count" ] do+ delete api_v1_transaction_url(parent.transaction), headers: api_headers(@api_key)+ end++ assert_response :unprocessable_entity+ assert_equal "validation_failed", JSON.parse(response.body)["error"]+ end+test "should reject destroy with read-only API key" dodelete api_v1_transaction_url(@transaction), headers: api_headers(@read_only_api_key)assert_response :forbiddendiff --git a/test/controllers/splits_controller_test.rb b/test/controllers/splits_controller_test.rbindex f1d7d6fa54..0a71a29e9f 100644--- a/test/controllers/splits_controller_test.rb+++ b/test/controllers/splits_controller_test.rb@@ -365,6 +365,32 @@ class SplitsControllerTest < ActionDispatch::IntegrationTestrefute @entry.reload.excluded?end+ test "destroy refuses while a part is linked as a transfer" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)++ assert_no_difference "Entry.count" do+ delete transaction_split_path(@entry)+ end++ assert_redirected_to transactions_url+ assert_equal I18n.t("splits.edit.part_transferred"), flash[:alert]+ assert @entry.reload.split_parent?+ end++ test "update refuses while a part is linked as a transfer" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)++ patch transaction_split_path(@entry), params: {+ split: { splits: [ { name: "A", amount: "-50" }, { name: "B", amount: "-50" } ] }+ }++ assert_redirected_to transactions_url+ assert_equal I18n.t("splits.edit.part_transferred"), flash[:alert]+ assert_equal %w[Interest Principal], @entry.reload.child_entries.order(:name).pluck(:name)+ end+privatedef sql_queries(&block)queries = []diff --git a/test/controllers/transactions/bulk_deletions_controller_test.rb b/test/controllers/transactions/bulk_deletions_controller_test.rbindex f6fbf96c84..227dd0defa 100644--- a/test/controllers/transactions/bulk_deletions_controller_test.rb+++ b/test/controllers/transactions/bulk_deletions_controller_test.rb@@ -1,6 +1,8 @@require "test_helper"class Transactions::BulkDeletionsControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper+setup dosign_in @user = users(:family_admin)@entry = entries(:transaction)@@ -45,4 +47,18 @@ class Transactions::BulkDeletionsControllerTest < ActionDispatch::IntegrationTesassert_redirected_to transactions_urlassert_equal "1 transaction deleted", flash[:notice]end++ test "bulk delete keeps a split whose part is linked as a transfer and deletes the rest" do+ parent = create_transaction(account: accounts(:depository), amount: 100, name: "Mortgage")+ part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ transfer = link_split_part_to_loan(part)++ post transactions_bulk_deletion_url, params: { bulk_delete: { entry_ids: [ parent.id, @entry.id ] } }++ assert Entry.exists?(parent.id)+ assert Transfer.exists?(transfer.id)+ assert_not Entry.exists?(@entry.id)+ assert_equal "1 transaction deleted", flash[:notice]+ assert_equal I18n.t("transactions.bulk_deletions.create.part_transferred", count: 1), flash[:alert]+ endenddiff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex d4b616ee30..dd763dc157 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -2541,6 +2541,42 @@ endassert_select "##{dom_id(outflow, "category_menu_desktop")} [data-ds--popover-frame-id-value='category_dropdown']"end+ test "deleting a split is refused while a part is linked as a transfer" do+ parent = create_transaction(account: accounts(:depository), amount: 100, name: "Mortgage")+ part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)++ assert_no_difference [ "Entry.count", "Transfer.count" ] do+ delete transaction_url(parent)+ end++ assert_equal I18n.t("account.entries.destroy.part_transferred"), flash[:alert]+ end++ test "update keeps a split part's amount, currency and kind" do+ parent = create_transaction(account: accounts(:depository), amount: 100, name: "Mortgage")+ part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)+ part.transaction.update!(kind: "loan_payment")++ patch transaction_url(part), params: {+ entry: {+ amount: "75",+ currency: "EUR",+ nature: "outflow",+ notes: "Principal part",+ entryable_type: "Transaction",+ entryable_attributes: { id: part.entryable_id, kind: "standard" }+ }+ }++ part.reload+ assert_equal 60, part.amount+ assert_equal "USD", part.currency+ assert_equal "loan_payment", part.transaction.kind+ assert_equal "Principal part", part.notes+ end+test "update drops a category sent for a matched transfer's inflow leg" dooutflow = Transaction.create!(kind: "investment_contribution")Entry.create!(account: accounts(:depository), entryable: outflow, name: "Contribution", amount: 500, currency: "USD", date: Date.current)diff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rbindex a2f7179519..46bed9b3ab 100644--- a/test/controllers/transfers_controller_test.rb+++ b/test/controllers/transfers_controller_test.rb@@ -689,6 +689,22 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestassert_equal "Test notes", transfer.reload.notesend+ test "editing a transfer locks the transfer before its legs" do+ transfer = transfers(:one)+ locking = []+ record = ->(*, payload) do+ sql = payload[:sql]+ locking << sql if sql.include?("FOR UPDATE") || sql.match?(/\A\s*(UPDATE|DELETE)\b/i)+ end++ ActiveSupport::Notifications.subscribed(record, "sql.active_record") do+ patch transfer_url(transfer), params: { transfer: { category_id: categories(:food_and_drink).id, notes: "Rent" } }+ end++ assert_redirected_to transactions_url+ assert_match(/FROM "transfers".*FOR UPDATE/, locking.first)+ end+test "a category chosen in the transfer editor is locked as the user's" dotransfer = transfers(:one)category = families(:dylan_family).investment_contributions_category@@ -1233,6 +1249,18 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestassert_equal I18n.t("recurring_transactions.transfer_feature_disabled"), flash[:alert]end+ test "update leaves the amount of a transfer whose leg is a split part" do+ parent = create_transaction(account: accounts(:depository), amount: 100, name: "Mortgage")+ part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ transfer = link_split_part_to_loan(part)++ patch transfer_url(transfer), params: { transfer: { amount: "75", notes: "Principal" } }++ assert_equal 60, part.reload.amount+ assert_equal(-60, transfer.inflow_transaction.entry.reload.amount)+ assert_equal "Principal", transfer.reload.notes+ end+privatedef create_dated_transfer(date:, amount: 2000)outflow_entry = create_transaction(date: date, account: accounts(:depository), amount: amount)diff --git a/test/models/assistant/function/delete_transaction_test.rb b/test/models/assistant/function/delete_transaction_test.rbindex c526c097ae..d387a5f5fd 100644--- a/test/models/assistant/function/delete_transaction_test.rb+++ b/test/models/assistant/function/delete_transaction_test.rb@@ -1,6 +1,8 @@require "test_helper"class Assistant::Function::DeleteTransactionTest < ActiveSupport::TestCase+ include EntriesTestHelper+setup do@user = users(:family_admin)@transaction = transactions(:one)@@ -75,6 +77,19 @@ class Assistant::Function::DeleteTransactionTest < ActiveSupport::TestCaseassert Transaction.exists?(@transaction.id)end+ test "refuses deleting a split whose part is linked as a transfer" do+ parent = create_transaction(account: accounts(:depository), amount: 100, name: "Mortgage")+ part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ transfer = link_split_part_to_loan(part)++ result = @function.call("id" => parent.transaction.id)++ assert_equal false, result[:success]+ assert_equal "split_part_transferred", result[:error]+ assert Entry.exists?(parent.id)+ assert Transfer.exists?(transfer.id)+ end+test "returns delete_aborted when a before_destroy guard aborts the destroy" doEntry.any_instance.stubs(:destroy!).raises(ActiveRecord::RecordNotDestroyed)diff --git a/test/models/entry_split_test.rb b/test/models/entry_split_test.rbindex 625e1d9d68..4bdb8dbac8 100644--- a/test/models/entry_split_test.rb+++ b/test/models/entry_split_test.rb@@ -340,4 +340,60 @@ class EntrySplitTest < ActiveSupport::TestCaseassert_not stale.unsplit_once!assert_not @entry.reload.split_parent?end++ test "unsplit_once! refuses while a part is a confirmed transfer leg" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)++ assert_raises(Entry::SplitPartTransferredError) { @entry.unsplit_once! }+ assert @entry.reload.split_parent?+ assert part.reload.transaction.transfer.present?+ end++ test "resplit! refuses while a part is a confirmed transfer leg" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part)++ assert_raises(Entry::SplitPartTransferredError) do+ @entry.resplit!([ { name: "C", amount: 30 }, { name: "D", amount: 70 } ])+ end+ assert_equal %w[Interest Principal], @entry.reload.child_entries.order(:name).pluck(:name)+ end++ test "unsplit_once! refuses while a part is the receiving leg of a confirmed transfer" do+ income = create_transaction(amount: -100, name: "Refund", account: accounts(:depository))+ part = income.split!([ { name: "A", amount: -60 }, { name: "B", amount: -40 } ]).first+ savings_entry = create_transaction(account: accounts(:investment), amount: 60, name: "Transfer out")+ Transfer.create!(inflow_transaction: part.transaction, outflow_transaction: savings_entry.transaction, status: "confirmed", amount: 60)++ assert_raises(Entry::SplitPartTransferredError) { income.unsplit_once! }+ assert income.reload.split_parent?+ end++ test "a pending transfer suggestion on a part does not block unsplitting" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part, status: "pending")++ assert @entry.unsplit_once!+ assert_not @entry.reload.split_parent?+ end++ test "deleting a split is refused while a part is a confirmed transfer leg" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ transfer = link_split_part_to_loan(part)++ assert_raises(Entry::SplitPartTransferredError) { @entry.destroy_unless_split_part_transferred! }+ assert Entry.exists?(@entry.id)+ assert Transfer.exists?(transfer.id)+ end++ test "deleting a split with only a pending transfer suggestion on a part removes it" do+ part = @entry.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ link_split_part_to_loan(part, status: "pending")++ @entry.destroy_unless_split_part_transferred!++ assert_not Entry.exists?(@entry.id)+ assert_not Entry.exists?(part.id)+ endenddiff --git a/test/models/entry_unsplit_concurrency_test.rb b/test/models/entry_unsplit_concurrency_test.rbnew file mode 100644index 0000000000..3d643464b3--- /dev/null+++ b/test/models/entry_unsplit_concurrency_test.rb@@ -0,0 +1,123 @@+require "test_helper"+require "concurrent"++# Unsplitting or deleting a split while a transfer on one of the parts is+# confirmed or removed must end in a consistent state. The split action must+# either succeed or be refused, and an unlink racing it must succeed, never+# fail with a deadlock. A racing confirm fails with RecordNotFound when the+# split action removed its transfer first, and then leaves the legs alone.+# Real threads on real connections, so this needs real commits.+class EntryUnsplitConcurrencyTest < ActiveSupport::TestCase+ self.use_transactional_tests = false++ setup do+ @family = Family.create!(name: "Unsplit Race", currency: "USD")+ @checking = Account.create!(+ family: @family, name: "Checking", currency: "USD",+ balance: 0, accountable: Depository.new)+ @loan = Account.create!(+ family: @family, name: "Mortgage", currency: "USD",+ balance: 0, accountable: Loan.new)+ end++ teardown do+ account_ids = [ @checking.id, @loan.id ]+ transaction_ids = Entry.where(account_id: account_ids, entryable_type: "Transaction").pluck(:entryable_id)+ Transfer.where(outflow_transaction_id: transaction_ids).or(Transfer.where(inflow_transaction_id: transaction_ids)).delete_all+ Entry.where(account_id: account_ids).where.not(parent_entry_id: nil).delete_all+ Entry.where(account_id: account_ids).delete_all+ Transaction.where(id: transaction_ids).delete_all+ @checking.destroy+ @loan.destroy+ @family.destroy+ end++ test "unsplitting while a part's transfer is confirmed keeps the split or removes the transfer" do+ 5.times do+ parent, transfer = split_with_part_transfer(status: "pending")++ race(split_action: -> { parent.unsplit_once! }, other: -> { transfer.confirm! }, other_may_raise: ActiveRecord::RecordNotFound)++ # Uncached: this thread's query cache still holds the rows read before the race.+ ActiveRecord::Base.uncached do+ if Entry.find(parent.id).split_parent?+ assert Transfer.find(transfer.id).confirmed?, "a split that stays must keep its confirmed transfer"+ else+ assert_not Transfer.exists?(transfer.id), "an unsplit must not leave the transfer behind"+ assert_equal "standard", Transaction.find(transfer.inflow_transaction_id).kind, "a confirm after the unsplit must not change the loan leg"+ end+ end+ end+ end++ test "unsplitting while a part's transfer is removed keeps the split or removes the transfer" do+ 5.times do+ parent, transfer = split_with_part_transfer(status: "pending")+ # Confirming gives the legs transfer kinds, so removing the transfer+ # updates them before it deletes the transfer row.+ transfer.confirm!++ race(split_action: -> { parent.unsplit_once! }, other: -> { transfer.destroy! })++ ActiveRecord::Base.uncached do+ if Transfer.exists?(transfer.id)+ assert Transfer.find(transfer.id).confirmed?+ assert Entry.find(parent.id).split_parent?, "a split must not be removed while its transfer stays"+ end+ end+ end+ end++ test "deleting a split while a part's transfer is confirmed keeps both or removes both" do+ 5.times do+ parent, transfer = split_with_part_transfer(status: "pending")++ race(split_action: -> { parent.destroy_unless_split_part_transferred! }, other: -> { transfer.confirm! }, other_may_raise: ActiveRecord::RecordNotFound)++ ActiveRecord::Base.uncached do+ if Entry.exists?(parent.id)+ assert Transfer.find(transfer.id).confirmed?, "a split that stays must keep its confirmed transfer"+ else+ assert_not Transfer.exists?(transfer.id), "deleting the split must not leave the transfer behind"+ assert_equal "standard", Transaction.find(transfer.inflow_transaction_id).kind, "a confirm after the delete must not change the loan leg"+ end+ end+ end+ end++ private+ def split_with_part_transfer(status:)+ parent = Entry.create!(+ account: @checking, name: "Mortgage payment", date: Date.current,+ amount: 100, currency: "USD", entryable: Transaction.new)+ part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first+ loan_entry = Entry.create!(+ account: @loan, name: "Payment", date: Date.current,+ amount: -60, currency: "USD", entryable: Transaction.new)+ transfer = Transfer.create!(inflow_transaction: loan_entry.transaction, outflow_transaction: part.transaction, status: status, amount: 60)++ [ Entry.find(parent.id), Transfer.find(transfer.id) ]+ end++ # Starts both actions at the same moment. The split action may only+ # succeed or be refused; the other action may only raise other_may_raise.+ def race(split_action:, other:, other_may_raise: nil)+ errors = Concurrent::Array.new+ latch = Concurrent::CountDownLatch.new(2)++ threads = [ [ split_action, Entry::SplitPartTransferredError ], [ other, other_may_raise ] ].map do |action, allowed|+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ latch.count_down+ latch.wait(5)+ action.call+ rescue => e+ errors << e unless allowed && e.is_a?(allowed)+ end+ end+ end+ threads.each(&:join)++ assert_empty errors.map { |e| "#{e.class}: #{e.message}" }+ end+enddiff --git a/test/models/transfer_test.rb b/test/models/transfer_test.rbindex 200b732006..5557455b02 100644--- a/test/models/transfer_test.rb+++ b/test/models/transfer_test.rb@@ -217,6 +217,30 @@ class TransferTest < ActiveSupport::TestCaseassert_equal categories(:income), transfer.outflow_transaction.reload.categoryend+ test "confirm! on a transfer removed in the meantime raises and leaves the legs alone" do+ transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:loan))+ stale = Transfer.find(transfer.id)+ transfer.destroy!++ assert_raises(ActiveRecord::RecordNotFound) { stale.confirm! }+ assert_equal "standard", transfer.inflow_transaction.reload.kind+ assert_equal "standard", transfer.outflow_transaction.reload.kind+ end++ test "destroy! on a copy loaded before a confirm resets the kinds the confirm set" do+ transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:credit_card))+ # The unlink request loads both legs for its permission check.+ stale = Transfer.find(transfer.id)+ stale.from_account+ stale.to_account+ transfer.confirm!++ stale.destroy!++ assert_equal "standard", transfer.inflow_transaction.reload.kind+ assert_equal "standard", transfer.outflow_transaction.reload.kind+ end+test "reject! leaves the kind of a pending transfer's transactions alone" dotransfer = create_pending_transfer(from: accounts(:depository), to: accounts(:credit_card))transfer.outflow_transaction.update!(kind: "one_time")diff --git a/test/support/entries_test_helper.rb b/test/support/entries_test_helper.rbindex a919d60048..171cc3ef29 100644--- a/test/support/entries_test_helper.rb+++ b/test/support/entries_test_helper.rb@@ -34,6 +34,12 @@ module EntriesTestHelperEntry.create! entry_defaults.merge(entry_attributes)end+ # Links a split part to a loan as the outflow leg of a loan payment.+ def link_split_part_to_loan(part, loan_account: accounts(:loan), status: "confirmed")+ loan_entry = create_transaction(account: loan_account, amount: -part.amount, currency: part.currency, name: "Payment")+ Transfer.create!(inflow_transaction: loan_entry.transaction, outflow_transaction: part.transaction, status: status, amount: part.amount.abs)+ end+def create_trade(security, account:, qty:, date:, price: nil, currency: "USD", fee: 0)trade_price = price || Security::Price.find_by!(security: security, date: date).price