The personal finance app for everyone (by everyone)
Ruby
feat(mcp): add set_opening_balance tool (#3820)
scragnog6b6a27e1c470
diff --git a/app/models/account/opening_balance_manager.rb b/app/models/account/opening_balance_manager.rbindex 3ad6818e06..c7f677207c 100644--- a/app/models/account/opening_balance_manager.rb+++ b/app/models/account/opening_balance_manager.rb@@ -23,47 +23,69 @@ class Account::OpeningBalanceManageropening_anchor_valuation&.entry&.amount || 0end+ # Serialized per account, so concurrent calls (e.g. an assistant retrying)+ # can't both see "no anchor" and create two. Uncached so the reads under+ # the lock can't be served from a query cache filled before another+ # request committed its anchor.def set_opening_balance(balance:, date: nil)- resolved_date = date || default_date+ Account.uncached do+ Account.transaction do+ lock_account!++ if (error = date_error(date))+ Result.new(success?: false, changes_made?: false, error: error)+ elsif opening_anchor_valuation.nil?+ create_opening_anchor(+ balance: balance,+ date: date || default_date+ )+ Result.new(success?: true, changes_made?: true, error: nil)+ else+ changes_made = update_opening_anchor(balance: balance, date: date)+ Result.new(success?: true, changes_made?: changes_made, error: nil)+ end+ end+ end+ end++ # The validation set_opening_balance applies to an explicit date, without+ # writing anything. Returns an error message, or nil when the date is valid.+ def date_error(date)+ return nil unless date && oldest_entry_date && date >= oldest_entry_date- # Validate date is before oldest entry- if date && oldest_entry_date && resolved_date >= oldest_entry_date- return Result.new(success?: false, changes_made?: false, error: "Opening balance date must be before the oldest entry date")+ "Opening balance date must be before the oldest entry date"+ end++ # The date the opening balance must precede, if the account has other entries.+ def oldest_entry_date+ if opening_anchor_valuation&.entry+ account.entries.where.not(id: opening_anchor_valuation.entry.id).minimum(:date)+ else+ account.entries.minimum(:date)end+ end- if opening_anchor_valuation.nil?- create_opening_anchor(- balance: balance,- date: resolved_date- )- Result.new(success?: true, changes_made?: true, error: nil)+ # Used when a new opening balance is set without a date.+ def default_date+ if oldest_entry_date+ [ oldest_entry_date - 1.day, 2.years.ago.to_date ].minelse- changes_made = update_opening_anchor(balance: balance, date: date)- Result.new(success?: true, changes_made?: changes_made, error: nil)+ 2.years.ago.to_dateendendprivateattr_reader :account- def opening_anchor_valuation- @opening_anchor_valuation ||= account.valuations.opening_anchor.includes(:entry).first+ # Row lock only: callers may hold unsaved changes on the account, which+ # with_lock would reload (or refuse). Re-read the anchor under the lock.+ def lock_account!+ Account.where(id: account.id).lock.pick(:id)+ @opening_anchor_valuation = nilend- def oldest_entry_date- if opening_anchor_valuation&.entry- account.entries.where.not(id: opening_anchor_valuation.entry.id).minimum(:date)- else- account.entries.minimum(:date)- end- end-- def default_date- if oldest_entry_date- [ oldest_entry_date - 1.day, 2.years.ago.to_date ].min- else- 2.years.ago.to_date- end+ def opening_anchor_valuation+ @opening_anchor_valuation ||= account.valuations.opening_anchor.includes(:entry).firstenddef create_opening_anchor(balance:, date:)diff --git a/app/models/assistant.rb b/app/models/assistant.rbindex 30c2d4bc70..f1eb763e92 100644--- a/app/models/assistant.rb+++ b/app/models/assistant.rb@@ -65,6 +65,7 @@ module AssistantFunction::ImportBankStatement,Function::SearchFamilyFiles,Function::CreateGoal,+ Function::SetOpeningBalance,Function::GetTags,Function::CreateTag,Function::UpdateTag,diff --git a/app/models/assistant/function/set_opening_balance.rb b/app/models/assistant/function/set_opening_balance.rbnew file mode 100644index 0000000000..b4e63b98a7--- /dev/null+++ b/app/models/assistant/function/set_opening_balance.rb@@ -0,0 +1,155 @@+# frozen_string_literal: true++# SetOpeningBalance — sets a manual account's opening balance and/or the date+# it applies from, through Account#set_opening_anchor_balance (the same+# Account::OpeningBalanceManager path used when an account is created).+#+# The date must be before the account's oldest entry. The response says what+# happens to the current balance: a later balance update (reconciliation)+# fixes it, otherwise it moves by the same amount as the opening balance.+class Assistant::Function::SetOpeningBalance < Assistant::Function+ class << self+ def name+ "set_opening_balance"+ end++ def description+ <<~INSTRUCTIONS+ Sets the opening balance of a manual account (one not synced from a+ bank or other provider) and, optionally, the date it applies from.+ Use it when an account's history starts on the wrong date or from the+ wrong amount, e.g. a loan whose first repayment predates its opening+ balance, or a savings account that opened at zero.++ balance uses the same sign convention as get_accounts (a loan's+ outstanding amount is positive). date must be before the account's+ oldest entry; omit it to keep the current opening date.++ The result says whether the current balance changes: if the account has+ a later balance update, only the history before it changes. Pass+ dry_run: true to see the effect without changing anything.+ INSTRUCTIONS+ end+ end++ def strict_mode?+ false+ end++ def params_schema+ build_schema(+ required: %w[account_id balance],+ properties: {+ account_id: {+ type: "string",+ description: "Manual account ID from get_accounts."+ },+ balance: {+ type: "number",+ description: "Opening balance in the account's currency."+ },+ date: {+ type: "string",+ description: "Date the opening balance applies from (YYYY-MM-DD), before the account's oldest entry. Omit to keep the current date."+ },+ dry_run: {+ type: "boolean",+ description: "Describe the change without making it. Defaults to false."+ }+ }+ )+ end++ def call(params = {})+ account = find_account(params["account_id"])+ return error("not_found", "No account with id '#{params["account_id"]}' that you can write to.") unless account+ return error("linked_account", "#{account.name} is synced from a provider, which manages its balances. Only manual accounts have an editable opening balance.") if account.linked?++ balance = parse_balance(params["balance"])+ return error("invalid_balance", "balance must be a number.") unless balance++ date = nil+ # A supplied blank date is an error, not "keep the current date".+ unless params["date"].nil?+ date = parse_date(params["date"])+ return error("invalid_date", "date must be YYYY-MM-DD.") unless date+ end++ manager = Account::OpeningBalanceManager.new(account)+ if (message = manager.date_error(date))+ return error("invalid_date", "#{message} (#{manager.oldest_entry_date}).", oldest_entry_date: manager.oldest_entry_date)+ end++ before = opening(account, manager)+ new_date = date || before&.dig(:date) || manager.default_date+ after = { date: new_date, balance: balance.to_s }+ effect = current_balance_effect(account, new_date, balance - (before ? BigDecimal(before[:balance]) : 0))++ if ActiveModel::Type::Boolean.new.cast(params["dry_run"])+ return { success: true, dry_run: true, account: account_summary(account), before: before, after: after, current_balance: effect }+ end++ result = account.set_opening_anchor_balance(balance: balance, date: date)+ return error("update_failed", result.error) unless result.success?++ {+ success: true,+ changed: result.changes_made?,+ account: account_summary(account),+ before: before,+ after: after,+ current_balance: effect+ }+ end++ private+ def find_account(id)+ return nil unless valid_uuid?(id)++ family.accounts.visible.writable_by(user).find_by(id: id)+ end++ def opening(account, manager)+ return nil unless manager.has_opening_anchor?++ { date: manager.opening_date, balance: manager.opening_balance.to_s }+ end++ # Reconciliations after the opening date pin the balance from that point on.+ def current_balance_effect(account, new_date, delta)+ pinned_by = account.entries.valuations+ .joins("JOIN valuations ON valuations.id = entries.entryable_id")+ .where(valuations: { kind: "reconciliation" })+ .where("entries.date > ?", new_date)+ .minimum(:date)++ if pinned_by+ { changes: false, reason: "The balance update on #{pinned_by} fixes the balance from that date, so only the history before it changes." }+ elsif delta.zero?+ { changes: false, reason: "The opening balance amount is unchanged." }+ else+ { changes: true, by: delta.to_s, reason: "No later balance update, so the current balance moves by the same amount as the opening balance." }+ end+ end++ def account_summary(account)+ { id: account.id, name: account.name, currency: account.currency }+ end++ def parse_balance(value)+ return nil if value.nil? || value.is_a?(TrueClass) || value.is_a?(FalseClass)++ number = BigDecimal(value.to_s, exception: false)+ number if number&.finite?+ end++ def parse_date(value)+ Date.iso8601(value.to_s)+ rescue ArgumentError+ nil+ end++ def error(key, message, **details)+ { success: false, error: key, message: message, **details }+ end+enddiff --git a/docs/hosting/mcp.md b/docs/hosting/mcp.mdindex b08c1d64d2..35483795aa 100644--- a/docs/hosting/mcp.md+++ b/docs/hosting/mcp.md@@ -146,6 +146,7 @@ At the time of writing, `tools/list` includes:| `get_tags` | Tags with pagination || `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` || `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/controllers/mcp_controller_test.rb b/test/controllers/mcp_controller_test.rbindex 72b94747a9..4f9fcf7ffb 100644--- a/test/controllers/mcp_controller_test.rb+++ b/test/controllers/mcp_controller_test.rb@@ -314,6 +314,7 @@ class McpControllerTest < ActionDispatch::IntegrationTestassert_includes tool_names, "get_transactions"assert_includes tool_names, "get_accounts"assert_includes tool_names, "get_holdings"+ assert_includes tool_names, "set_opening_balance"assert_includes tool_names, "get_balance_sheet"assert_includes tool_names, "get_income_statement"assert_includes tool_names, "update_transaction"diff --git a/test/models/account/opening_balance_manager_test.rb b/test/models/account/opening_balance_manager_test.rbindex 78411bd00d..fd19559e91 100644--- a/test/models/account/opening_balance_manager_test.rb+++ b/test/models/account/opening_balance_manager_test.rb@@ -298,6 +298,18 @@ class Account::OpeningBalanceManagerTest < ActiveSupport::TestCaseassert_nil @depository_account.valuations.opening_anchor.firstend+ test "date_error checks a date without writing" do+ oldest_date = 60.days.ago.to_date+ @depository_account.entries.create!(date: oldest_date, name: "Test transaction", amount: 100, currency: "USD", entryable: Transaction.new)+ manager = Account::OpeningBalanceManager.new(@depository_account)++ assert_nil manager.date_error(nil)+ assert_nil manager.date_error(oldest_date - 1.day)+ assert_equal "Opening balance date must be before the oldest entry date", manager.date_error(oldest_date)+ assert_equal oldest_date, manager.oldest_entry_date+ assert_nil @depository_account.valuations.opening_anchor.first+ end+test "when no changes made, returns success with no changes made" do# First create an opening anchormanager = Account::OpeningBalanceManager.new(@depository_account)@@ -318,4 +330,19 @@ class Account::OpeningBalanceManagerTest < ActiveSupport::TestCaseassert_not result.changes_made?assert_nil result.errorend++ test "locks the account row before reading the opening anchor" do+ sql = []+ callback = ->(*, payload) { sql << payload[:sql] }++ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do+ Account::OpeningBalanceManager.new(@depository_account).set_opening_balance(balance: 100, date: 1.year.ago.to_date)+ end++ lock = sql.index { |q| q.include?("FOR UPDATE") && q.include?('"accounts"') }+ anchor_read = sql.index { |q| q.match?(/"valuations"."kind"/) }+ assert lock, "expected the account row to be locked"+ assert anchor_read, "expected the opening anchor to be read"+ assert_operator lock, :<, anchor_read+ endenddiff --git a/test/models/assistant/function/set_opening_balance_test.rb b/test/models/assistant/function/set_opening_balance_test.rbnew file mode 100644index 0000000000..9c81cbcadc--- /dev/null+++ b/test/models/assistant/function/set_opening_balance_test.rb@@ -0,0 +1,110 @@+require "test_helper"++class Assistant::Function::SetOpeningBalanceTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @user = users(:family_admin)+ @function = Assistant::Function::SetOpeningBalance.new(@user)+ @account = families(:dylan_family).accounts.create!(+ name: "Manual savings", balance: 0, currency: "USD", accountable: Depository.new, owner: @user+ )+ @account.set_opening_anchor_balance(balance: 500, date: 30.days.ago.to_date)+ create_transaction(account: @account, amount: -10_000, date: 20.days.ago.to_date)+ end++ test "moves the opening balance and date" do+ result = @function.call("account_id" => @account.id, "balance" => 0, "date" => 25.days.ago.to_date.iso8601)++ assert_equal true, result[:success]+ assert_equal true, result[:changed]+ assert_equal({ date: 30.days.ago.to_date, balance: "500.0" }, result[:before])+ assert_equal 25.days.ago.to_date, result[:after][:date]++ anchor = @account.valuations.opening_anchor.first.entry+ assert_equal 0, anchor.amount+ assert_equal 25.days.ago.to_date, anchor.date+ end++ test "keeps the current date when none is given" do+ @function.call("account_id" => @account.id, "balance" => 750)++ anchor = @account.valuations.opening_anchor.first.entry+ assert_equal 750, anchor.amount+ assert_equal 30.days.ago.to_date, anchor.date+ end++ test "reports that the current balance moves when nothing later fixes it" do+ result = @function.call("account_id" => @account.id, "balance" => 0, "dry_run" => true)++ assert_equal true, result[:current_balance][:changes]+ assert_equal "-500.0", result[:current_balance][:by]+ end++ test "reports that a later balance update fixes the current balance" do+ Account::ReconciliationManager.new(@account).reconcile_balance(balance: 9_000, date: 5.days.ago.to_date)++ result = @function.call("account_id" => @account.id, "balance" => 0, "dry_run" => true)++ assert_equal false, result[:current_balance][:changes]+ assert_match 5.days.ago.to_date.to_s, result[:current_balance][:reason]+ end++ test "dry run changes nothing" do+ result = assert_no_difference "Entry.count" do+ @function.call("account_id" => @account.id, "balance" => 0, "date" => 25.days.ago.to_date.iso8601, "dry_run" => true)+ end++ assert_equal true, result[:dry_run]+ assert_equal 500, @account.valuations.opening_anchor.first.entry.amount+ end++ test "creates an opening balance when the account has none" do+ account = families(:dylan_family).accounts.create!(+ name: "No anchor", balance: 0, currency: "USD", accountable: Depository.new, owner: @user+ )++ result = @function.call("account_id" => account.id, "balance" => 0, "date" => 10.days.ago.to_date.iso8601)++ assert_equal true, result[:success]+ assert_nil result[:before]+ assert_equal 0, account.valuations.opening_anchor.first.entry.amount+ end++ test "rejects a date on or after the oldest entry, naming that date" do+ result = @function.call("account_id" => @account.id, "balance" => 0, "date" => 20.days.ago.to_date.iso8601)++ assert_equal false, result[:success]+ assert_equal "invalid_date", result[:error]+ assert_equal 20.days.ago.to_date, result[:oldest_entry_date]+ assert_equal 500, @account.valuations.opening_anchor.first.entry.amount+ end++ test "validates balance and date" do+ assert_equal "invalid_balance", @function.call("account_id" => @account.id, "balance" => "lots")[:error]+ assert_equal "invalid_balance", @function.call("account_id" => @account.id, "balance" => true)[:error]+ assert_equal "invalid_date", @function.call("account_id" => @account.id, "balance" => 0, "date" => "28/09/2026")[:error]+ end++ test "rejects a blank date instead of keeping the current one" do+ result = @function.call("account_id" => @account.id, "balance" => 900, "date" => "")++ assert_equal "invalid_date", result[:error]+ assert_equal 500, @account.opening_anchor_balance+ end++ test "refuses accounts synced from a provider" do+ result = @function.call("account_id" => accounts(:connected).id, "balance" => 0)++ assert_equal "linked_account", result[:error]+ end++ test "refuses accounts the user can only read, and other families' accounts" do+ # family_member has a read-only share of the credit card+ result = Assistant::Function::SetOpeningBalance.new(users(:family_member)).call("account_id" => accounts(:credit_card).id, "balance" => 0)+ assert_equal "not_found", result[:error]++ result = Assistant::Function::SetOpeningBalance.new(users(:josh)).call("account_id" => @account.id, "balance" => 0)+ assert_equal "not_found", result[:error]+ end+end