The personal finance app for everyone (by everyone)
Ruby
feat(mcp): add unmatch_transfer tool (#4157)
scragnog12e21f778c92
diff --git a/app/models/assistant.rb b/app/models/assistant.rbindex 2f74cfe3fc..f12c2f39f9 100644--- a/app/models/assistant.rb+++ b/app/models/assistant.rb@@ -66,6 +66,7 @@ module AssistantFunction::SearchFamilyFiles,Function::CreateGoal,Function::SetOpeningBalance,+ Function::UnmatchTransfer,Function::GetTags,Function::CreateTag,Function::UpdateTag,diff --git a/app/models/assistant/function/unmatch_transfer.rb b/app/models/assistant/function/unmatch_transfer.rbnew file mode 100644index 0000000000..0d0a4399de--- /dev/null+++ b/app/models/assistant/function/unmatch_transfer.rb@@ -0,0 +1,180 @@+# frozen_string_literal: true++# UnmatchTransfer — unlinks a transfer between two of the family's+# transactions, confirmed or pending, so a wrong match can be undone (e.g. a+# card payment paired with the account that funded it rather than the one that+# paid it). Both transactions stay in the ledger; a confirmed transfer's+# become standard transactions again (a pending match never changed their+# kinds, so those stay). Balances don't change.+#+# By default it rejects the pairing (Transfer#reject!, the Reject button), so+# auto-match won't suggest it again. reject: false only unlinks+# (Transfer#destroy!, as TransfersController#destroy does).+#+# Transfer fee transactions belong to the transfer and are deleted with it, as+# in the UI; the result lists them and the affected accounts are resynced.+class Assistant::Function::UnmatchTransfer < Assistant::Function+ class << self+ def name+ "unmatch_transfer"+ end++ def description+ <<~INSTRUCTIONS+ Unlinks a transfer (or a credit card or loan payment) between two of+ the user's accounts, so its two transactions count as ordinary income+ and spending again. Use it to undo a wrong match: the transactions are+ kept, and can then be matched with the right counterparts.++ Pass the id of either transaction in the transfer (get_transactions+ marks them is_transfer), or the transfer_id. Works on confirmed and+ pending transfers. Both accounts must be writable.++ By default the pairing is also recorded as rejected, so Sure's+ auto-match won't suggest it again; pass reject: false to only unlink.+ Fee transactions attached to the transfer are deleted with it (listed+ in the result). Pass dry_run: true to see the effect first.+ INSTRUCTIONS+ end+ end++ def strict_mode?+ false+ end++ def params_schema+ build_schema(+ properties: {+ transaction_id: {+ type: "string",+ description: "ID of either transaction in the transfer, from get_transactions. Omit when passing transfer_id."+ },+ transfer_id: {+ type: "string",+ description: "Transfer ID. Omit when passing transaction_id."+ },+ reject: {+ type: "boolean",+ description: "Also stop auto-match from suggesting this pairing again. Defaults to true."+ },+ dry_run: {+ type: "boolean",+ description: "Describe the change without making it. Defaults to false."+ }+ }+ )+ end++ def call(params = {})+ if params["transaction_id"].present? == params["transfer_id"].present?+ return error("invalid_arguments", "Pass exactly one of transaction_id or transfer_id.")+ end++ transfer = params["transfer_id"].present? ? find_transfer(params["transfer_id"]) : find_transfer_for_transaction(params["transaction_id"])+ unless transfer+ ref = params["transfer_id"].presence || params["transaction_id"]+ return error("not_found", "No transfer for '#{ref}' between accounts you can write to.")+ end++ # Only an explicit false skips the rejection; null counts as omitted.+ reject = params["reject"].nil? || ActiveModel::Type::Boolean.new.cast(params["reject"])++ if ActiveModel::Type::Boolean.new.cast(params["dry_run"])+ snapshot = serialize_transfer(transfer)+ return { success: true, dry_run: true, reject: reject, transfer: snapshot, message: "Would unlink #{snapshot[:name]}." }+ end++ # Lock, then re-find within the writable scope: two concurrent calls can't+ # both act on the transfer, a fee attached meanwhile is reported, and+ # write access lost since the lookup is caught.+ snapshot = accounts = nil+ unmatched = Transfer.uncached do+ Transfer.transaction do+ locked = scoped_transfers.lock.find_by(id: transfer.id)+ next false unless locked++ snapshot = serialize_transfer(locked)+ accounts = ([ locked.from_account, locked.to_account ] + locked.fee_transactions.map { |t| t.entry.account }).compact.uniq+ reject ? locked.reject! : locked.destroy!+ true+ end+ end+ return error("not_found", "The transfer was already unlinked, or you can no longer write to its accounts.") unless unmatched++ # A pending match never changed the kinds, so report what they are now.+ kinds = Transaction.where(id: [ snapshot[:outflow][:id], snapshot[:inflow][:id] ]).pluck(:id, :kind).to_h+ snapshot[:outflow][:kind_after] = kinds[snapshot[:outflow][:id]]+ snapshot[:inflow][:kind_after] = kinds[snapshot[:inflow][:id]]++ response = {+ success: true,+ unmatched: true,+ rejected: reject,+ transfer: snapshot,+ message: "Unlinked #{snapshot[:name]}. Outflow kind is now #{snapshot[:outflow][:kind_after]}, inflow kind #{snapshot[:inflow][:kind_after]}."+ }++ # Best-effort: the unlink has already committed.+ if snapshot[:deleted_fee_transactions].any?+ begin+ accounts.each(&:sync_later)+ rescue StandardError => e+ response[:warning] = "Transfer unlinked, but the account sync for the deleted fees could not be enqueued (#{e.class}). Balances will recalculate on the next sync."+ end+ end++ response+ end++ private+ def writable_transactions+ family.transactions.joins(entry: :account).merge(Account.writable_by(user))+ end++ def scoped_transfers+ ids = writable_transactions.select(:id)+ Transfer.where(inflow_transaction_id: ids).where(outflow_transaction_id: ids)+ end++ def find_transfer(id)+ return nil unless valid_uuid?(id)++ scoped_transfers.find_by(id: id)+ end++ def find_transfer_for_transaction(id)+ return nil unless valid_uuid?(id)++ scoped_transfers.where("inflow_transaction_id = :id OR outflow_transaction_id = :id", id: id).first+ end++ def serialize_transfer(transfer)+ {+ id: transfer.id,+ name: transfer.name,+ status: transfer.status,+ outflow: serialize_transaction(transfer.outflow_transaction),+ inflow: serialize_transaction(transfer.inflow_transaction),+ deleted_fee_transactions: transfer.fee_transactions.map { |t| serialize_transaction(t) }+ }+ end++ def serialize_transaction(transaction)+ entry = transaction.entry+ {+ 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: entry.amount_money.abs.format,+ currency: entry.currency,+ kind: transaction.kind+ }+ end++ def error(key, message)+ { success: false, error: key, message: message }+ end+enddiff --git a/docs/hosting/ai.md b/docs/hosting/ai.mdindex 8ff404a8f5..329cc7d60e 100644--- a/docs/hosting/ai.md+++ b/docs/hosting/ai.md@@ -1463,6 +1463,7 @@ Read and analysis:Write:- `update_transaction`, `update_budget`, `create_goal`+- `unmatch_transfer` - Unlink a wrongly matched transfer- `create_tag` / `update_tag`, `create_category` / `update_category`Documents:diff --git a/docs/hosting/mcp.md b/docs/hosting/mcp.mdindex b1fca8716f..fa9b5681c8 100644--- a/docs/hosting/mcp.md+++ b/docs/hosting/mcp.md@@ -147,6 +147,7 @@ At the time of writing, `tools/list` includes:| `get_categories` | Categories with hierarchy and pagination || `create_goal` | Create a savings goal linked to depository accounts || `set_opening_balance` | Set a manual account's opening balance and the date it applies from, reporting whether the current balance changes. Supports `dry_run` |+| `unmatch_transfer` | Unlink a confirmed or pending transfer (by either transaction's id) so a wrong match can be redone; rejects the pairing for auto-match by default. Supports `dry_run` || `create_tag` / `update_tag` | Manage tags || `create_category` / `update_category` | Manage categories || `update_transaction` | Edit a transaction's metadata (name, notes, category, merchant, tags) |diff --git a/test/models/assistant/function/unmatch_transfer_test.rb b/test/models/assistant/function/unmatch_transfer_test.rbnew file mode 100644index 0000000000..7bcecaf0f3--- /dev/null+++ b/test/models/assistant/function/unmatch_transfer_test.rb@@ -0,0 +1,144 @@+require "test_helper"++class Assistant::Function::UnmatchTransferTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @user = users(:family_admin)+ @function = Assistant::Function::UnmatchTransfer.new(@user)+ @transfer = create_transfer(from_account: accounts(:depository), to_account: accounts(:credit_card), amount: 250)+ @transfer.outflow_transaction.update!(kind: "cc_payment")+ end++ test "is registered for the assistant and MCP" do+ assert_includes Assistant.function_classes(@user), Assistant::Function::UnmatchTransfer+ end++ test "unmatches a confirmed transfer by either transaction and rejects the pairing" do+ outflow = @transfer.outflow_transaction+ inflow = @transfer.inflow_transaction++ result = @function.call("transaction_id" => inflow.id)++ assert result[:success]+ assert result[:unmatched]+ assert result[:rejected]+ assert_equal "confirmed", result[:transfer][:status]+ assert_equal outflow.id, result[:transfer][:outflow][:id]+ assert_equal "cc_payment", result[:transfer][:outflow][:kind]++ assert_nil Transfer.find_by(id: @transfer.id)+ assert_equal "standard", outflow.reload.kind+ assert_equal "standard", inflow.reload.kind+ assert_equal "standard", result[:transfer][:outflow][:kind_after]+ assert_equal "standard", result[:transfer][:inflow][:kind_after]+ assert RejectedTransfer.exists?(inflow_transaction_id: inflow.id, outflow_transaction_id: outflow.id)+ end++ test "reject false only unlinks" do+ result = @function.call("transfer_id" => @transfer.id, "reject" => false)++ assert result[:success]+ assert_equal false, result[:rejected]+ assert_nil Transfer.find_by(id: @transfer.id)+ assert_not RejectedTransfer.exists?(inflow_transaction_id: @transfer.inflow_transaction_id)+ end++ test "a null reject rejects the pairing, like an omitted one" do+ result = @function.call("transfer_id" => @transfer.id, "reject" => nil)++ assert result[:success]+ assert_equal true, result[:rejected]+ assert RejectedTransfer.exists?(inflow_transaction_id: @transfer.inflow_transaction_id)+ end++ test "unmatches a pending auto-match" do+ @transfer.update!(status: "pending")++ result = @function.call("transaction_id" => @transfer.outflow_transaction_id)++ assert result[:success]+ assert_equal "pending", result[:transfer][:status]+ assert_nil Transfer.find_by(id: @transfer.id)++ # A pending match never changed the kinds, so a kind set before it stays.+ assert_equal "cc_payment", @transfer.outflow_transaction.reload.kind+ assert_equal "cc_payment", result[:transfer][:outflow][:kind_after]+ assert_includes result[:message], "Outflow kind is now cc_payment"+ end++ test "dry run changes nothing" do+ assert_no_difference [ "Transfer.count", "RejectedTransfer.count" ] do+ result = @function.call("transfer_id" => @transfer.id, "dry_run" => true)++ assert result[:success]+ assert result[:dry_run]+ assert_equal @transfer.id, result[:transfer][:id]+ end++ assert_equal "cc_payment", @transfer.outflow_transaction.reload.kind+ end++ test "lists and deletes fee transactions, like the UI" do+ transfer = create_transfer(from_account: accounts(:depository), to_account: accounts(:investment), amount: 100)+ fee = create_transaction(account: accounts(:depository), name: "Transfer fee", amount: 2).entryable+ fee_entry_id = fee.entry.id+ transfer.fee_transactions << fee++ result = @function.call("transfer_id" => transfer.id, "reject" => false)++ assert result[:success]+ assert_equal [ fee.id ], result[:transfer][:deleted_fee_transactions].map { |t| t[:id] }+ assert_nil Transaction.find_by(id: fee.id)+ assert_nil Entry.find_by(id: fee_entry_id)+ end++ test "reports success with a warning when the fee resync can't be enqueued" do+ transfer = create_transfer(from_account: accounts(:depository), to_account: accounts(:investment), amount: 100)+ transfer.fee_transactions << create_transaction(account: accounts(:depository), name: "Transfer fee", amount: 2).entryable+ Account.any_instance.stubs(:sync_later).raises(StandardError, "queue down")++ result = @function.call("transfer_id" => transfer.id)++ assert result[:success]+ assert_match "could not be enqueued", result[:warning]+ assert_nil Transfer.find_by(id: transfer.id)+ end++ test "requires exactly one of transaction_id or transfer_id" do+ assert_equal "invalid_arguments", @function.call({})[:error]+ assert_equal "invalid_arguments", @function.call("transfer_id" => @transfer.id, "transaction_id" => @transfer.inflow_transaction_id)[:error]+ end++ test "returns not_found for a transaction that is not in a transfer" do+ result = @function.call("transaction_id" => transactions(:one).id)++ assert_equal "not_found", result[:error]+ end++ test "returns not_found unless both accounts are writable" do+ # family_member has a read-only share of the credit card+ result = Assistant::Function::UnmatchTransfer.new(users(:family_member)).call("transfer_id" => @transfer.id)++ assert_equal "not_found", result[:error]+ assert Transfer.exists?(@transfer.id)+ end++ test "rechecks write access under the lock" do+ # As if the lookup had passed before the read-only share took effect.+ function = Assistant::Function::UnmatchTransfer.new(users(:family_member))+ function.stubs(:find_transfer).returns(@transfer)++ result = function.call("transfer_id" => @transfer.id)++ assert_equal "not_found", result[:error]+ assert Transfer.exists?(@transfer.id)+ end++ test "returns not_found for another family's user" do+ result = Assistant::Function::UnmatchTransfer.new(users(:empty)).call("transfer_id" => @transfer.id)++ assert_equal "not_found", result[:error]+ assert Transfer.exists?(@transfer.id)+ end+end