The personal finance app for everyone (by everyone)
Ruby
feat(transfers): add common writer condition for auto-matching transfers (#3722)
JulienGourmet2c700c0f91d3
diff --git a/app/controllers/transfer_matches_controller.rb b/app/controllers/transfer_matches_controller.rbindex a306a86ede..43edbcbbc2 100644--- a/app/controllers/transfer_matches_controller.rb+++ b/app/controllers/transfer_matches_controller.rb@@ -3,7 +3,7 @@ class TransferMatchesController < ApplicationControllerdef new@accounts = Current.family.accounts.writable_by(Current.user).visible.alphabetically.where.not(id: @entry.account_id)- @transfer_match_candidates = @entry.transaction.transfer_match_candidates+ @transfer_match_candidates = writable_transfer_match_candidatesenddef create@@ -41,6 +41,20 @@ class TransferMatchesController < ApplicationController@entry = Current.accessible_entries.find(params[:transaction_id])end+ # Family-wide candidates, limited to counterparts in accounts the user can+ # write to (create would reject the others anyway).+ def writable_transfer_match_candidates+ candidates = @entry.transaction.transfer_match_candidates+ counterpart_id = ->(candidate) { @entry.amount.negative? ? candidate.outflow_transaction_id : candidate.inflow_transaction_id }++ writable_counterpart_ids = Entry+ .where(entryable_type: "Transaction", entryable_id: candidates.map(&counterpart_id), account_id: @accounts.map(&:id))+ .pluck(:entryable_id)+ .to_set++ candidates.select { |candidate| writable_counterpart_ids.include?(counterpart_id.call(candidate)) }+ end+def transfer_match_paramsparams.require(:transfer_match).permit(:method, :matched_entry_id, :target_account_id)enddiff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rbindex 692c41b64e..ab8446a2f6 100644--- a/app/controllers/transfers_controller.rb+++ b/app/controllers/transfers_controller.rb@@ -87,13 +87,15 @@ class TransfersController < ApplicationControllerenddef update+ return reject_transfer if rejecting?+outflow_account = @transfer.outflow_transaction.entry.accountreturn unless require_account_permission!(outflow_account, redirect_path: transactions_url)Transfer.transaction doupdate_transfer_statusupdate_transfer_fees_and_amount- update_transfer_details unless transfer_update_params[:status] == "rejected"+ update_transfer_detailsendrespond_to do |format|@@ -122,8 +124,7 @@ class TransfersController < ApplicationControllerenddef destroy- outflow_account = @transfer.outflow_transaction.entry.account- return unless require_account_permission!(outflow_account, redirect_path: transactions_url)+ return unless require_account_permission!(unlink_permission_account, redirect_path: transactions_url)@transfer.destroy!redirect_back_or_to transactions_url, notice: t(".success")@@ -190,16 +191,64 @@ class TransfersController < ApplicationControllerprivatedef set_transfer- # Finds the transfer and ensures the user has access to it+ # Finds the transfer and ensures the user has access to it. Unlinking+ # (reject/destroy) only needs access to one side, so a user can undo a+ # match against an account that is not shared with them. Any other+ # update edits both entries, so it needs access to both sides.accessible_transaction_ids = Current.family.transactions.joins(entry: :account).merge(Account.accessible_by(Current.user)).select(:id)- @transfer = Transfer- .where(id: params[:id])- .where(inflow_transaction_id: accessible_transaction_ids)- .first!+ scope = Transfer.where(id: params[:id])+ inflow_accessible = scope.where(inflow_transaction_id: accessible_transaction_ids)+ outflow_accessible = scope.where(outflow_transaction_id: accessible_transaction_ids)++ accessible = if unlinking?+ inflow_accessible.or(outflow_accessible)+ elsif action_name == "update"+ inflow_accessible.where(outflow_transaction_id: accessible_transaction_ids)+ else+ inflow_accessible+ end++ @transfer = accessible.first!+ end++ def rejecting?+ params.dig(:transfer, :status) == "rejected"+ end++ def unlinking?+ action_name == "destroy" || (action_name == "update" && rejecting?)+ end++ def reject_transfer+ return unless require_account_permission!(unlink_permission_account, redirect_path: transactions_url)++ @transfer.reject!++ respond_to do |format|+ format.html { redirect_back_or_to transactions_url, notice: t(".success") }+ format.turbo_stream+ end+ end++ # Unlinking (reject/destroy) needs write access to one endpoint, plus every+ # account holding a fee transaction, since destroying the transfer deletes+ # those fees. Returns the account to run the permission check against: the+ # first one the user cannot write to, or a writable endpoint.+ def unlink_permission_account+ endpoints = [ @transfer.from_account, @transfer.to_account ].compact+ fee_accounts = Account.where(id: @transfer.fee_transactions.joins(:entry).select("entries.account_id")).to_a+ writable_ids = Current.family.accounts.writable_by(Current.user)+ .where(id: (endpoints + fee_accounts).map(&:id))+ .pluck(:id).to_set++ writable_endpoint = endpoints.find { |account| writable_ids.include?(account.id) }+ return endpoints.first unless writable_endpoint++ fee_accounts.find { |account| !writable_ids.include?(account.id) } || writable_endpointenddef transfer_paramsdiff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rbindex 3c6c56e228..273fd14cee 100644--- a/app/models/family/auto_transfer_matchable.rb+++ b/app/models/family/auto_transfer_matchable.rb@@ -36,7 +36,8 @@ module Family::AutoTransferMatchableoutflow_transaction_id: nil,account_id: nil,include_rejected: true,- restrict_cross_currency_to_linked_accounts: false+ restrict_cross_currency_to_linked_accounts: false,+ require_common_writer: false)date_window = coerce_transfer_match_date_window!(date_window)exchange_rate_tolerance = coerce_transfer_match_exchange_rate_tolerance!(exchange_rate_tolerance)@@ -52,6 +53,7 @@ module Family::AutoTransferMatchableaccount_id:,include_rejected:,restrict_cross_currency_to_linked_accounts:,+ require_common_writer:,lower_exchange_rate_bound: 1 - exchange_rate_tolerance,upper_exchange_rate_bound: 1 + exchange_rate_tolerance}@@ -70,7 +72,10 @@ module Family::AutoTransferMatchableaccount_id: account&.id,include_rejected: false,exchange_rate_tolerance:,- restrict_cross_currency_to_linked_accounts: true+ restrict_cross_currency_to_linked_accounts: true,+ # Only pair accounts that at least one member can write to on both sides, so+ # someone can always confirm or reject the match.+ require_common_writer: true)transaction_ids = candidates_scope.flat_map do |match|[ match.inflow_transaction_id, match.outflow_transaction_id ]@@ -179,6 +184,38 @@ module Family::AutoTransferMatchabletoleranceend+ # A family member who can write to (Account.writable_by) at least one side+ # and to every side that has an owner, so someone can always unlink the+ # match. An owner-less account (owner_id is nullified when its owner is+ # removed from the family) does not block pairing: nobody can write to it,+ # but the member on the other side can still reject the match. When the+ # owner-less side is the outflow, the match can be rejected but not+ # confirmed or edited, as before this condition existed.+ def common_writer_condition_sql+ <<~SQL.squish+ (:require_common_writer = FALSE OR EXISTS (+ SELECT 1 FROM users writers+ WHERE+ writers.family_id = :family_id AND+ (inflow_accounts.owner_id IS NULL OR #{writer_can_write_sql("inflow_accounts")}) AND+ (outflow_accounts.owner_id IS NULL OR #{writer_can_write_sql("outflow_accounts")}) AND+ (#{writer_can_write_sql("inflow_accounts")} OR #{writer_can_write_sql("outflow_accounts")})+ ))+ SQL+ end++ # Mirrors Account.writable_by for the `writers` row: owner or full_control share.+ def writer_can_write_sql(accounts_alias)+ <<~SQL.squish+ (writers.id = #{accounts_alias}.owner_id OR EXISTS (+ SELECT 1 FROM account_shares writer_shares+ WHERE writer_shares.account_id = #{accounts_alias}.id AND+ writer_shares.user_id = writers.id AND+ writer_shares.permission = 'full_control'+ ))+ SQL+ end+# The second UNION branch below (cross-currency, FX-rate-tolerance matching) is a# coincidence guess -- amount x FX-rate within a tolerance band, not an exact amount# match -- and a manual account has no institution behind it confirming money actually@@ -255,7 +292,8 @@ module Family::AutoTransferMatchable(:account_id IS NULL OR inflow_candidates.account_id = :account_id OR outflow_candidates.account_id = :account_id) AND(:inflow_transaction_id IS NULL OR inflow_candidates.entryable_id = :inflow_transaction_id) AND(:outflow_transaction_id IS NULL OR outflow_candidates.entryable_id = :outflow_transaction_id) AND- (:include_rejected = TRUE OR rejected_transfers.id IS NULL)+ (:include_rejected = TRUE OR rejected_transfers.id IS NULL) AND+ #{common_writer_condition_sql}UNION ALLSELECTinflow_candidates.entryable_id AS inflow_transaction_id,@@ -319,7 +357,8 @@ module Family::AutoTransferMatchable(:restrict_cross_currency_to_linked_accounts = FALSE OR(#{linked_account_sql("inflow_accounts")} AND #{linked_account_sql("outflow_accounts")})- )+ ) AND+ #{common_writer_condition_sql}) transfer_match_candidatesORDER BY transfer_match_candidates.match_rank ASC, transfer_match_candidates.date_diff ASCSQLdiff --git a/test/controllers/transfer_matches_controller_test.rb b/test/controllers/transfer_matches_controller_test.rbindex fa277659a5..4d373714f0 100644--- a/test/controllers/transfer_matches_controller_test.rb+++ b/test/controllers/transfer_matches_controller_test.rb@@ -7,6 +7,23 @@ class TransferMatchesControllerTest < ActionDispatch::IntegrationTestsign_in @user = users(:family_admin)end+ test "new only offers candidates from accounts the user can write to" do+ loan = accounts(:loan)+ loan.update!(owner: users(:family_member))+ # Accessible but not writable: candidates must be filtered by write access+ loan.account_shares.create!(user: @user, permission: "read_only")++ outflow_entry = create_transaction(amount: 100, account: accounts(:depository))+ hidden_inflow = create_transaction(amount: -100, account: loan, name: "Hidden member inflow")+ visible_inflow = create_transaction(amount: -100, account: accounts(:investment), name: "Visible own inflow")++ get new_transaction_transfer_match_path(outflow_entry)++ assert_response :success+ assert_select "option[value=?]", visible_inflow.id+ assert_select "option[value=?]", hidden_inflow.id, count: 0+ end+test "matches existing transaction and creates transfer" doinflow_transaction = create_transaction(amount: 100, account: accounts(:depository))outflow_transaction = create_transaction(amount: -100, account: accounts(:investment))diff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rbindex b87575ed1e..97e3ecba6f 100644--- a/test/controllers/transfers_controller_test.rb+++ b/test/controllers/transfers_controller_test.rb@@ -1,6 +1,8 @@require "test_helper"class TransfersControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper+setup dosign_in users(:family_admin)end@@ -667,6 +669,97 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestendend+ test "can reject a match when only the outflow account is accessible" do+ transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)++ assert_difference -> { Transfer.count } => -1, -> { RejectedTransfer.count } => 1 do+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }+ end++ assert_redirected_to transactions_url+ assert_equal "standard", transfer.outflow_transaction.reload.kind+ assert_equal "standard", transfer.inflow_transaction.reload.kind+ end++ test "can reject a match when only the inflow account is accessible" do+ transfer = cross_owner_transfer(outflow_account: member_loan, inflow_account: accounts(:depository))++ assert_difference -> { Transfer.count } => -1, -> { RejectedTransfer.count } => 1 do+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }+ end++ assert_redirected_to transactions_url+ end++ test "can unlink a match when only one side is accessible" do+ transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)++ assert_difference -> { Transfer.count }, -1 do+ delete transfer_url(transfer)+ end+ end++ test "cannot unlink a match from one side when a fee sits in the other account" do+ transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)+ writable_fee = attach_fee(transfer, account: accounts(:depository))+ unwritable_fee = attach_fee(transfer, account: member_loan)++ assert_no_difference -> { Transfer.count } do+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }+ delete transfer_url(transfer)+ end++ assert_equal I18n.t("accounts.not_authorized"), flash[:alert]+ assert Transfer.exists?(transfer.id)+ assert Transaction.exists?(writable_fee.id)+ assert Transaction.exists?(unwritable_fee.id)+ end++ test "can reject a match from one side when its fees sit in a writable account" do+ transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)+ fee = attach_fee(transfer, account: accounts(:depository))++ assert_difference -> { Transfer.count } => -1, -> { RejectedTransfer.count } => 1 do+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }+ end++ assert_not Transaction.exists?(fee.id)+ end++ test "cannot edit a match when only the inflow account is accessible" do+ transfer = cross_owner_transfer(outflow_account: member_loan, inflow_account: accounts(:depository))++ patch transfer_url(transfer), params: { transfer: { status: "confirmed", notes: "Nope" } }++ assert_response :not_found+ assert transfer.reload.pending?+ assert_nil transfer.notes+ end++ test "cannot edit a match when only the outflow account is accessible" do+ transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)+ inflow_amount = transfer.inflow_transaction.entry.amount++ patch transfer_url(transfer), params: { transfer: { status: "confirmed", amount: transfer.amount + 10, notes: "Nope" } }++ assert_response :not_found+ assert transfer.reload.pending?+ assert_nil transfer.notes+ assert_equal inflow_amount, transfer.inflow_transaction.entry.reload.amount+ end++ test "cannot reject a match when neither side is accessible" do+ vehicle = accounts(:vehicle)+ vehicle.update!(owner: users(:family_member))+ transfer = cross_owner_transfer(outflow_account: vehicle, inflow_account: member_loan)++ assert_no_difference -> { Transfer.count } do+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }+ end++ assert_response :not_found+ end+test "mark_as_recurring creates a recurring transfer" dotransfer = transfers(:one)family = users(:family_admin).family@@ -710,4 +803,23 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestendassert_equal I18n.t("recurring_transactions.transfer_feature_disabled"), flash[:alert]end++ private+ # A loan owned by family_member and not shared with family_admin+ def member_loan+ accounts(:loan).tap { |loan| loan.update!(owner: users(:family_member)) }+ end++ def cross_owner_transfer(outflow_account:, inflow_account:)+ outflow = create_transaction(account: outflow_account, amount: 250, kind: "funds_movement")+ inflow = create_transaction(account: inflow_account, amount: -250, kind: "funds_movement")++ Transfer.create!(outflow_transaction: outflow.transaction, inflow_transaction: inflow.transaction, status: "pending")+ end++ def attach_fee(transfer, account:)+ create_transaction(account: account, amount: 5, name: "Transfer fee").transaction.tap do |fee|+ fee.update!(transfer: transfer)+ end+ endenddiff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rbindex d828624d48..52844281cf 100644--- a/test/models/family/auto_transfer_matchable_test.rb+++ b/test/models/family/auto_transfer_matchable_test.rb@@ -512,6 +512,77 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseendend+ test "does not auto-match accounts no single member can write to" do+ # family_admin owns the credit card but has no access to the loan;+ # family_member owns the loan but only has read_only on the card.+ @loan.update!(owner: users(:family_member))++ outflow = create_transaction(date: Date.current, account: @loan, amount: 500)+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500)++ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end++ # Manual matching still sees the pair; the controller scopes it per user.+ candidates = @family.transfer_match_candidates(inflow_transaction_id: inflow.entryable_id)+ assert_equal [ outflow.entryable_id ], candidates.map(&:outflow_transaction_id)+ end++ test "does not auto-match cross-currency accounts no single member can write to" do+ load_exchange_prices+ # Same ownership as above; both linked so only the writer condition blocks the match.+ @loan.update!(owner: users(:family_member))+ link_account!(@loan)+ link_account!(@credit_card)++ outflow = create_transaction(date: Date.current, account: @loan, amount: 1000)+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -1400, currency: "CAD")++ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end++ assert_includes candidate_pairs, [ inflow.entryable_id, outflow.entryable_id ]+ end++ test "auto-matches across owners when a member can write to both accounts" do+ # family_member owns the loan and has full_control on the depository+ @loan.update!(owner: users(:family_member))++ create_transaction(date: Date.current, account: @depository, amount: 500)+ create_transaction(date: Date.current, account: @loan, amount: -500)++ assert_difference -> { Transfer.count }, 1 do+ @family.auto_match_transfers!+ end+ end++ test "auto-matches an owner-less account against one a member can write to" do+ # owner_id is nullified when the owner is removed; update! would reassign one+ @loan.update_column(:owner_id, nil)++ create_transaction(date: Date.current, account: @depository, amount: 500)+ create_transaction(date: Date.current, account: @loan, amount: -500)++ assert_difference -> { Transfer.count }, 1 do+ @family.auto_match_transfers!+ end+ end++ test "does not auto-match two owner-less accounts nobody can write to" do+ @loan.update_column(:owner_id, nil)+ @credit_card.update_column(:owner_id, nil)+ AccountShare.where(account: [ @loan, @credit_card ], permission: "full_control").delete_all++ create_transaction(date: Date.current, account: @credit_card, amount: 500)+ create_transaction(date: Date.current, account: @loan, amount: -500)++ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end+ end+test "does not match transactions outside the 4-day window" docreate_transaction(date: 10.days.ago.to_date, account: @depository, amount: 500)create_transaction(date: Date.current, account: @credit_card, amount: -500)@@ -623,6 +694,7 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert_includes sql, "EXISTS (SELECT 1 FROM account_providers WHERE account_providers.account_id = inflow_accounts.id)"assert_includes sql, "EXISTS (SELECT 1 FROM account_providers WHERE account_providers.account_id = outflow_accounts.id)"assert_includes sql, ":restrict_cross_currency_to_linked_accounts = FALSE"+ assert_equal 2, sql.scan(":require_common_writer = FALSE").sizeend# Regression tests for loan transfer kind assignment bug