The personal finance app for everyone (by everyone)
Ruby
feat(mcp): add transfer matching tools (#3818)
scragnog13c03a3607c2
diff --git a/app/models/assistant.rb b/app/models/assistant.rbindex e124912b3f..e99cc5df53 100644--- a/app/models/assistant.rb+++ b/app/models/assistant.rb@@ -95,6 +95,9 @@ module AssistantFunction::UpdateTransaction,Function::CreateTransaction,Function::DeleteTransaction,+ Function::GetTransferMatchCandidates,+ Function::MatchTransfer,+ Function::ReviewTransfer,Function::UpdateBudget]diff --git a/app/models/assistant/function/get_transfer_match_candidates.rb b/app/models/assistant/function/get_transfer_match_candidates.rbnew file mode 100644index 0000000000..8c68317c46--- /dev/null+++ b/app/models/assistant/function/get_transfer_match_candidates.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++# GetTransferMatchCandidates — the read half of match_transfer. Shows whether a+# transaction is already part of a transfer (including a pending auto-match+# awaiting review) and, if not, which existing transactions it could be+# matched with. Same candidate rules as the "Match transfer" dialog.+class Assistant::Function::GetTransferMatchCandidates < Assistant::Function+ include Assistant::Function::TransferMatchSupport++ class << self+ def name+ "get_transfer_match_candidates"+ end++ def description+ <<~INSTRUCTIONS+ Shows how a transaction can be matched as a transfer between the user's+ own accounts (e.g. a card payment, a loan repayment, a move to savings).++ Returns the transaction's current transfer, if any. A transfer with+ status "pending" is an auto-match Sure suggested that the user has not+ reviewed yet; confirm or reject it with review_transfer.++ Otherwise returns candidate transactions in other accounts: opposite+ direction, matching amount, within 30 days. `previously_rejected` marks a+ pairing the user already rejected, so ask before matching it.++ Use match_transfer to link the transaction with a candidate, or with+ an account that has no matching transaction (e.g. a manual loan account).+ INSTRUCTIONS+ end+ end++ def strict_mode?+ false+ end++ def params_schema+ build_schema(+ required: %w[transaction_id],+ properties: {+ transaction_id: {+ type: "string",+ description: "Transaction ID from get_transactions."+ }+ }+ )+ end++ def call(params = {})+ transaction = find_transaction(params["transaction_id"], writable: false)+ return error("not_found", "No transaction with id '#{params["transaction_id"]}' in an account you can access.") unless transaction++ result = { success: true, transaction: serialize_transaction(transaction) }++ if (transfer = transaction.transfer)+ result[:transfer] = serialize_transfer(transfer, from: transaction)+ result[:candidates] = []+ return result+ end++ matcher = Transfer::Matcher.new(transaction)+ rows = matcher.candidates+ counterparts = Transaction.includes(entry: :account).where(id: rows.map { |row| matcher.counterpart_id(row) }).index_by(&:id)++ result[:candidates] = rows.filter_map do |row|+ counterpart = counterparts[matcher.counterpart_id(row)]+ next unless counterpart && accessible_account_ids.include?(counterpart.entry.account_id)++ serialize_transaction(counterpart).merge(+ days_apart: row.date_diff.to_i,+ previously_rejected: row.rejected_transfer_id.present?+ )+ end++ result+ end+enddiff --git a/app/models/assistant/function/match_transfer.rb b/app/models/assistant/function/match_transfer.rbnew file mode 100644index 0000000000..6482407831--- /dev/null+++ b/app/models/assistant/function/match_transfer.rb@@ -0,0 +1,162 @@+# frozen_string_literal: true++# MatchTransfer — links an existing transaction into a confirmed transfer, the+# same operation as the "Match transfer" dialog. Either pairs it with an+# existing opposite transaction, or creates the missing counterpart in a+# target account (the usual case for manual loan, mortgage and savings+# accounts that have no bank feed).+#+# Both accounts must be writable by the user. The data rules live in+# Transfer::Matcher.+class Assistant::Function::MatchTransfer < Assistant::Function+ include Assistant::Function::TransferMatchSupport++ class << self+ def name+ "match_transfer"+ end++ def description+ <<~INSTRUCTIONS+ Marks a transaction as a transfer between the user's own accounts, so it+ stops counting as income or spending and moves the other account's+ balance. Payments to loans and credit cards still count in budgets.++ Pass exactly one of:+ - counterpart_transaction_id: an existing transaction to pair with,+ from get_transfer_match_candidates.+ - target_account_id: an account (from get_accounts) with no matching+ transaction; a counterpart transaction is created there.++ Pass dry_run: true to see what would happen without changing anything.++ Returns already_linked (with the transfer id) if either transaction is+ already in a transfer. If the pair you asked for is already a pending+ auto-match, returns pending_match: confirm it with review_transfer+ (action "confirm"). For a pending auto-match with a different+ counterpart, reject it with review_transfer first. Matching the same+ confirmed pair again is a no-op.+ INSTRUCTIONS+ end+ end++ def strict_mode?+ false+ end++ def params_schema+ build_schema(+ required: %w[transaction_id],+ properties: {+ transaction_id: {+ type: "string",+ description: "Transaction ID from get_transactions."+ },+ counterpart_transaction_id: {+ type: "string",+ description: "Existing opposite transaction to pair with, from get_transfer_match_candidates. Omit when passing target_account_id."+ },+ target_account_id: {+ type: "string",+ description: "Account to create the counterpart transaction in, from get_accounts. Omit when passing counterpart_transaction_id."+ },+ dry_run: {+ type: "boolean",+ description: "Describe the change without making it. Defaults to false."+ }+ }+ )+ end++ def call(params = {})+ if params["counterpart_transaction_id"].present? == params["target_account_id"].present?+ return error("invalid_arguments", "Pass exactly one of counterpart_transaction_id or target_account_id.")+ end++ transaction = find_transaction(params["transaction_id"], writable: true)+ return error("not_found", "No transaction with id '#{params["transaction_id"]}' in an account you can write to.") unless transaction++ if params["counterpart_transaction_id"].present?+ counterpart = find_transaction(params["counterpart_transaction_id"], writable: true)+ return error("not_found", "No transaction with id '#{params["counterpart_transaction_id"]}' in an account you can write to.") unless counterpart+ else+ account = find_account(params["target_account_id"])+ return error("account_not_found", "No account with id '#{params["target_account_id"]}' that you can write to.") unless account+ end++ if (existing = transaction.transfer)+ return already_matched(existing, transaction) if same_match?(existing, transaction, counterpart, account)++ if existing.pending? && same_pair?(existing, transaction, counterpart, account)+ return error(+ "pending_match",+ "This pair is already a pending auto-match. Confirm it with review_transfer (action: \"confirm\", transfer_id: \"#{existing.id}\"); don't reject it.",+ transfer: serialize_transfer(existing, from: transaction)+ )+ end++ return error(+ "already_linked",+ existing.pending? ? "The transaction is in a pending auto-match. Reject it with review_transfer before matching it elsewhere." : "The transaction is already part of a transfer.",+ transfer: serialize_transfer(existing, from: transaction)+ )+ end++ if counterpart&.transfer+ return error("already_linked", "The counterpart transaction is already part of a transfer.", transfer: serialize_transfer(counterpart.transfer, from: counterpart))+ end++ dry_run = ActiveModel::Type::Boolean.new.cast(params["dry_run"]) || false+ matcher = Transfer::Matcher.new(transaction)+ transfer = counterpart ? matcher.match_with!(counterpart, dry_run:) : matcher.match_to_account!(account, dry_run:)++ return dry_run_result(transfer, transaction, account) if dry_run++ {+ success: true,+ created_counterpart: counterpart.nil?,+ transfer: transfer_result(transfer)+ }+ rescue Transfer::Matcher::Error => e+ error(e.code.to_s, e.message)+ end++ private+ def same_match?(transfer, transaction, counterpart, account)+ !transfer.pending? && same_pair?(transfer, transaction, counterpart, account)+ end++ def same_pair?(transfer, transaction, counterpart, account)+ other = transfer.inflow_transaction_id == transaction.id ? transfer.outflow_transaction : transfer.inflow_transaction+ return false if other.nil?++ counterpart ? other.id == counterpart.id : other.entry.account_id == account.id+ end++ def already_matched(transfer, transaction)+ { success: true, already_matched: true, transfer: serialize_transfer(transfer, from: transaction) }+ end++ # The transfer is unsaved: a counterpart to be created has no id yet.+ def dry_run_result(transfer, transaction, account)+ counterpart = transfer.inflow_transaction == transaction ? transfer.outflow_transaction : transfer.inflow_transaction++ {+ success: true,+ dry_run: true,+ transaction: serialize_transaction(transaction),+ counterpart: account ? nil : serialize_transaction(counterpart),+ creates_counterpart_in: account && { account_id: account.id, account: account.name, name: counterpart.entry.name },+ outflow_kind: Transfer.kind_for_account(transfer.inflow_transaction.entry.account)+ }.compact+ end++ def transfer_result(transfer)+ {+ transfer_id: transfer.id,+ status: transfer.status,+ outflow: serialize_transaction(transfer.outflow_transaction.reload),+ inflow: serialize_transaction(transfer.inflow_transaction.reload)+ }+ end+enddiff --git a/app/models/assistant/function/review_transfer.rb b/app/models/assistant/function/review_transfer.rbnew file mode 100644index 0000000000..7060e89b0f--- /dev/null+++ b/app/models/assistant/function/review_transfer.rb@@ -0,0 +1,101 @@+# frozen_string_literal: true++# ReviewTransfer — confirms or rejects a pending auto-matched transfer, the+# same as the Confirm / Reject buttons on an "Auto-matched" transaction.+# Rejecting records the pairing so auto-match does not suggest it again.+class Assistant::Function::ReviewTransfer < Assistant::Function+ include Assistant::Function::TransferMatchSupport++ ACTIONS = %w[confirm reject].freeze++ class << self+ def name+ "review_transfer"+ end++ def description+ <<~INSTRUCTIONS+ Confirms or rejects a transfer that Sure auto-matched and the user has+ not reviewed yet (status "pending" in get_transfer_match_candidates).++ confirm keeps the match. reject unlinks the two transactions and stops+ auto-match from suggesting that pairing again.++ Only pending transfers can be reviewed. Both accounts must be writable.+ INSTRUCTIONS+ end+ end++ def strict_mode?+ false+ end++ def params_schema+ build_schema(+ required: %w[transfer_id action],+ properties: {+ transfer_id: {+ type: "string",+ description: "Transfer ID from get_transfer_match_candidates."+ },+ action: {+ type: "string",+ enum: ACTIONS,+ description: "confirm or reject."+ }+ }+ )+ end++ def call(params = {})+ return error("invalid_arguments", "action must be one of: #{ACTIONS.join(", ")}.") unless ACTIONS.include?(params["action"])++ transfer = find_transfer(params["transfer_id"])+ return error("not_found", "No transfer with id '#{params["transfer_id"]}' between accounts you can write to.") unless transfer+ return error("not_pending", "Only pending auto-matched transfers can be reviewed; this one is #{transfer.status}.") unless transfer.pending?++ snapshot = {+ transfer_id: transfer.id,+ outflow: serialize_transaction(transfer.outflow_transaction),+ inflow: serialize_transaction(transfer.inflow_transaction)+ }++ # Lock and recheck, so of two concurrent reviews only the first one acts:+ # otherwise a reject could destroy a transfer another call just confirmed.+ reviewed = transfer.with_lock do+ next false unless transfer.pending?++ params["action"] == "confirm" ? transfer.confirm! : transfer.reject!+ true+ end+ return error("not_pending", "The transfer was reviewed by another request; it is no longer pending.") unless reviewed++ if params["action"] == "confirm"+ # confirm! sets the kinds, so report the transactions as they are now.+ confirmed = {+ transfer_id: transfer.id,+ outflow: serialize_transaction(transfer.outflow_transaction.reload),+ inflow: serialize_transaction(transfer.inflow_transaction.reload),+ status: transfer.status+ }+ { success: true, action: "confirmed", transfer: confirmed }+ else+ { success: true, action: "rejected", transfer: snapshot }+ end+ end++ private+ def find_transfer(id)+ return nil unless valid_uuid?(id)++ writable_transaction_ids = family.transactions+ .joins(entry: :account)+ .merge(Account.writable_by(user))+ .select(:id)++ Transfer+ .where(inflow_transaction_id: writable_transaction_ids)+ .where(outflow_transaction_id: writable_transaction_ids)+ .find_by(id: id)+ end+enddiff --git a/app/models/assistant/function/transfer_match_support.rb b/app/models/assistant/function/transfer_match_support.rbnew file mode 100644index 0000000000..b3a6bdaf43--- /dev/null+++ b/app/models/assistant/function/transfer_match_support.rb@@ -0,0 +1,68 @@+# frozen_string_literal: true++# Shared plumbing for the transfer-matching tools (get_transfer_match_candidates,+# match_transfer, review_transfer). Tool calls never pass through+# TransferMatchesController or TransfersController, so every lookup here+# re-applies their account-access scopes: reads resolve through accounts the+# user can see, writes through accounts the user can write to. Anything else+# resolves to nil, so a caller cannot tell "no access" from "does not exist".+module Assistant::Function::TransferMatchSupport+ private+ def find_transaction(id, writable:)+ return nil unless valid_uuid?(id)++ family.transactions+ .joins(entry: :account)+ .merge(writable ? Account.writable_by(user) : Account.accessible_by(user))+ .find_by(id: id)+ end++ def find_account(id)+ return nil unless valid_uuid?(id)++ family.accounts.visible.writable_by(user).find_by(id: id)+ end++ def accessible_account_ids+ @accessible_account_ids ||= family.accounts.accessible_by(user).pluck(:id).to_set+ end++ def serialize_transaction(transaction)+ entry = transaction.entry++ {+ transaction_id: transaction.id,+ account_id: entry.account_id,+ account: entry.account.name,+ name: entry.name,+ date: entry.date,+ amount: entry.amount.abs.to_s,+ amount_formatted: format_money(entry.amount_money.abs),+ currency: entry.currency,+ direction: entry.amount.negative? ? "inflow" : "outflow",+ kind: transaction.kind+ }+ end++ # The counterpart is omitted when it sits in an account the user cannot+ # see, e.g. a transfer into another member's private account.+ def serialize_transfer(transfer, from:)+ other = transfer.inflow_transaction_id == from.id ? transfer.outflow_transaction : transfer.inflow_transaction++ {+ transfer_id: transfer.id,+ status: transfer.status,+ counterpart: (serialize_transaction(other) if other && accessible_account_ids.include?(other.entry.account_id))+ }.compact+ end++ def format_money(money)+ money.format+ rescue StandardError+ "#{money.amount} #{money.currency}"+ end++ def error(key, message, **details)+ { success: false, error: key, message: message, **details }+ end+enddiff --git a/app/models/transfer/matcher.rb b/app/models/transfer/matcher.rbnew file mode 100644index 0000000000..a2cafd1502--- /dev/null+++ b/app/models/transfer/matcher.rb@@ -0,0 +1,154 @@+# Links an existing transaction into a confirmed transfer, either with an+# existing opposite transaction (one of Transaction#transfer_match_candidates)+# or with a new counterpart entry created in a target account.+#+# This is the same operation as TransferMatchesController#create and+# Rule::ActionExecutor::SetAsTransferOrPayment, which predate this class.+# Kinds and the Investment Contributions category come from Transfer#confirm!,+# as there. Permission checks are the caller's job: this class enforces only+# the data rules.+class Transfer::Matcher+ class Error < StandardError+ attr_reader :code++ def initialize(code, message)+ @code = code+ super(message)+ end+ end++ # The manual match dialog's window. Transfer validation allows confirmed+ # transfers up to 30 days apart.+ DATE_WINDOW = 30++ attr_reader :transaction++ def initialize(transaction)+ @transaction = transaction+ end++ # Only pairs match_with! accepts: the family query already skips excluded+ # entries (including split parents), so split children are dropped here.+ def candidates(date_window: DATE_WINDOW)+ return [] if entry.excluded? || entry.split_child?++ filter = entry.amount.negative? ? { inflow_transaction_id: transaction.id } : { outflow_transaction_id: transaction.id }++ rows = family.transfer_match_candidates(+ date_window: date_window,+ exchange_rate_tolerance: Family::AutoTransferMatchable.manual_match_exchange_rate_tolerance,+ **filter+ )++ split_child_ids = Entry.where(entryable_type: "Transaction", entryable_id: rows.map { |row| counterpart_id(row) })+ .where.not(parent_entry_id: nil)+ .pluck(:entryable_id)+ .to_set++ rows.reject { |row| split_child_ids.include?(counterpart_id(row)) }+ end++ # The other transaction in a candidate row.+ def counterpart_id(row)+ row.inflow_transaction_id == transaction.id ? row.outflow_transaction_id : row.inflow_transaction_id+ end++ # With dry_run: true, runs every check and returns the unsaved transfer.+ def match_with!(counterpart, dry_run: false)+ link!(transaction, counterpart, dry_run:) do+ ensure_matchable!(transaction)+ ensure_matchable!(counterpart)++ unless candidates.any? { |row| counterpart_id(row) == counterpart.id }+ raise Error.new(:not_a_candidate, "The two transactions cannot form a transfer: they need opposite, matching amounts in different accounts of the same family, at most #{DATE_WINDOW} days apart.")+ end++ entry.amount.negative? ? [ transaction, counterpart ] : [ counterpart, transaction ]+ end+ end++ def match_to_account!(account, dry_run: false)+ link!(transaction, dry_run:) do+ ensure_matchable!(transaction)+ raise Error.new(:same_account, "The target account must differ from the transaction's account.") if account.id == entry.account_id+ raise Error.new(:account_not_found, "The target account must belong to the same family.") unless account.family_id == entry.account.family_id++ # Built in memory; saved together with the transfer by link!.+ counterpart = Transaction.new(+ entry: account.entries.build(+ amount: entry.amount * -1,+ currency: entry.currency,+ date: entry.date,+ name: "Transfer to #{entry.amount.negative? ? entry.account.name : account.name}",+ user_modified: true+ )+ )++ entry.amount.negative? ? [ transaction, counterpart ] : [ counterpart, transaction ]+ end+ end++ private+ def entry+ transaction.entry+ end++ def family+ entry.account.family+ end++ def ensure_matchable!(txn)+ txn_entry = txn.entry+ raise Error.new(:split_transaction, "Split transactions cannot be matched as transfers.") if txn_entry.split_parent? || txn_entry.split_child?+ raise Error.new(:excluded_transaction, "Excluded transactions cannot be matched as transfers.") if txn_entry.excluded?+ raise Error.new(:already_linked, "The transaction is already part of a transfer.") if txn.transfer.present?+ end++ # Two concurrent matches of one transaction (with different counterparts)+ # could otherwise both pass the checks; the unique index only covers the+ # pair. Lock the persisted transactions and their entries in a fixed+ # order, then reload them so the checks see what is committed now+ # (another transfer, an exclusion, a split, a changed amount or date).+ def lock_and_reload!(txns)+ ids = txns.map(&:id).sort+ Transaction.where(id: ids).order(:id).lock.pluck(:id)+ Entry.where(entryable_type: "Transaction", entryable_id: ids).order(:id).lock.pluck(:id)+ txns.each(&:reload)+ end++ # The block runs the checks and returns [inflow, outflow]. For a real+ # match it runs under the locks, uncached so no read is answered from a+ # query cache filled before the lock.+ def link!(*txns, dry_run:)+ if dry_run+ transfer = build_transfer(*yield)+ raise Error.new(:invalid_transfer, transfer.errors.full_messages.to_sentence) unless transfer.valid?+ return transfer+ end++ transfer = nil+ Transfer.uncached do+ Transfer.transaction do+ lock_and_reload!(txns)+ inflow, outflow = yield+ transfer = build_transfer(inflow, outflow)+ transfer.save!+ transfer.confirm!+ end+ end++ transfer.sync_account_later+ transfer+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e+ raise Error.new(:invalid_transfer, e.message)+ end++ def build_transfer(inflow, outflow)+ Transfer.new(+ inflow_transaction: inflow,+ outflow_transaction: outflow,+ status: "confirmed",+ amount: outflow.entry.amount.abs+ )+ end+enddiff --git a/docs/hosting/mcp.md b/docs/hosting/mcp.mdindex f7b871eaeb..24fa7b9d29 100644--- a/docs/hosting/mcp.md+++ b/docs/hosting/mcp.md@@ -152,6 +152,9 @@ At the time of writing, `tools/list` includes:| `create_tag` / `update_tag` | Manage tags || `create_category` / `update_category` / `delete_category` | Manage categories: create, rename, recolor, move between parents, and delete (optionally moving transactions to a replacement) || `update_transaction` | Edit a transaction's metadata (name, notes, category, merchant, tags) |+| `get_transfer_match_candidates` | A transaction's current transfer (including a pending auto-match) or the transactions it could be matched with, as in the "Match transfer" dialog |+| `match_transfer` | Match a transaction as a transfer with an existing counterpart, or create the counterpart in a target account (e.g. a manual loan). Supports `dry_run` |+| `review_transfer` | Confirm or reject a pending auto-matched transfer || `update_budget` | Update budget allocations for a month || `get_rules` / `get_rule_options` | Transaction rules in readable form (ids resolved to names, latest run; paginated, with a text search), and the condition and action types a rule can use || `preview_rule` | Match count and a sample of matching transactions for a saved rule or an unsaved definition, without changing anything |diff --git a/test/controllers/mcp_controller_test.rb b/test/controllers/mcp_controller_test.rbindex ddffd2c688..ef4877dec8 100644--- a/test/controllers/mcp_controller_test.rb+++ b/test/controllers/mcp_controller_test.rb@@ -319,6 +319,9 @@ class McpControllerTest < ActionDispatch::IntegrationTestassert_includes tool_names, "get_income_statement"assert_includes tool_names, "update_transaction"assert_includes tool_names, "update_budget"+ assert_includes tool_names, "get_transfer_match_candidates"+ assert_includes tool_names, "match_transfer"+ assert_includes tool_names, "review_transfer"# Each tool has required fieldstools.each do |tool|diff --git a/test/models/assistant/function/get_transfer_match_candidates_test.rb b/test/models/assistant/function/get_transfer_match_candidates_test.rbnew file mode 100644index 0000000000..2e557b06d5--- /dev/null+++ b/test/models/assistant/function/get_transfer_match_candidates_test.rb@@ -0,0 +1,64 @@+require "test_helper"++class Assistant::Function::GetTransferMatchCandidatesTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @user = users(:family_admin)+ @function = Assistant::Function::GetTransferMatchCandidates.new(@user)+ @checking = accounts(:depository)+ @card = accounts(:credit_card)+ end++ test "lists candidates and flags previously rejected pairings" do+ outflow = create_transaction(account: @checking, amount: 64, date: Date.current).transaction+ fresh = create_transaction(account: @card, amount: -64, date: 1.day.ago.to_date).transaction+ rejected = create_transaction(account: accounts(:other_liability), amount: -64, date: 2.days.ago.to_date).transaction+ RejectedTransfer.create!(outflow_transaction: outflow, inflow_transaction: rejected)++ result = @function.call("transaction_id" => outflow.id)++ assert_equal true, result[:success]+ assert_nil result[:transfer]+ by_id = result[:candidates].index_by { |c| c[:transaction_id] }+ assert_equal [ fresh.id, rejected.id ].sort, by_id.keys.sort+ assert_equal false, by_id[fresh.id][:previously_rejected]+ assert_equal true, by_id[rejected.id][:previously_rejected]+ assert_equal 1, by_id[fresh.id][:days_apart]+ assert_equal "inflow", by_id[fresh.id][:direction]+ end++ test "returns the current transfer, including a pending auto-match" do+ outflow = create_transaction(account: @checking, amount: 64).transaction+ inflow = create_transaction(account: @card, amount: -64).transaction+ transfer = Transfer.create!(outflow_transaction: outflow, inflow_transaction: inflow, status: "pending")++ result = @function.call("transaction_id" => outflow.id)++ assert_equal transfer.id, result[:transfer][:transfer_id]+ assert_equal "pending", result[:transfer][:status]+ assert_equal inflow.id, result[:transfer][:counterpart][:transaction_id]+ assert_empty result[:candidates]+ end++ test "hides candidates in accounts the user cannot access" do+ member = users(:family_member)+ private_account = families(:dylan_family).accounts.create!(+ name: "Admin private", balance: 0, currency: "USD", accountable: Depository.new, owner: @user+ )+ outflow = create_transaction(account: @checking, amount: 64).transaction+ create_transaction(account: private_account, amount: -64)++ result = Assistant::Function::GetTransferMatchCandidates.new(member).call("transaction_id" => outflow.id)++ assert_empty result[:candidates]+ end++ test "returns not_found for another family's transaction" do+ outflow = create_transaction(account: @checking, amount: 64).transaction++ result = Assistant::Function::GetTransferMatchCandidates.new(users(:josh)).call("transaction_id" => outflow.id)++ assert_equal "not_found", result[:error]+ end+enddiff --git a/test/models/assistant/function/match_transfer_test.rb b/test/models/assistant/function/match_transfer_test.rbnew file mode 100644index 0000000000..14f2fb378d--- /dev/null+++ b/test/models/assistant/function/match_transfer_test.rb@@ -0,0 +1,148 @@+require "test_helper"++class Assistant::Function::MatchTransferTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @user = users(:family_admin)+ @function = Assistant::Function::MatchTransfer.new(@user)+ @checking = accounts(:depository)+ @card = accounts(:credit_card)+ @loan = accounts(:loan)+ end++ test "matches with an existing counterpart" do+ outflow = create_transaction(account: @checking, amount: 120).transaction+ inflow = create_transaction(account: @card, amount: -120).transaction++ result = @function.call("transaction_id" => outflow.id, "counterpart_transaction_id" => inflow.id)++ assert_equal true, result[:success]+ assert_equal false, result[:created_counterpart]+ assert_equal "confirmed", result[:transfer][:status]+ assert_equal outflow.id, result[:transfer][:outflow][:transaction_id]+ assert_equal inflow.id, result[:transfer][:inflow][:transaction_id]+ assert_equal "cc_payment", result[:transfer][:outflow][:kind]+ end++ test "creates the counterpart in a target account" do+ outflow = create_transaction(account: @checking, amount: 289.60).transaction++ result = assert_difference "Entry.count", 1 do+ @function.call("transaction_id" => outflow.id, "target_account_id" => @loan.id)+ end++ assert_equal true, result[:success]+ assert_equal true, result[:created_counterpart]+ assert_equal @loan.id, result[:transfer][:inflow][:account_id]+ assert_equal "loan_payment", result[:transfer][:outflow][:kind]+ end++ test "dry run describes the match without changing anything" do+ outflow = create_transaction(account: @checking, amount: 289.60).transaction++ result = assert_no_difference [ "Entry.count", "Transfer.count" ] do+ @function.call("transaction_id" => outflow.id, "target_account_id" => @loan.id, "dry_run" => true)+ end++ assert_equal true, result[:success]+ assert_equal true, result[:dry_run]+ assert_equal @loan.id, result[:creates_counterpart_in][:account_id]+ assert_equal "loan_payment", result[:outflow_kind]+ assert_equal "standard", outflow.reload.kind+ end++ test "dry run reports validation errors" do+ outflow = create_transaction(account: @checking, amount: 100).transaction+ wrong = create_transaction(account: @card, amount: -99).transaction++ result = @function.call("transaction_id" => outflow.id, "counterpart_transaction_id" => wrong.id, "dry_run" => true)++ assert_equal false, result[:success]+ assert_equal "not_a_candidate", result[:error]+ end++ test "matching the same pair again is a no-op" do+ outflow = create_transaction(account: @checking, amount: 120).transaction+ inflow = create_transaction(account: @card, amount: -120).transaction+ @function.call("transaction_id" => outflow.id, "counterpart_transaction_id" => inflow.id)++ result = assert_no_difference "Transfer.count" do+ @function.call("transaction_id" => outflow.id, "counterpart_transaction_id" => inflow.id)+ end++ assert_equal true, result[:success]+ assert_equal true, result[:already_matched]+ end++ test "matching to the same target account again is a no-op" do+ outflow = create_transaction(account: @checking, amount: 50).transaction+ @function.call("transaction_id" => outflow.id, "target_account_id" => @loan.id)++ result = assert_no_difference [ "Transfer.count", "Entry.count" ] do+ @function.call("transaction_id" => outflow.id, "target_account_id" => @loan.id)+ end++ assert_equal true, result[:already_matched]+ end++ test "reports already_linked with the transfer id, pointing pending auto-matches at review_transfer" do+ outflow = create_transaction(account: @checking, amount: 120).transaction+ inflow = create_transaction(account: @card, amount: -120).transaction+ pending = Transfer.create!(outflow_transaction: outflow, inflow_transaction: inflow, status: "pending")++ result = @function.call("transaction_id" => outflow.id, "target_account_id" => @loan.id)++ assert_equal false, result[:success]+ assert_equal "already_linked", result[:error]+ assert_equal pending.id, result[:transfer][:transfer_id]+ assert_match "review_transfer", result[:message]+ end++ test "points a pending auto-match of the requested pair at confirming, not rejecting" do+ outflow = create_transaction(account: @checking, amount: 120).transaction+ inflow = create_transaction(account: @card, amount: -120).transaction+ pending = Transfer.create!(outflow_transaction: outflow, inflow_transaction: inflow, status: "pending")++ result = @function.call("transaction_id" => outflow.id, "counterpart_transaction_id" => inflow.id)++ assert_equal "pending_match", result[:error]+ assert_equal pending.id, result[:transfer][:transfer_id]+ assert_match "\"confirm\"", result[:message]+ assert_no_match(/Reject it/, result[:message])+ assert pending.reload.pending?+ assert_not RejectedTransfer.exists?(inflow_transaction_id: inflow.id, outflow_transaction_id: outflow.id)+ end++ test "requires exactly one of counterpart_transaction_id and target_account_id" do+ outflow = create_transaction(account: @checking, amount: 120).transaction++ [ {}, { "counterpart_transaction_id" => outflow.id, "target_account_id" => @loan.id } ].each do |extra|+ result = @function.call({ "transaction_id" => outflow.id }.merge(extra))+ assert_equal "invalid_arguments", result[:error]+ end+ end++ test "does not match into an account the user can only read" do+ # family_member has full control of the checking account but read-only on the card+ function = Assistant::Function::MatchTransfer.new(users(:family_member))+ outflow = create_transaction(account: @checking, amount: 120).transaction+ inflow = create_transaction(account: @card, amount: -120).transaction++ result = function.call("transaction_id" => outflow.id, "counterpart_transaction_id" => inflow.id)+ assert_equal "not_found", result[:error]++ result = function.call("transaction_id" => outflow.id, "target_account_id" => @card.id)+ assert_equal "account_not_found", result[:error]++ assert_nil outflow.reload.transfer+ end++ test "does not resolve another family's transaction" do+ outflow = create_transaction(account: @checking, amount: 120).transaction++ result = Assistant::Function::MatchTransfer.new(users(:josh)).call("transaction_id" => outflow.id, "target_account_id" => @loan.id)++ assert_equal "not_found", result[:error]+ end+enddiff --git a/test/models/assistant/function/review_transfer_test.rb b/test/models/assistant/function/review_transfer_test.rbnew file mode 100644index 0000000000..9af396d9e8--- /dev/null+++ b/test/models/assistant/function/review_transfer_test.rb@@ -0,0 +1,75 @@+require "test_helper"++class Assistant::Function::ReviewTransferTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @user = users(:family_admin)+ @function = Assistant::Function::ReviewTransfer.new(@user)+ @outflow = create_transaction(account: accounts(:depository), amount: 64).transaction+ @inflow = create_transaction(account: accounts(:other_asset), amount: -64).transaction+ @transfer = Transfer.create!(outflow_transaction: @outflow, inflow_transaction: @inflow, status: "pending")+ end++ test "confirms a pending transfer" do+ result = @function.call("transfer_id" => @transfer.id, "action" => "confirm")++ assert_equal true, result[:success]+ assert_equal "confirmed", result[:action]+ assert @transfer.reload.confirmed?+ assert_equal "funds_movement", @inflow.reload.kind+ assert_equal @outflow.reload.kind, result[:transfer][:outflow][:kind]+ assert_equal "funds_movement", result[:transfer][:inflow][:kind]+ end++ test "rejects a pending transfer and remembers the pairing" do+ result = assert_difference({ "Transfer.count" => -1, "RejectedTransfer.count" => 1 }) do+ @function.call("transfer_id" => @transfer.id, "action" => "reject")+ end++ assert_equal "rejected", result[:action]+ assert_nil @outflow.reload.transfer+ assert RejectedTransfer.exists?(outflow_transaction_id: @outflow.id, inflow_transaction_id: @inflow.id)+ end++ test "refuses a confirmed transfer" do+ @transfer.confirm!++ result = @function.call("transfer_id" => @transfer.id, "action" => "reject")++ assert_equal "not_pending", result[:error]+ assert Transfer.exists?(@transfer.id)+ end++ test "a review that lost a race to another review changes nothing" do+ # Loaded while pending, then confirmed by a concurrent request+ stale = Transfer.find(@transfer.id)+ @transfer.confirm!+ @function.stubs(:find_transfer).returns(stale)++ result = @function.call("transfer_id" => @transfer.id, "action" => "reject")++ assert_equal "not_pending", result[:error]+ assert Transfer.find(@transfer.id).confirmed?+ end++ test "refuses an unknown action" do+ result = @function.call("transfer_id" => @transfer.id, "action" => "delete")++ assert_equal "invalid_arguments", result[:error]+ end++ test "requires write access to both accounts" do+ # family_member has full control of the checking account but no share of other_asset+ result = Assistant::Function::ReviewTransfer.new(users(:family_member)).call("transfer_id" => @transfer.id, "action" => "confirm")++ assert_equal "not_found", result[:error]+ assert @transfer.reload.pending?+ end++ test "does not resolve another family's transfer" do+ result = Assistant::Function::ReviewTransfer.new(users(:josh)).call("transfer_id" => @transfer.id, "action" => "confirm")++ assert_equal "not_found", result[:error]+ end+enddiff --git a/test/models/transfer/matcher_test.rb b/test/models/transfer/matcher_test.rbnew file mode 100644index 0000000000..148085df8a--- /dev/null+++ b/test/models/transfer/matcher_test.rb@@ -0,0 +1,205 @@+require "test_helper"++class Transfer::MatcherTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:dylan_family)+ @checking = accounts(:depository)+ @card = accounts(:credit_card)+ @loan = accounts(:loan)+ @investment = accounts(:investment)+ end++ test "matches an outflow with an existing opposite transaction" do+ outflow = create_transaction(account: @checking, amount: 250, date: Date.current).transaction+ inflow = create_transaction(account: @card, amount: -250, date: 2.days.ago.to_date).transaction++ transfer = Transfer::Matcher.new(outflow).match_with!(inflow)++ assert transfer.persisted?+ assert transfer.confirmed?+ assert_equal outflow, transfer.outflow_transaction+ assert_equal inflow, transfer.inflow_transaction+ assert_equal 250, transfer.amount+ assert_equal "cc_payment", outflow.reload.kind+ assert_equal "funds_movement", inflow.reload.kind+ end++ test "matches from the inflow side too" do+ outflow = create_transaction(account: @checking, amount: 80).transaction+ inflow = create_transaction(account: @card, amount: -80).transaction++ transfer = Transfer::Matcher.new(inflow).match_with!(outflow)++ assert_equal outflow, transfer.outflow_transaction+ assert_equal inflow, transfer.inflow_transaction+ end++ test "creates the missing counterpart in a target account" do+ outflow = create_transaction(account: @checking, amount: 289.60, date: 3.days.ago.to_date).transaction++ transfer = assert_difference [ "Transfer.count", "Entry.count" ], 1 do+ Transfer::Matcher.new(outflow).match_to_account!(@loan)+ end++ inflow_entry = transfer.inflow_transaction.entry+ assert_equal @loan, inflow_entry.account+ assert_equal(-289.60, inflow_entry.amount)+ assert_equal outflow.entry.date, inflow_entry.date+ assert_equal "Transfer to #{@loan.name}", inflow_entry.name+ assert inflow_entry.user_modified?+ assert_equal "loan_payment", outflow.reload.kind+ end++ test "sets the investment contributions category on an uncategorized outflow" do+ outflow = create_transaction(account: @checking, amount: 500).transaction++ Transfer::Matcher.new(outflow).match_to_account!(@investment)++ outflow.reload+ assert_equal "investment_contribution", outflow.kind+ assert_equal @family.investment_contributions_category, outflow.category+ end++ test "keeps a category the user already set" do+ category = categories(:food_and_drink)+ outflow = create_transaction(account: @checking, amount: 500, category: category).transaction++ Transfer::Matcher.new(outflow).match_to_account!(@investment)++ assert_equal category, outflow.reload.category+ end++ test "dry run validates without saving" do+ outflow = create_transaction(account: @checking, amount: 40).transaction++ transfer = assert_no_difference [ "Transfer.count", "Entry.count" ] do+ Transfer::Matcher.new(outflow).match_to_account!(@loan, dry_run: true)+ end++ assert transfer.new_record?+ assert_equal "standard", outflow.reload.kind+ end++ test "rejects a counterpart that is not a match candidate" do+ outflow = create_transaction(account: @checking, amount: 100).transaction+ wrong_amount = create_transaction(account: @card, amount: -99).transaction+ too_far = create_transaction(account: @card, amount: -100, date: 40.days.ago.to_date).transaction++ [ wrong_amount, too_far ].each do |counterpart|+ error = assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(outflow).match_with!(counterpart) }+ assert_equal :not_a_candidate, error.code+ end++ assert_nil outflow.reload.transfer+ end++ test "refuses a transaction that is already in a transfer, including a pending auto-match" do+ outflow = create_transaction(account: @checking, amount: 100).transaction+ inflow = create_transaction(account: @card, amount: -100).transaction+ Transfer.create!(outflow_transaction: outflow, inflow_transaction: inflow, status: "pending")++ error = assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(outflow).match_to_account!(@loan) }+ assert_equal :already_linked, error.code+ end++ test "refuses a transaction another match linked after it was loaded" do+ outflow = create_transaction(account: @checking, amount: 100).transaction+ inflow = create_transaction(account: @card, amount: -100).transaction+ stale = Transaction.find(outflow.id)+ assert_nil stale.transfer # loaded before the other match++ Transfer::Matcher.new(outflow).match_with!(inflow)++ error = assert_no_difference "Transfer.count" do+ assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(stale).match_to_account!(@loan) }+ end+ assert_equal :already_linked, error.code+ end++ test "locks both transactions before saving the transfer" do+ outflow = create_transaction(account: @checking, amount: 100).transaction+ inflow = create_transaction(account: @card, amount: -100).transaction+ sql = []+ callback = ->(*, payload) { sql << payload[:sql] }++ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do+ Transfer::Matcher.new(outflow).match_with!(inflow)+ end++ lock = sql.index { |q| q.include?("FOR UPDATE") && q.include?('"transactions"') }+ entry_lock = sql.index { |q| q.include?("FOR UPDATE") && q.include?('"entries"') }+ insert = sql.index { |q| q.start_with?('INSERT INTO "transfers"') }+ assert lock, "expected the transactions to be locked"+ assert entry_lock, "expected their entries to be locked"+ assert_operator lock, :<, insert+ assert_operator entry_lock, :<, insert+ end++ test "checks the transaction as committed, not as it was loaded" do+ outflow = create_transaction(account: @checking, amount: 100).transaction+ stale = Transaction.find(outflow.id)+ stale.entry # loaded before the exclusion+ outflow.entry.update!(excluded: true)++ error = assert_no_difference "Transfer.count" do+ assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(stale).match_to_account!(@loan) }+ end+ assert_equal :excluded_transaction, error.code+ end++ test "re-checks the pair against the counterpart's committed amount" do+ outflow = create_transaction(account: @checking, amount: 100).transaction+ inflow = create_transaction(account: @card, amount: -100).transaction+ stale = Transaction.find(inflow.id)+ stale.entry # loaded while it still matched+ inflow.entry.update!(amount: -250)++ error = assert_no_difference "Transfer.count" do+ assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(outflow).match_with!(stale) }+ end+ assert_equal :not_a_candidate, error.code+ end++ test "refuses excluded and split transactions" do+ excluded = create_transaction(account: @checking, amount: 100, excluded: true).transaction+ error = assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(excluded).match_to_account!(@loan) }+ assert_equal :excluded_transaction, error.code++ split = create_transaction(account: @checking, amount: 100).transaction+ Entry.any_instance.stubs(:split_parent?).returns(true)+ error = assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(split).match_to_account!(@loan) }+ assert_equal :split_transaction, error.code+ end++ test "refuses the transaction's own account and another family's account" do+ outflow = create_transaction(account: @checking, amount: 100).transaction++ error = assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(outflow).match_to_account!(@checking) }+ assert_equal :same_account, error.code++ other_family_account = families(:empty).accounts.create!(name: "Elsewhere", balance: 0, currency: "USD", accountable: Depository.new)+ error = assert_raises(Transfer::Matcher::Error) { Transfer::Matcher.new(outflow).match_to_account!(other_family_account) }+ assert_equal :account_not_found, error.code+ end++ test "does not offer split children as candidates, or candidates for one" do+ parent = create_transaction(account: @card, amount: -100)+ children = parent.split!([ { name: "Part A", amount: -60 }, { name: "Part B", amount: -40 } ])+ outflow = create_transaction(account: @checking, amount: 60).transaction++ assert_empty Transfer::Matcher.new(outflow).candidates+ assert_empty Transfer::Matcher.new(children.first.entryable).candidates+ end++ test "lists candidates with the manual dialog's 30 day window" do+ outflow = create_transaction(account: @checking, amount: 75, date: Date.current).transaction+ near = create_transaction(account: @card, amount: -75, date: 20.days.ago.to_date).transaction+ create_transaction(account: @card, amount: -75, date: 45.days.ago.to_date)++ ids = Transfer::Matcher.new(outflow).candidates.map(&:inflow_transaction_id)++ assert_equal [ near.id ], ids+ end+end