Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Point unmatched transfers to the matcher and show account logos in it (#4168)

Andrei Shkarinbcba93d25e70
diff --git a/app/components/DS/select.html.erb b/app/components/DS/select.html.erb
index 547eb4b528..420bdff327 100644
--- a/app/components/DS/select.html.erb
+++ b/app/components/DS/select.html.erb
@@ -4,13 +4,15 @@
<div class="form-field <%= options[:container_class] %>">
<div class="form-field__body">
<%= form.label method, options[:label], class: "form-field__label", id: label_id if options[:label].present? %>
- <%= form.hidden_field method,
- value: @selected_value,
- data: {
- "form-dropdown-target": "input",
- "auto-submit-target": "auto",
- **(options.dig(:html_options, :data) || {})
- } %>
+ <% unless disabled? %>
+ <%= form.hidden_field method,
+ value: @selected_value,
+ data: {
+ "form-dropdown-target": "input",
+ "auto-submit-target": "auto",
+ **(options.dig(:html_options, :data) || {})
+ } %>
+ <% end %>
<%# `aria-expanded` reflects MENU open/closed state — managed by the
select controller's openMenu/close. Init as "false"; previously
this incorrectly mirrored whether a value was selected.
@@ -22,13 +24,21 @@
<button type="button"
id="<%= trigger_id %>"
class="form-field__input w-full"
+ <%= "disabled" if disabled? %>
data-select-target="button"
data-action="click->select#toggle focus->select#handleButtonFocus"
aria-haspopup="listbox"
aria-expanded="false"
tabindex="0"
<%= tag.attributes(aria: { labelledby: "#{label_id} #{trigger_id}" }) if options[:label].present? %>>
- <%= selected_item&.dig(:label) || @placeholder %>
+ <% if trigger_logo? %>
+ <span class="flex items-center gap-2 min-w-0">
+ <%= logo_markup(selected_item) %>
+ <span class="truncate"><%= selected_item[:label] %></span>
+ </span>
+ <% else %>
+ <%= selected_item&.dig(:label) || @placeholder %>
+ <% end %>
</button>
</div>
</div>
@@ -76,20 +86,7 @@
<%= item[:label] %>
<% when :logo %>
- <% unless item[:value].nil? %>
- <% if logo_for(item) %>
- <%= image_tag logo_for(item),
- class: "w-6 h-6 rounded-full border border-secondary",
- loading: "lazy" %>
- <% else %>
- <%= render DS::FilledIcon.new(
- variant: :text,
- text: item[:label],
- size: "sm",
- rounded: true
- ) %>
- <% end %>
- <% end %>
+ <%= logo_markup(item) unless item[:value].nil? %>
<%= item[:label] %>
<% when :badge %>
diff --git a/app/components/DS/select.rb b/app/components/DS/select.rb
index a5b1384022..0968d13ea6 100644
--- a/app/components/DS/select.rb
+++ b/app/components/DS/select.rb
@@ -73,6 +73,31 @@ module DS
obj&.respond_to?(:logo_url) && obj.logo_url.present? ? Setting.transform_brand_fetch_url(obj.logo_url) : nil
end
+ # The logo (or lettermark) shown before an item's label in the :logo
+ # variant, both in the menu and on the closed trigger. select_controller.js
+ # copies the [data-select-logo] element onto the trigger when an option is
+ # picked.
+ def logo_markup(item)
+ url = logo_for(item)
+ content = if url
+ helpers.image_tag(url, class: "w-6 h-6 rounded-full border border-secondary", loading: "lazy")
+ else
+ render(DS::FilledIcon.new(variant: :text, text: item[:label], size: "sm", rounded: true))
+ end
+
+ tag.span(content, class: "shrink-0", data: { select_logo: true })
+ end
+
+ # A disabled select shows its value like a disabled native <select>: the
+ # trigger does not open and no field is submitted.
+ def disabled?
+ options[:disabled].present?
+ end
+
+ def trigger_logo?
+ variant == :logo && selected_item.present? && !selected_item[:value].nil?
+ end
+
# Returns true if the item represents a child/subcategory of another item
# in the list (i.e. has a parent). Used to visually indent hierarchical
# items such as categories with subcategories.
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index 0b6dbb3e75..18b1538f27 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -155,6 +155,8 @@ class AccountsController < ApplicationController
).call
end
+ @transfer_hint_transaction_ids = Current.family.transaction_ids_with_transfer_candidates(transactions, user: Current.user)
+
entry_ids = @entries.map(&:id)
@split_parent_entry_ids = Entry.split_parent_ids_among(entry_ids)
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb
index f1e5976435..b2ae330d0f 100644
--- a/app/controllers/transactions_controller.rb
+++ b/app/controllers/transactions_controller.rb
@@ -52,6 +52,8 @@ class TransactionsController < ApplicationController
@pagy, @transactions = pagy(base_scope, limit: safe_per_page(stored_params["per_page"]))
Transaction::ActivitySecurityPreloader.new(@transactions).preload
+ @transfer_hint_transaction_ids = Current.family.transaction_ids_with_transfer_candidates(@transactions, user: Current.user)
+
# Preload split parent data
entry_ids = @transactions.map { |t| t.entry.id }
diff --git a/app/controllers/transfer_matches_controller.rb b/app/controllers/transfer_matches_controller.rb
index b56a36c4e5..952d7e967b 100644
--- a/app/controllers/transfer_matches_controller.rb
+++ b/app/controllers/transfer_matches_controller.rb
@@ -2,8 +2,10 @@ class TransferMatchesController < ApplicationController
before_action :set_entry
def new
+ # Preloaded for the logo selects, which call Account#logo_url per option.
@accounts = Current.family.accounts.writable_by(Current.user).visible.alphabetically.where.not(id: @entry.account_id)
- @transfer_match_candidates = writable_transfer_match_candidates
+ .includes(:account_providers, logo_attachment: :blob)
+ @candidate_entries = writable_candidate_entries
end
def create
@@ -23,23 +25,37 @@ class TransferMatchesController < ApplicationController
redirect_back_or_to transactions_path, notice: t(".success")
end
+ # "Not a transfer" on the list's transfer hint.
+ def destroy
+ return unless require_account_permission!(@entry.account, redirect_path: transactions_path)
+
+ Current.family.dismiss_transfer_hint!(@entry.transaction, user: Current.user)
+
+ respond_to do |format|
+ format.turbo_stream { render turbo_stream: turbo_stream.remove(helpers.dom_id(@entry.transaction, :transfer_hint)) }
+ format.html { redirect_back_or_to transactions_path }
+ end
+ end
+
private
def set_entry
@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 }
+ # Counterpart entries of the family-wide candidates, in candidate order and
+ # limited to accounts the user can write to (create would reject the others
+ # anyway).
+ def writable_candidate_entries
+ counterpart_ids = @entry.transaction.transfer_match_candidates.map do |candidate|
+ @entry.amount.negative? ? candidate.outflow_transaction_id : candidate.inflow_transaction_id
+ end
- writable_counterpart_ids = Entry
- .where(entryable_type: "Transaction", entryable_id: candidates.map(&counterpart_id), account_id: @accounts.map(&:id))
- .pluck(:entryable_id)
- .to_set
+ entries_by_transaction_id = Entry
+ .where(entryable_type: "Transaction", entryable_id: counterpart_ids, account_id: @accounts.map(&:id))
+ .includes(account: [ :account_providers, { logo_attachment: :blob } ])
+ .index_by(&:entryable_id)
- candidates.select { |candidate| writable_counterpart_ids.include?(counterpart_id.call(candidate)) }
+ counterpart_ids.filter_map { |id| entries_by_transaction_id[id] }
end
def transfer_match_params
diff --git a/app/javascript/controllers/select_controller.js b/app/javascript/controllers/select_controller.js
index 3d79a1f027..4d729e2f4a 100644
--- a/app/javascript/controllers/select_controller.js
+++ b/app/javascript/controllers/select_controller.js
@@ -128,12 +128,30 @@ export default class extends Controller {
setTimeout(() => { if (!this.isOpen && this.hasMenuTarget) this.menuTarget.classList.add("hidden") }, 150)
}
+ // Mirrors the closed trigger markup in select.html.erb: options of the :logo
+ // variant carry a [data-select-logo] element that is shown next to the label.
+ renderTrigger(selectedElement, label) {
+ const logo = selectedElement.querySelector("[data-select-logo]")
+ if (!logo) {
+ this.buttonTarget.textContent = label
+ return
+ }
+
+ const wrapper = document.createElement("span")
+ wrapper.className = "flex items-center gap-2 min-w-0"
+ const text = document.createElement("span")
+ text.className = "truncate"
+ text.textContent = label
+ wrapper.append(logo.cloneNode(true), text)
+ this.buttonTarget.replaceChildren(wrapper)
+ }
+
select(event) {
const selectedElement = event.currentTarget
const value = selectedElement.dataset.value
const label = selectedElement.dataset.filterName || selectedElement.textContent.trim()
- this.buttonTarget.textContent = label
+ this.renderTrigger(selectedElement, label)
if (this.hasInputTarget) {
this.inputTarget.value = value
this.inputTarget.dispatchEvent(new Event("change", { bubbles: true }))
diff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rb
index 0db2215e8a..fd99753c9a 100644
--- a/app/models/family/auto_transfer_matchable.rb
+++ b/app/models/family/auto_transfer_matchable.rb
@@ -15,6 +15,13 @@ module Family::AutoTransferMatchable
# date_window: 30 vs. 4 widening that dialog already applies.
MANUAL_MATCH_EXCHANGE_RATE_TOLERANCE = 0.1
+ # The "Transfer?" hint in the transaction list is unprompted, so it is much
+ # narrower than the dialog it opens: across a real multi-currency history,
+ # the dialog's 30 days / 10% flagged mostly coincidental small purchases,
+ # while 2 days / 3% kept mainly genuine currency conversions.
+ TRANSFER_HINT_DATE_WINDOW = 2
+ TRANSFER_HINT_EXCHANGE_RATE_TOLERANCE = 0.03
+
# Read at call time rather than frozen into a constant at boot, so a bad value falls back
# instead of raising inside every sync: Family::Syncer and Account::Syncer both call
# auto_match_transfers! without a tolerance of their own.
@@ -35,6 +42,7 @@ module Family::AutoTransferMatchable
inflow_transaction_id: nil,
outflow_transaction_id: nil,
account_id: nil,
+ transaction_ids: nil,
include_rejected: true,
restrict_cross_currency_to_linked_accounts: false,
require_common_writer: false
@@ -51,6 +59,9 @@ module Family::AutoTransferMatchable
inflow_transaction_id:,
outflow_transaction_id:,
account_id:,
+ filter_transaction_ids: !transaction_ids.nil?,
+ # IN () is invalid SQL, so an empty list binds a NULL that matches nothing.
+ transaction_ids: transaction_ids.presence || [ nil ],
include_rejected:,
restrict_cross_currency_to_linked_accounts:,
require_common_writer:,
@@ -60,6 +71,33 @@ module Family::AutoTransferMatchable
])
end
+ # Which of `transactions` have a likely transfer counterpart, so the
+ # transaction list can point the user to the "match as transfer" dialog.
+ #
+ # @return [Set<String>] ids of the given transactions that have a candidate
+ def transaction_ids_with_transfer_candidates(transactions, user:)
+ page_ids = transactions.map(&:id).to_set
+
+ transfer_hint_candidates(transactions, user:).each_with_object(Set.new) do |candidate, ids|
+ [ candidate.inflow_transaction_id, candidate.outflow_transaction_id ].each { |id| ids << id if page_ids.include?(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 dialog
+ # still lists them.
+ def dismiss_transfer_hint!(transaction, user:)
+ RejectedTransfer.transaction do
+ transfer_hint_candidates([ transaction ], user:).each do |candidate|
+ RejectedTransfer.find_or_create_by!(
+ inflow_transaction_id: candidate.inflow_transaction_id,
+ outflow_transaction_id: candidate.outflow_transaction_id
+ )
+ end
+ end
+ end
+
def auto_match_transfers!(account: nil, exchange_rate_tolerance: Family::AutoTransferMatchable.exchange_rate_tolerance)
return if auto_match_transfers_disabled?
@@ -101,6 +139,38 @@ module Family::AutoTransferMatchable
end
private
+ # The hint's candidate pairs for `transactions`: the narrower hint window and
+ # tolerance, no rejected pairs, both legs in the same category (or both
+ # uncategorized, since a categorized purchase against an income is not a
+ # transfer), and `user` able to write to both accounts
+ # (TransferMatchesController#create requires that).
+ def transfer_hint_candidates(transactions, user:)
+ unmatched_ids = transactions.reject { |transaction| transaction.transfer? || transaction.transfer.present? }.map(&:id)
+ return [] if unmatched_ids.empty?
+
+ candidates = transfer_match_candidates(
+ date_window: TRANSFER_HINT_DATE_WINDOW,
+ exchange_rate_tolerance: TRANSFER_HINT_EXCHANGE_RATE_TOLERANCE,
+ transaction_ids: unmatched_ids,
+ include_rejected: false
+ ).to_a
+ return [] if candidates.empty?
+
+ leg_ids = candidates.flat_map { |candidate| [ candidate.inflow_transaction_id, candidate.outflow_transaction_id ] }
+ account_ids = Entry.where(entryable_type: "Transaction", entryable_id: leg_ids).pluck(:entryable_id, :account_id).to_h
+ category_ids = Transaction.where(id: leg_ids).pluck(:id, :category_id).to_h
+ writable_account_ids = accounts.writable_by(user).pluck(:id).to_set
+
+ candidates.select do |candidate|
+ inflow_id = candidate.inflow_transaction_id
+ outflow_id = candidate.outflow_transaction_id
+
+ category_ids[inflow_id] == category_ids[outflow_id] &&
+ writable_account_ids.include?(account_ids[inflow_id]) &&
+ writable_account_ids.include?(account_ids[outflow_id])
+ end
+ end
+
# Create the transfer for a matched candidate, tolerating a concurrent sync
# that already inserted the same pair.
#
@@ -272,6 +342,7 @@ 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
+ (:filter_transaction_ids = FALSE OR inflow_candidates.entryable_id IN (:transaction_ids) OR outflow_candidates.entryable_id IN (:transaction_ids)) AND
(:include_rejected = TRUE OR rejected_transfers.id IS NULL) AND
#{common_writer_condition_sql}
UNION ALL
@@ -355,6 +426,7 @@ module Family::AutoTransferMatchable
BETWEEN :lower_exchange_rate_bound AND :upper_exchange_rate_bound 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
+ (:filter_transaction_ids = FALSE OR inflow_candidates.entryable_id IN (:transaction_ids) OR outflow_candidates.entryable_id IN (:transaction_ids)) AND
(:include_rejected = TRUE OR rejected_transfers.id IS NULL) AND
(
:restrict_cross_currency_to_linked_accounts = FALSE OR
diff --git a/app/models/transaction/transferable.rb b/app/models/transaction/transferable.rb
index 0060e50b1a..0441a09b55 100644
--- a/app/models/transaction/transferable.rb
+++ b/app/models/transaction/transferable.rb
@@ -31,15 +31,39 @@ module Transaction::Transferable
family_matches_scope(date_window: date_window, exchange_rate_tolerance: exchange_rate_tolerance, outflow_transaction_id: self.id)
end
- candidates_scope.map do |match|
+ candidates = candidates_scope.map do |match|
Transfer.new(
inflow_transaction_id: match.inflow_transaction_id,
outflow_transaction_id: match.outflow_transaction_id,
)
end
+
+ likeliest_first(candidates)
end
private
+ # A pair the user already rejected goes last, and a counterpart in this
+ # transaction's category goes first (and is preselected in the dialog), so
+ # the dialog a list hint opens defaults to the kind of pair the hint found;
+ # otherwise the query's order (exact amounts, then nearest date) stays.
+ def likeliest_first(candidates)
+ counterpart_id = ->(candidate) { candidate.inflow_transaction_id == id ? candidate.outflow_transaction_id : candidate.inflow_transaction_id }
+ category_ids = Transaction.where(id: candidates.map(&counterpart_id)).pluck(:id, :category_id).to_h
+ rejected_counterpart_ids = RejectedTransfer.where(inflow_transaction_id: id).pluck(:outflow_transaction_id) +
+ RejectedTransfer.where(outflow_transaction_id: id).pluck(:inflow_transaction_id)
+
+ candidates.each_with_index
+ .sort_by do |candidate, index|
+ counterpart = counterpart_id.call(candidate)
+ [
+ rejected_counterpart_ids.include?(counterpart) ? 1 : 0,
+ category_ids[counterpart] == category_id ? 0 : 1,
+ index
+ ]
+ end
+ .map(&:first)
+ end
+
def family_matches_scope(date_window:, **filters)
self.entry.account.family.transfer_match_candidates(date_window: date_window, **filters)
end
diff --git a/app/views/transactions/_transaction.html.erb b/app/views/transactions/_transaction.html.erb
index f68324e83f..3fbdacccd6 100644
--- a/app/views/transactions/_transaction.html.erb
+++ b/app/views/transactions/_transaction.html.erb
@@ -206,6 +206,26 @@
<div class="<%= class_names("flex justify-end min-w-0", transaction.transfer&.pending? ? "flex-col-reverse items-end gap-1 lg:flex-row lg:flex-wrap lg:items-center lg:gap-2" : "items-center gap-2 lg:gap-4") %>">
<% if transaction.transfer.present? %>
<%= render "transactions/transfer_match", transaction: transaction %>
+ <% elsif @transfer_hint_transaction_ids&.include?(transaction.id) %>
+ <span id="<%= dom_id(transaction, :transfer_hint) %>" class="flex shrink-0 items-center gap-1">
+ <%= link_to new_transaction_transfer_match_path(entry),
+ class: "hover:opacity-80",
+ data: { turbo_frame: "modal" } do %>
+ <%= render DS::Pill.new(
+ label: t("transactions.transaction.transfer_hint"),
+ tone: :info,
+ marker: false,
+ icon: "refresh-cw",
+ title: t("transactions.transaction.transfer_hint_tooltip")
+ ) %>
+ <% end %>
+ <%= button_to transaction_transfer_match_path(entry),
+ method: :delete,
+ class: "text-subdued hover:text-primary flex items-center justify-center cursor-pointer",
+ title: t("transactions.transaction.transfer_hint_dismiss") do %>
+ <%= icon "x", size: "sm", color: "current" %>
+ <% end %>
+ </span>
<% end %>
<div class="shrink-0 ml-auto flex items-center justify-end gap-2 <%= "opacity-50" if entry.excluded %>">
diff --git a/app/views/transfer_matches/_matching_fields.html.erb b/app/views/transfer_matches/_matching_fields.html.erb
index 46c6e1bd45..48d1d4f4ca 100644
--- a/app/views/transfer_matches/_matching_fields.html.erb
+++ b/app/views/transfer_matches/_matching_fields.html.erb
@@ -1,5 +1,7 @@
<%# locals: (form:, entry:, candidates:, accounts:) %>
+<% account_items = accounts.map { |account| { value: account.id, label: account.name, object: account } } %>
+
<% if candidates.any? %>
<div data-controller="transfer-match" class="space-y-2">
<p class="text-sm text-secondary">
@@ -15,17 +17,26 @@
data: { action: "change->transfer-match#update" } %>
<div data-transfer-match-target="existingSelect">
- <%= form.select :matched_entry_id,
- candidates.map { |entry|
- [entry_name_detailed(entry), entry.id]
- },
- { label: t(".matching_transaction") } %>
+ <%= render DS::Select.new(
+ form: form,
+ method: :matched_entry_id,
+ items: candidates.map { |candidate| { value: candidate.id, label: entry_name_detailed(candidate), object: candidate.account } },
+ selected: candidates.first.id,
+ variant: :logo,
+ label: t(".matching_transaction")
+ ) %>
</div>
<div data-transfer-match-target="newSelect" class="hidden">
- <%= form.select :target_account_id,
- accounts.map { |account| [account.name, account.id] },
- { label: t(".target_account") } %>
+ <%= render DS::Select.new(
+ form: form,
+ method: :target_account_id,
+ items: account_items,
+ selected: account_items.first&.dig(:value),
+ variant: :logo,
+ searchable: true,
+ label: t(".target_account")
+ ) %>
</div>
</div>
<% else %>
@@ -35,9 +46,13 @@
<%= form.hidden_field :method, value: "new" %>
- <div>
- <%= form.select :target_account_id,
- accounts.map { |account| [account.name, account.id] },
- { label: t(".target_account") } %>
- </div>
+ <%= render DS::Select.new(
+ form: form,
+ method: :target_account_id,
+ items: account_items,
+ selected: account_items.first&.dig(:value),
+ variant: :logo,
+ searchable: true,
+ label: t(".target_account")
+ ) %>
<% end %>
diff --git a/app/views/transfer_matches/new.html.erb b/app/views/transfer_matches/new.html.erb
index e85f3dc4e0..a1551414c8 100644
--- a/app/views/transfer_matches/new.html.erb
+++ b/app/views/transfer_matches/new.html.erb
@@ -14,18 +14,18 @@
</h2>
<% if @entry.amount.positive? %>
- <%= f.select(
- :entry_id,
- [[entry_name_detailed(@entry), @entry.id]],
- {
- label: t(".outflow_transaction"),
- selected: @entry.id,
- },
- disabled: true
+ <%= render DS::Select.new(
+ form: f,
+ method: :entry_id,
+ items: [ { value: @entry.id, label: entry_name_detailed(@entry), object: @entry.account } ],
+ selected: @entry.id,
+ variant: :logo,
+ disabled: true,
+ label: t(".outflow_transaction")
) %>
<% else %>
<%= render "transfer_matches/matching_fields",
- form: f, entry: @entry, candidates: @transfer_match_candidates.map { |pm| pm.outflow_transaction.entry }, accounts: @accounts %>
+ form: f, entry: @entry, candidates: @candidate_entries, accounts: @accounts %>
<% end %>
</div>
</section>
@@ -41,18 +41,18 @@
</h2>
<% if @entry.amount.negative? %>
- <%= f.select(
- :entry_id,
- [[entry_name_detailed(@entry), @entry.id]],
- {
- label: t(".inflow_transaction"),
- selected: @entry.id,
- },
- disabled: true
+ <%= render DS::Select.new(
+ form: f,
+ method: :entry_id,
+ items: [ { value: @entry.id, label: entry_name_detailed(@entry), object: @entry.account } ],
+ selected: @entry.id,
+ variant: :logo,
+ disabled: true,
+ label: t(".inflow_transaction")
) %>
<% else %>
<%= render "transfer_matches/matching_fields",
- form: f, entry: @entry, candidates: @transfer_match_candidates.map { |pm| pm.inflow_transaction.entry }, accounts: @accounts %>
+ form: f, entry: @entry, candidates: @candidate_entries, accounts: @accounts %>
<% end %>
</div>
</section>
diff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.yml
index 8362bba343..366a990c3e 100644
--- a/config/locales/views/transactions/en.yml
+++ b/config/locales/views/transactions/en.yml
@@ -186,6 +186,9 @@ en:
split: Split
split_tooltip: This transaction has been split into multiple entries
split_child_tooltip: Part of a split transaction
+ transfer_hint: Transfer?
+ transfer_hint_dismiss: Not a transfer
+ transfer_hint_tooltip: A matching transaction in another account looks like the other side of a transfer — click to match them
merge_duplicate:
success: Transactions merged successfully
failure: Could not merge transactions
diff --git a/config/locales/views/transactions/ru.yml b/config/locales/views/transactions/ru.yml
index 37421782ee..0fa02f35f5 100644
--- a/config/locales/views/transactions/ru.yml
+++ b/config/locales/views/transactions/ru.yml
@@ -386,6 +386,9 @@ ru:
split: Разделена
split_child_tooltip: Часть разделенной операции
split_tooltip: Эта операция была разделена на несколько записей
+ transfer_hint: Перевод?
+ transfer_hint_dismiss: Это не перевод
+ transfer_hint_tooltip: В другом счёте есть похожая встречная операция — нажмите, чтобы сопоставить их как перевод
transfer_match:
auto_matched: Автоматически сопоставлено
auto_matched_short: А/С
diff --git a/config/routes.rb b/config/routes.rb
index cb96a26b58..b8a251e821 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -566,7 +566,7 @@ Rails.application.routes.draw do
resources :transactions, only: %i[index new create show update destroy] do
resource :split, only: %i[new create edit update destroy]
- resource :transfer_match, only: %i[new create]
+ resource :transfer_match, only: %i[new create destroy]
resource :pending_duplicate_merges, only: %i[new create]
resource :category, only: :update, controller: :transaction_categories
resources :attachments, only: %i[show create destroy], controller: :transaction_attachments
diff --git a/test/components/DS/select_test.rb b/test/components/DS/select_test.rb
index 4b50fa708c..2592207b80 100644
--- a/test/components/DS/select_test.rb
+++ b/test/components/DS/select_test.rb
@@ -47,6 +47,44 @@ class DS::SelectTest < ViewComponent::TestCase
assert_not select.child?(blank_item)
end
+ test "the logo variant shows the selected item's logo on the closed trigger" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client")
+ account = accounts(:depository)
+ account.update!(institution_domain: "example-bank.com")
+
+ render_select(variant: :logo, items: [ account ], selected: account.id)
+
+ assert_selector "button[data-select-target=button] [data-select-logo] img[src*='example-bank.com']"
+ assert_selector "button[data-select-target=button]", text: account.name
+ end
+
+ test "the logo variant falls back to a lettermark on the closed trigger" do
+ account = accounts(:depository)
+
+ render_select(variant: :logo, items: [ account ], selected: account.id)
+
+ assert_selector "button[data-select-target=button] [data-select-logo]"
+ assert_no_selector "button[data-select-target=button] img"
+ end
+
+ test "the simple variant keeps a plain-text trigger" do
+ account = accounts(:depository)
+
+ render_select(variant: :simple, items: [ account ], selected: account.id)
+
+ assert_no_selector "button[data-select-target=button] [data-select-logo]"
+ assert_selector "button[data-select-target=button]", text: account.name
+ end
+
+ test "a disabled select shows its value without a submitted field" do
+ account = accounts(:depository)
+
+ render_select(variant: :logo, items: [ account ], selected: account.id, disabled: true)
+
+ assert_selector "button[data-select-target=button][disabled] [data-select-logo]"
+ assert_no_selector "input[type=hidden][name='transfer_match[account_id]']", visible: :all
+ end
+
test "falls back to the placeholder, not the include_blank item's own label, when nothing is selected" do
render_inline DS::Select.new(
form: form_builder_for(Category.new, "category"),
@@ -75,6 +113,16 @@ class DS::SelectTest < ViewComponent::TestCase
end
private
+ def render_select(**options)
+ with_request_url "/" do
+ render_inline(DS::Select.new(form: form_builder, method: :account_id, **options))
+ end
+ end
+
+ def form_builder
+ ActionView::Helpers::FormBuilder.new(:transfer_match, nil, vc_test_controller.view_context, {})
+ end
+
def form_builder_for(object, name)
StyledFormBuilder.new(name, object, vc_test_controller.view_context, {})
end
diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rb
index e1c3706cf9..61513b6754 100644
--- a/test/controllers/accounts_controller_test.rb
+++ b/test/controllers/accounts_controller_test.rb
@@ -17,6 +17,16 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
assert_select "p.ml-auto.privacy-sensitive"
end
+ test "show points an unmatched transaction with a counterpart to the transfer matcher" do
+ outflow = create_transaction(account: @account, name: "Hint outflow", amount: 500, date: Date.current)
+ create_transaction(account: accounts(:credit_card), name: "Hint inflow", amount: -500, date: Date.current)
+
+ get account_url(@account)
+
+ assert_response :success
+ assert_select "a[href='#{new_transaction_transfer_match_path(outflow)}']", text: I18n.t("transactions.transaction.transfer_hint")
+ end
+
test "show filters account activity to uncategorized transactions" do
uncategorized = create_transaction(account: @account, name: "Uncategorized Filter Target", category: nil)
categorized = create_transaction(account: @account, name: "Categorized Filter Decoy", category: categories(:food_and_drink))
diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rb
index c0f7fcd37f..4a40661268 100644
--- a/test/controllers/transactions_controller_test.rb
+++ b/test/controllers/transactions_controller_test.rb
@@ -90,6 +90,22 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTest
"the preview-gated bill link must not render for a user without the flag"
end
+ test "index points an unmatched transaction with a counterpart to the transfer matcher" do
+ outflow = create_transaction(account: accounts(:depository), name: "Hint outflow", amount: 500, date: Date.current)
+ inflow = create_transaction(account: accounts(:credit_card), name: "Hint inflow", amount: -500, date: Date.current)
+ lone = create_transaction(account: accounts(:depository), name: "Hint lone", amount: 77, date: Date.current)
+
+ get transactions_url
+
+ assert_response :success
+ [ outflow, inflow ].each do |entry|
+ assert_select "a[href='#{new_transaction_transfer_match_path(entry)}'][data-turbo-frame=modal]",
+ text: I18n.t("transactions.transaction.transfer_hint")
+ end
+ assert_select "a[href='#{new_transaction_transfer_match_path(lone)}']", count: 0
+ assert_select "##{dom_id(outflow.transaction, :transfer_hint)} form[action='#{transaction_transfer_match_path(outflow)}'] input[name=_method][value=delete]"
+ end
+
test "the investment activity badge shows translated labels" do
@user.update!(locale: "ru")
accounts(:investment).entries.create!(
diff --git a/test/controllers/transfer_matches_controller_test.rb b/test/controllers/transfer_matches_controller_test.rb
index 4d373714f0..bcc6a3a531 100644
--- a/test/controllers/transfer_matches_controller_test.rb
+++ b/test/controllers/transfer_matches_controller_test.rb
@@ -20,8 +20,59 @@ class TransferMatchesControllerTest < ActionDispatch::IntegrationTest
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
+ assert_select "[role=option][data-value=?]", visible_inflow.id
+ assert_select "[role=option][data-value=?]", hidden_inflow.id, count: 0
+ end
+
+ test "new shows account logos and preselects the closest candidate and first account" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client")
+ accounts(:investment).update!(institution_domain: "example-broker.com")
+
+ outflow_entry = create_transaction(amount: 100, account: accounts(:depository))
+ inflow = create_transaction(amount: -100, account: accounts(:investment), name: "Broker inflow")
+
+ get new_transaction_transfer_match_path(outflow_entry)
+
+ assert_response :success
+ assert_select "[role=option][data-value=?] img[src*='example-broker.com']", inflow.id
+ assert_select "input[type=hidden][name='transfer_match[matched_entry_id]'][value=?]", inflow.id
+ assert_select "input[type=hidden][name='transfer_match[target_account_id]']:not([value=''])"
+ end
+
+ test "new preselects an unrejected candidate over a closer rejected one" do
+ outflow_entry = create_transaction(amount: 123.45, account: accounts(:depository), date: Date.current)
+ rejected_inflow = create_transaction(amount: -123.45, account: accounts(:investment), date: Date.current, name: "Rejected inflow")
+ open_inflow = create_transaction(amount: -123.45, account: accounts(:credit_card), date: 1.day.ago.to_date, name: "Open inflow")
+ RejectedTransfer.create!(inflow_transaction_id: rejected_inflow.entryable_id, outflow_transaction_id: outflow_entry.entryable_id)
+
+ get new_transaction_transfer_match_path(outflow_entry)
+
+ assert_response :success
+ assert_select "[role=option][data-value=?]", rejected_inflow.id
+ assert_select "input[type=hidden][name='transfer_match[matched_entry_id]'][value=?]", open_inflow.id
+ end
+
+ test "new preloads account logo dependencies for every select option" do
+ outflow_entry = create_transaction(amount: 123.45, account: accounts(:depository))
+ 3.times do |i|
+ account = @user.family.accounts.create!(name: "Logo account #{i}", currency: "USD", balance: 0, accountable: Depository.new, owner: @user)
+ create_transaction(amount: -123.45, account: account)
+ end
+ option_account_ids = @user.family.accounts.where.not(id: outflow_entry.account_id).pluck(:id)
+
+ # Batched IN (...) preloads are fine; a per-account lookup is the N+1.
+ single_lookup_ids = []
+ callback = lambda do |*, payload|
+ next unless payload[:sql].match?(/FROM "(account_providers|active_storage_attachments)" WHERE .*"(account_id|record_id)" = \$1/)
+
+ single_lookup_ids << payload[:binds].first.value
+ end
+ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
+ get new_transaction_transfer_match_path(outflow_entry)
+ end
+
+ assert_response :success
+ assert_empty single_lookup_ids & option_account_ids
end
test "matches existing transaction and creates transfer" do
@@ -92,4 +143,41 @@ class TransferMatchesControllerTest < ActionDispatch::IntegrationTest
category = @user.family.investment_contributions_category
assert_equal category, outflow_txn.category
end
+
+ test "new shows the transaction being matched with its account logo" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client")
+ accounts(:credit_card).update!(institution_domain: "example-card.com")
+ inflow = create_transaction(amount: -100, account: accounts(:credit_card))
+
+ get new_transaction_transfer_match_path(inflow)
+
+ assert_response :success
+ assert_select "button[disabled][data-select-target=button] img[src*='example-card.com']"
+ assert_select "select[name='transfer_match[entry_id]']", count: 0
+ end
+
+ test "destroy dismisses the transfer hint by rejecting its pairs" do
+ outflow = create_transaction(amount: 500, account: accounts(:depository))
+ inflow = create_transaction(amount: -500, account: accounts(:credit_card))
+
+ assert_difference -> { RejectedTransfer.count } => 1 do
+ delete transaction_transfer_match_path(outflow), as: :turbo_stream
+ end
+
+ assert_response :success
+ assert_match %(<turbo-stream action="remove" target="#{ActionView::RecordIdentifier.dom_id(outflow.transaction, :transfer_hint)}">), response.body
+ assert RejectedTransfer.exists?(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id)
+ end
+
+ test "destroy is refused on an account the user may only read" do
+ loan = accounts(:loan)
+ loan.update!(owner: users(:family_member))
+ loan.account_shares.create!(user: @user, permission: "read_only")
+ outflow = create_transaction(amount: 500, account: loan)
+ create_transaction(amount: -500, account: accounts(:credit_card))
+
+ assert_no_difference -> { RejectedTransfer.count } do
+ delete transaction_transfer_match_path(outflow)
+ end
+ end
end
diff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rb
index 7ce7b70eb9..a35203ecc8 100644
--- a/test/models/family/auto_transfer_matchable_test.rb
+++ b/test/models/family/auto_transfer_matchable_test.rb
@@ -694,6 +694,17 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCase
assert_empty noise_pairs
end
+ test "manual transfer candidates list same-category counterparts first" do
+ category = categories(:food_and_drink)
+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500, category: category)
+ closer = create_transaction(date: Date.current, account: @depository, amount: 500, category: categories(:income))
+ same_category = create_transaction(date: 3.days.ago.to_date, account: @other_asset, amount: 500, category: category)
+
+ candidates = inflow.transaction.transfer_match_candidates
+
+ assert_equal [ same_category.entryable_id, closer.entryable_id ], candidates.map(&:outflow_transaction_id)
+ end
+
test "single transaction transfer candidates filter optimized relation aliases" do
outflow = create_transaction(date: Date.current, account: @depository, amount: 500)
inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500)
@@ -705,6 +716,118 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCase
assert_equal [ outflow.entryable_id ], inflow_candidates.map(&:outflow_transaction_id)
end
+ test "transaction_ids_with_transfer_candidates flags both legs of an unmatched pair" do
+ outflow = create_transaction(date: 2.days.ago.to_date, account: @depository, amount: 500)
+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500)
+ lone = create_transaction(date: Date.current, account: @depository, amount: 77)
+
+ ids = @family.transaction_ids_with_transfer_candidates(
+ [ outflow.transaction, inflow.transaction, lone.transaction ], user: users(:family_admin)
+ )
+
+ assert_equal Set[outflow.entryable_id, inflow.entryable_id], ids
+ end
+
+ test "transaction_ids_with_transfer_candidates only looks at the given transactions" do
+ outflow = create_transaction(date: Date.current, account: @depository, amount: 500)
+ create_transaction(date: Date.current, account: @credit_card, amount: -500)
+ create_transaction(date: Date.current, account: @depository, amount: 600)
+ create_transaction(date: Date.current, account: @credit_card, amount: -600)
+
+ ids = @family.transaction_ids_with_transfer_candidates([ outflow.transaction ], user: users(:family_admin))
+
+ assert_equal Set[outflow.entryable_id], ids
+ end
+
+ test "transaction_ids_with_transfer_candidates skips matched and rejected pairs" do
+ outflow = create_transaction(date: Date.current, account: @depository, amount: 500)
+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500)
+ RejectedTransfer.create!(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id)
+
+ matched_out = create_transaction(date: Date.current, account: @depository, amount: 900)
+ matched_in = create_transaction(date: Date.current, account: @credit_card, amount: -900)
+ Transfer.create!(inflow_transaction: matched_in.transaction, outflow_transaction: matched_out.transaction)
+
+ transactions = [ outflow, inflow, matched_out, matched_in ].map(&:transaction)
+
+ assert_empty @family.transaction_ids_with_transfer_candidates(transactions, user: users(:family_admin))
+ end
+
+ test "transaction_ids_with_transfer_candidates ignores counterparts the user cannot write to" do
+ @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)
+
+ ids = @family.transaction_ids_with_transfer_candidates(
+ [ outflow.transaction, inflow.transaction ], user: users(:family_admin)
+ )
+
+ assert_empty ids
+ end
+
+ test "transaction_ids_with_transfer_candidates finds cross-currency pairs between manual accounts" do
+ ExchangeRate.create!(from_currency: "USD", to_currency: "GBP", date: Date.current, rate: 0.8)
+ outflow = create_transaction(date: Date.current, account: @depository, amount: 500)
+ inflow = create_transaction(date: Date.current, account: @other_asset, amount: -400, currency: "GBP")
+
+ ids = @family.transaction_ids_with_transfer_candidates([ inflow.transaction ], user: users(:family_admin))
+
+ assert_equal Set[inflow.entryable_id], ids
+ end
+
+ test "transaction_ids_with_transfer_candidates skips pairs whose legs carry different categories" do
+ groceries = categories(:food_and_drink)
+ other = categories(:income)
+ purchase = create_transaction(date: Date.current, account: @depository, amount: 500, category: groceries)
+ income = create_transaction(date: Date.current, account: @credit_card, amount: -500, category: other)
+ half_out = create_transaction(date: Date.current, account: @depository, amount: 300, category: groceries)
+ half_in = create_transaction(date: Date.current, account: @credit_card, amount: -300)
+
+ transactions = [ purchase, income, half_out, half_in ].map(&:transaction)
+
+ assert_empty @family.transaction_ids_with_transfer_candidates(transactions, user: users(:family_admin))
+ end
+
+ test "transaction_ids_with_transfer_candidates keeps pairs that share a category" do
+ category = categories(:food_and_drink)
+ outflow = create_transaction(date: Date.current, account: @depository, amount: 500, category: category)
+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500, category: category)
+
+ ids = @family.transaction_ids_with_transfer_candidates([ outflow.transaction, inflow.transaction ], user: users(:family_admin))
+
+ assert_equal Set[outflow.entryable_id, inflow.entryable_id], ids
+ end
+
+ test "dismiss_transfer_hint! rejects the hinted pairs of one transaction" do
+ outflow = create_transaction(date: Date.current, account: @depository, amount: 500)
+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500)
+
+ assert_difference -> { RejectedTransfer.count } => 1 do
+ @family.dismiss_transfer_hint!(inflow.transaction, user: users(:family_admin))
+ end
+
+ assert_empty @family.transaction_ids_with_transfer_candidates([ outflow.transaction, inflow.transaction ], user: users(:family_admin))
+ assert_no_difference -> { Transfer.count } do
+ @family.auto_match_transfers!
+ end
+ # The manual dialog still offers the pair.
+ assert_equal [ outflow.entryable_id ], inflow.transaction.transfer_match_candidates.map(&:outflow_transaction_id)
+ end
+
+ test "transaction_ids_with_transfer_candidates stays narrower than the manual dialog" do
+ ExchangeRate.create!(from_currency: "USD", to_currency: "GBP", date: Date.current, rate: 0.8)
+ outflow = create_transaction(date: Date.current, account: @depository, amount: 500)
+ # 8% off the rate: the dialog offers it, the unprompted hint does not.
+ inflow = create_transaction(date: Date.current, account: @other_asset, amount: -432, currency: "GBP")
+ far_outflow = create_transaction(date: 5.days.ago.to_date, account: @depository, amount: 900)
+ far_inflow = create_transaction(date: Date.current, account: @credit_card, amount: -900)
+
+ assert_equal [ outflow.entryable_id ], inflow.transaction.transfer_match_candidates.map(&:outflow_transaction_id)
+ assert_empty @family.transaction_ids_with_transfer_candidates(
+ [ inflow.transaction, far_outflow.transaction, far_inflow.transaction ], user: users(:family_admin)
+ )
+ end
+
test "transfer candidate query separates exact and exchange-rate matching paths" do
sql = @family.send(:transfer_match_candidates_sql)