The personal finance app for everyone (by everyone)
Ruby
Reject a pending transfer match without reloading the page (#4795)
Yong Cong Sin8982dac33cb9
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex 9ddb811c97..ca21422a76 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -214,6 +214,9 @@ class TransactionsController < ApplicationControllerformat.html { redirect_back_or_to account_path(@entry.account), notice: t(".updated") }format.turbo_stream doin_split_group = helpers.in_split_group?(@entry, params[:grouped])+ # The row draws the "Transfer?" hint, and its cache key records+ # whether it applies, so the hint is worked out as the list does.+ @transfer_hint_transaction_ids = Current.family.transaction_ids_with_transfer_candidates([ @entry.transaction ], user: Current.user)render turbo_stream: [turbo_stream.replace(dom_id(@entry, :header),diff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rbindex 9d4e4f5b46..41bf70ef12 100644--- a/app/controllers/transfers_controller.rb+++ b/app/controllers/transfers_controller.rb@@ -1,6 +1,10 @@class TransfersController < ApplicationControllerinclude StreamExtensions+ # Most rows besides the two legs a rejection redraws in place; past this the+ # page reloads instead, as the stream would carry rows the page may not show.+ MAX_REDRAWN_PAIRED_ROWS = 10+before_action :set_transfer, only: %i[show destroy update update_tags mark_as_recurring]before_action :set_accounts, only: %i[new create]@@ -102,6 +106,7 @@ class TransfersController < ApplicationControllerupdate_investment_contributionend+ @view_ctx = view_ctx_from_refererrespond_to do |format|format.html { redirect_back_or_to transactions_url, notice: t(".success") }format.turbo_stream do@@ -238,14 +243,84 @@ class TransfersController < ApplicationControllerdef reject_transferreturn unless require_account_permission!(unlink_permission_account, redirect_path: transactions_url)- @transfer.reject!+ @view_ctx = view_ctx_from_referer+ # Locked, so a confirmation landing meanwhile cannot change what the+ # rejection undoes after the response was chosen.+ in_place = @transfer.with_lock do+ rejection_redraws_in_place?.tap { @transfer.reject! }+ endrespond_to do |format|format.html { redirect_back_or_to transactions_url, notice: t(".success") }- format.turbo_stream+ format.turbo_stream do+ @redrawn_entries = in_place ? redrawn_entries : []+ if @redrawn_entries.any?+ render :reject+ else+ stream_redirect_to(request.referer.presence || transactions_url)+ end+ endendend+ # The rows a rejection changes: both legs, and any other transaction the+ # "Transfer?" hint now pairs with one of them (a pair touching a transfer+ # is never offered, so destroying it can free one), each drawn with that+ # hint as the list would. Empty, and the page reloads, when the user can+ # no longer see either leg, when a freed row sits inside a split group+ # (it needs the group's context), or when more rows than+ # MAX_REDRAWN_PAIRED_ROWS were freed.+ def redrawn_entries+ leg_ids = [ @transfer.inflow_transaction_id, @transfer.outflow_transaction_id ]+ legs = accessible_transaction_entries(leg_ids)+ return [] if legs.empty?++ @transfer_hint_transaction_ids = Current.family.transfer_hint_pair_ids(legs.map(&:entryable), user: Current.user)+ others = accessible_transaction_entries(@transfer_hint_transaction_ids.to_a - leg_ids)+ return [] if others.size > MAX_REDRAWN_PAIRED_ROWS || others.any? { |entry| entry.parent_entry_id.present? }++ legs + others+ end++ def accessible_transaction_entries(transaction_ids)+ return [] if transaction_ids.empty?++ Current.accessible_entries.where(entryable_type: "Transaction", entryable_id: transaction_ids).includes(:entryable).to_a+ end++ # Whether rejecting changes nothing on the page but the two legs' rows, so+ # those rows can be redrawn in place. Not when the transfer was confirmed+ # (its legs go back to income and spending, moving the page's totals), has+ # fees (rejecting deletes them), or has a leg drawn inside a split group+ # (its row needs the group's context). Nor when both legs are on a list+ # outside an account page: such a list draws a transfer once, by its+ # outflow (EntriesHelper#entries_by_date), so the inflow has no row to+ # redraw and its date group's count would be off.+ def rejection_redraws_in_place?+ legs = Entry.where(entryable_type: "Transaction", entryable_id: [ @transfer.inflow_transaction_id, @transfer.outflow_transaction_id ])++ @transfer.pending? &&+ @transfer.fee_transactions.none? &&+ !legs.where.not(parent_entry_id: nil).exists? &&+ (@view_ctx == "account" || legs.merge(Current.accessible_entries).count < 2)+ end++ # Rows are drawn the way the page that asked draws them: an account page+ # signs each leg for its own account, every other list shows a transfer as+ # +/-. Taken from the page the request came from, the account page of one+ # of the legs, rather than from a client flag, so a stale link or a row+ # another response redrew cannot claim a view the page does not have.+ # Without a Referer it is the global list, which reloads after a rejection.+ def view_ctx_from_referer+ path = URI.parse(request.referer.to_s).path+ return "global" if path.blank?++ leg_account_ids = Entry.where(entryable_type: "Transaction", entryable_id: [ @transfer.inflow_transaction_id, @transfer.outflow_transaction_id ]).pluck(:account_id)+ leg_account_ids.any? { |id| path == account_path(id) } ? "account" : "global"+ rescue URI::InvalidURIError+ "global"+ 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: thediff --git a/app/helpers/transactions_helper.rb b/app/helpers/transactions_helper.rbindex 4ec21a1fb3..095dade75f 100644--- a/app/helpers/transactions_helper.rb+++ b/app/helpers/transactions_helper.rb@@ -123,6 +123,8 @@ module TransactionsHelperview_ctx,in_split_group,split_parent,+ # The "Transfer?" hint is drawn inside the cached row.+ @transfer_hint_transaction_ids&.include?(transaction.id) || false,can_annotate_account?(entry.account),counterpart.present? && @accessible_account_ids&.include?(counterpart.id),Setting.brand_fetch_logo_size,diff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rbindex 1d88ab5e70..30cdea60b6 100644--- a/app/models/family/auto_transfer_matchable.rb+++ b/app/models/family/auto_transfer_matchable.rb@@ -85,6 +85,17 @@ module Family::AutoTransferMatchableendend+ # Both sides of every pair the "Transfer?" hint offers for any of+ # `transactions`: rows that show the hint once these transactions are free+ # to pair, such as after a match between them was rejected.+ #+ # @return [Set<String>] transaction ids, including ones outside `transactions`+ def transfer_hint_pair_ids(transactions, user:)+ transfer_hint_candidates(transactions, user:).each_with_object(Set.new) do |candidate, ids|+ ids << candidate.inflow_transaction_id << candidate.outflow_transaction_id+ end+ end+# "Not a transfer" on a hint: rejects every pair the hint offered for this# transaction, the same record a rejected auto-match leaves behind, so neither# the hint nor the automatic matcher suggests them again. The manual dialogdiff --git a/app/views/transactions/_transfer_match.html.erb b/app/views/transactions/_transfer_match.html.erbindex eb88b24eca..fc48702d02 100644--- a/app/views/transactions/_transfer_match.html.erb+++ b/app/views/transactions/_transfer_match.html.erb@@ -73,7 +73,6 @@variant: :icon, size: :sm, icon: "x",href: transfer_path(transaction.transfer, transfer: { status: "rejected" }),method: :patch,- data: { turbo: false },title: t("transactions.transfer_match.reject_match"),aria: { label: t("transactions.transfer_match.reject_match") }) %>diff --git a/app/views/transfers/reject.turbo_stream.erb b/app/views/transfers/reject.turbo_stream.erbnew file mode 100644index 0000000000..10b517b055--- /dev/null+++ b/app/views/transfers/reject.turbo_stream.erb@@ -0,0 +1,10 @@+<%# The rows the rejection changed (TransfersController#redrawn_entries): the+ match's legs, loaded after it was destroyed (the transfer's own legs still+ hold it in memory and would draw its pill again), and any row the+ "Transfer?" hint now pairs with them. Each row holds its category menus and+ match controls, so redrawing the row is enough. Rows are drawn in the+ page's view (an account page signs a transfer's amount, other lists show+ +/-). %>+<% @redrawn_entries.each do |entry| %>+ <%= turbo_stream.replace entry, partial: "entries/entry", locals: { entry: entry, view_ctx: @view_ctx } %>+<% end %>diff --git a/app/views/transfers/update.turbo_stream.erb b/app/views/transfers/update.turbo_stream.erbindex 929a63ab5d..2a78f4260d 100644--- a/app/views/transfers/update.turbo_stream.erb+++ b/app/views/transfers/update.turbo_stream.erb@@ -1,6 +1,10 @@<% unless @transfer.destroyed? %>- <%= turbo_stream.replace @transfer.inflow_transaction.entry %>- <%= turbo_stream.replace @transfer.outflow_transaction.entry %>+ <%= turbo_stream.replace @transfer.inflow_transaction.entry,+ partial: "entries/entry",+ locals: { entry: @transfer.inflow_transaction.entry, view_ctx: @view_ctx } %>+ <%= turbo_stream.replace @transfer.outflow_transaction.entry,+ partial: "entries/entry",+ locals: { entry: @transfer.outflow_transaction.entry, view_ctx: @view_ctx } %><%= turbo_stream.replace dom_id(@transfer.inflow_transaction, "category_menu_mobile"),partial: "transactions/transaction_category",diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex 31b3664979..f367071311 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -516,6 +516,17 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTestassert_equal 2.days.ago.to_date, @entry.reload.dateend+ test "editing a transaction that pairs with another redraws its row with the transfer hint" do+ outflow = accounts(:depository).entries.create!(name: "To card", date: 1.day.ago.to_date, amount: 75, currency: "USD", entryable: Transaction.new)+ accounts(:credit_card).entries.create!(name: "From checking", date: 1.day.ago.to_date, amount: -75, currency: "USD", entryable: Transaction.new)++ patch transaction_url(outflow), params: { entry: { notes: "Card payment", entryable_type: "Transaction" } }, as: :turbo_stream++ assert_response :success+ assert_select "turbo-stream[action=replace][target=?]", dom_id(outflow)+ assert_select "##{dom_id(outflow.entryable, :transfer_hint)}"+ end+test "name_suggestions returns matching past transaction names with their usual category" doget name_suggestions_transactions_url(q: "Starbucks"), as: :turbo_streamdiff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rbindex 1dc48cbffe..c9524795f8 100644--- a/test/controllers/transfers_controller_test.rb+++ b/test/controllers/transfers_controller_test.rb@@ -731,6 +731,199 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestendend+ test "rejecting a pending match from an account page redraws both rows in place" do+ transfer = transfers(:one)+ assert transfer.pending?, "precondition: the fixture is a pending match"+ inflow_entry = transfer.inflow_transaction.entry+ outflow_entry = transfer.outflow_transaction.entry++ assert_difference -> { Transfer.count } => -1, -> { RejectedTransfer.count } => 1 do+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }+ end++ assert_response :success+ assert_equal "text/vnd.turbo-stream.html", response.media_type+ assert_select "turbo-stream[action=replace][target=?]", dom_id(inflow_entry)+ assert_select "turbo-stream[action=replace][target=?]", dom_id(outflow_entry)+ assert_select "turbo-stream[action=redirect]", count: 0+ assert_no_match transfer_path(transfer), response.body, "the redrawn rows still offer the rejected match"+ end++ test "rejecting a pending match redraws only the rows the user can see" do+ transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)++ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream++ assert_response :success+ assert_select "turbo-stream[action=replace][target=?]", dom_id(transfer.outflow_transaction.entry)+ assert_select "turbo-stream[target=?]", dom_id(transfer.inflow_transaction.entry), count: 0+ end++ test "rejecting a pending match with fees reloads the page, as the fees go with it" do+ transfer = transfers(:one)+ attach_fee(transfer, account: accounts(:depository))++ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => transactions_url }++ assert_select "turbo-stream[action=redirect][target=?]", transactions_url+ end++ test "rejecting a pending match with a leg in a split group reloads the page, which draws the group" do+ transfer = transfers(:one)+ outflow_entry = transfer.outflow_transaction.entry+ parent = create_transaction(account: outflow_entry.account, amount: 250, name: "Split parent")+ outflow_entry.update_columns(parent_entry_id: parent.id)++ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => transactions_url }++ assert_select "turbo-stream[action=redirect][target=?]", transactions_url+ end++ test "a redrawn leg that still pairs with another transaction offers the transfer hint" do+ transfer = transfers(:one)+ inflow_entry = transfer.inflow_transaction.entry+ create_transaction(account: accounts(:depository), amount: -inflow_entry.amount, date: inflow_entry.date, name: "Another payment")++ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,++ headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }++ assert_select "turbo-stream[action=replace][target=?]", dom_id(inflow_entry)+ assert_select "##{dom_id(transfer.inflow_transaction, :transfer_hint)}"+ end++ # A pair touching a transfer is never offered, so destroying the match can+ # free another visible row to pair with one of its legs.+ test "a row the rejection frees to pair with a leg is redrawn with the transfer hint" do+ transfer = transfers(:one)+ inflow_entry = transfer.inflow_transaction.entry+ other = create_transaction(account: accounts(:depository), amount: -inflow_entry.amount, date: inflow_entry.date, name: "Another payment")++ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,++ headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }++ assert_select "turbo-stream[action=replace][target=?]", dom_id(other)+ assert_select "##{dom_id(other.transaction, :transfer_hint)}"+ end++ test "a rejection freeing a row inside a split group to pair reloads the page, which draws the group" do+ transfer = transfers(:one)+ inflow_entry = transfer.inflow_transaction.entry+ other = create_transaction(account: accounts(:depository), amount: -inflow_entry.amount, date: inflow_entry.date, name: "Another payment")+ parent = create_transaction(account: accounts(:depository), amount: 500, name: "Split parent")+ other.update_columns(parent_entry_id: parent.id)++ account_page = account_url(transfer.outflow_transaction.entry.account)+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => account_page }++ assert_select "turbo-stream[action=redirect][target=?]", account_page+ end++ test "a rejection freeing more rows than the bound to pair reloads the page" do+ transfer = transfers(:one)+ inflow_entry = transfer.inflow_transaction.entry+ (TransfersController::MAX_REDRAWN_PAIRED_ROWS + 1).times do |i|+ create_transaction(account: accounts(:depository), amount: -inflow_entry.amount, date: inflow_entry.date, name: "Candidate #{i}")+ end++ account_page = account_url(transfer.outflow_transaction.entry.account)+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => account_page }++ assert_select "turbo-stream[action=redirect][target=?]", account_page+ end++ test "a rejection leaving no row the user can see reloads the page" do+ transfer = transfers(:one)+ TransfersController.any_instance.stubs(:accessible_transaction_entries).returns([])++ account_page = account_url(transfer.outflow_transaction.entry.account)+ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => account_page }++ assert_select "turbo-stream[action=redirect][target=?]", account_page+ end++ # The transactions list draws a transfer once, by its outflow, so the+ # inflow has no row there to redraw.+ test "rejecting a pending match whose legs are both on the transactions list reloads the page" do+ transfer = transfers(:one)++ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => transactions_url }++ assert_select "turbo-stream[action=redirect][target=?]", transactions_url+ assert_not Transfer.exists?(transfer.id)+ end++ test "rows redrawn on an account page keep the account view's signed amounts" do+ transfer = transfers(:one)+ transfer.outflow_transaction.update_columns(kind: "funds_movement")++ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,++ headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }++ assert_select "turbo-stream[action=replace][target=?]", dom_id(transfer.outflow_transaction.entry)+ assert_no_match "+/-", response.body+ end++ test "an account page's reject button carries no view of its own" do+ transfer = transfers(:one)++ get account_url(transfer.outflow_transaction.entry.account)++ assert_select "##{dom_id(transfer.outflow_transaction, :transfer_match)} form[action=?]",+ transfer_path(transfer, transfer: { status: "rejected" })+ end++ # The page a request comes from decides the view, so a client flag cannot+ # claim the account view on the transactions list.+ test "a view_ctx param does not make the transactions list redraw a rejection in place" do+ transfer = transfers(:one)++ patch transfer_url(transfer, view_ctx: "account"), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => transactions_url }++ assert_select "turbo-stream[action=redirect][target=?]", transactions_url+ end++ test "editing a pending transfer on an account page redraws its rows in the account view" do+ transfer = transfers(:one)+ transfer.outflow_transaction.update_columns(kind: "funds_movement")++ patch transfer_url(transfer), params: { transfer: { notes: "Rent" } }, as: :turbo_stream,+ headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }++ assert_select "turbo-stream[action=replace][target=?]", dom_id(transfer.outflow_transaction.entry)+ assert_no_match "+/-", response.body+ end++ test "editing a pending transfer on the transactions list redraws its rows in the list's view" do+ transfer = transfers(:one)+ transfer.outflow_transaction.update_columns(kind: "funds_movement")++ patch transfer_url(transfer), params: { transfer: { notes: "Rent" } }, as: :turbo_stream,+ headers: { "Referer" => transactions_url }++ assert_select "turbo-stream[action=replace][target=?]", dom_id(transfer.outflow_transaction.entry)+ assert_match "+/-", response.body+ end++ test "rejecting a confirmed transfer reloads the page, whose totals it moves" do+ transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan, status: "confirmed")++ patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,+ headers: { "Referer" => transactions_url }++ assert_select "turbo-stream[action=redirect][target=?]", transactions_url+ end+test "can reject a match when only the outflow account is accessible" do# Confirmed, so the legs carry transfer kinds that rejecting must resettransfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan, status: "confirmed")diff --git a/test/views/transactions/transaction_row_cache_test.rb b/test/views/transactions/transaction_row_cache_test.rbindex a3778f039f..9f02024f11 100644--- a/test/views/transactions/transaction_row_cache_test.rb+++ b/test/views/transactions/transaction_row_cache_test.rb@@ -126,6 +126,14 @@ class Transactions::TransactionRowCacheTest < ActionView::TestCaseassert_includes row_key, TransactionsHelper::TRANSACTION_ROW_SOURCES_DIGESTend+ test "a row cached with a transfer hint is drawn without it once the hint no longer applies" do+ @transfer_hint_transaction_ids = Set[@transaction.id]+ assert_includes render_row, dom_id(@transaction, :transfer_hint)++ @transfer_hint_transaction_ids = Set.new+ assert_not_includes render_row, dom_id(@transaction, :transfer_hint)+ end+test "the key changes with the BUILD_COMMIT_SHA of the deployed image" dobase = row_key