The personal finance app for everyone (by everyone)
Ruby
fix(ibkr): anchor the balance on the statement's date, not on today (#3815)
Daniel Garcia Sardina3366ac223421
diff --git a/app/models/account/anchorable.rb b/app/models/account/anchorable.rbindex 5dc3261e4a..1f60534636 100644--- a/app/models/account/anchorable.rb+++ b/app/models/account/anchorable.rb@@ -39,10 +39,12 @@ module Account::Anchorableendend+ # `date` is the day the balance describes, for a provider whose figures are+ # as of a statement rather than of this moment; it defaults to today.# Pass schedule_sync: false when the caller schedules the account sync# itself, such as a provider sync that syncs its accounts afterwards.- def set_current_balance(balance, schedule_sync: true)- result = current_balance_manager.set_current_balance(balance)+ def set_current_balance(balance, date: nil, schedule_sync: true)+ result = current_balance_manager.set_current_balance(balance, date: date)sync_later if schedule_sync && result.success?resultenddiff --git a/app/models/account/current_balance_manager.rb b/app/models/account/current_balance_manager.rbindex b01c2f26a8..b25c59d65b 100644--- a/app/models/account/current_balance_manager.rb+++ b/app/models/account/current_balance_manager.rb@@ -1,7 +1,10 @@class Account::CurrentBalanceManagerInvalidOperation = Class.new(StandardError)- Result = Struct.new(:success?, :changes_made?, :error, keyword_init: true)+ # `historical?` marks the statement as older than the anchor: it was recorded+ # behind the current balance, which nothing about the account as it stands now+ # should follow.+ Result = Struct.new(:success?, :changes_made?, :error, :historical?, keyword_init: true)def initialize(account)@account = account@@ -30,17 +33,21 @@ class Account::CurrentBalanceManagerendend- def set_current_balance(balance)+ # `date` is the day the balance describes, for a provider whose figures are+ # as of a statement rather than of this moment. It only applies to a linked+ # account: a manual one has no statement, and its strategies reconcile against+ # today by design.+ def set_current_balance(balance, date: nil)if account.linked?- result = set_current_balance_for_linked_account(balance)+ set_current_balance_for_linked_account(balance, date || Date.current)elseresult = set_current_balance_for_manual_account(balance)- end- # Update cache field so changes appear immediately to the user- account.update!(balance: balance)+ # Update cache field so changes appear immediately to the user+ account.update!(balance: balance)- result+ result+ endrescue => eResult.new(success?: false, changes_made?: false, error: e.message)end@@ -96,24 +103,60 @@ class Account::CurrentBalanceManager# Before overwriting a stale (previous-day) current_anchor, we convert it to a# reconciliation valuation. This preserves the API-reported balance as a historical# waypoint that the ReverseCalculator uses for more accurate balance history.- def set_current_balance_for_linked_account(balance)+ def set_current_balance_for_linked_account(balance, date)changes_made = false-- ActiveRecord::Base.transaction do- # If an anchor exists from a previous day, preserve it as a reconciliation- # before replacing it with today's fresh anchor.- preserve_anchor_as_reconciliation_if_stale if current_anchor_valuation-- # Re-check: the memoized value was cleared if the anchor was converted- if current_anchor_valuation- changes_made = update_current_anchor(balance)+ error = nil+ historical = false++ # Locked, with the anchor re-read inside it: everything below turns on+ # which side of the anchor's date this statement falls, and a sync running+ # beside this one can move that anchor between the read and the write.+ account.with_lock do+ @current_anchor_valuation = nil++ if anchor_newer_than?(date)+ # A statement older than the anchor already holds is a correction to a+ # day gone by, not the balance now. It is recorded on its own date,+ # the newer anchor is left where it stands, and the cached balance --+ # which is the balance now -- is not touched.+ result = record_historical_balance(balance, date)+ changes_made = result.changes_made?+ error = result.error+ historical = trueelse- create_current_anchor(balance)- changes_made = true+ # Only a statement that moves the balance forward leaves the previous+ # anchor behind as a reconciliation. One carrying the anchor's own date+ # is that same anchor restated, so it is updated rather than duplicated.+ preserve_anchor_as_reconciliation_if_stale(date) if current_anchor_valuation++ # Re-check: the memoized value was cleared if the anchor was converted+ if current_anchor_valuation+ changes_made = update_current_anchor(balance, date)+ else+ create_current_anchor(balance, date)+ changes_made = true+ end++ # Update cache field so changes appear immediately to the user+ account.update!(balance: balance)endend- Result.new(success?: true, changes_made?: changes_made, error: nil)+ Result.new(success?: error.nil?, changes_made?: changes_made, error: error, historical?: historical)+ end++ def anchor_newer_than?(date)+ current_anchor_valuation.present? && current_anchor_valuation.entry.date > date+ end++ def record_historical_balance(balance, date)+ result = reconciliation_manager.reconcile_balance(+ balance: balance,+ date: date,+ existing_valuation_entry: account.entries.valuations.find_by(date: date)+ )++ Result.new(success?: result.success?, changes_made?: result.success?, error: result.error_message)enddef current_anchor_valuation@@ -125,9 +168,9 @@ class Account::CurrentBalanceManager# balance waypoints over time without creating extra entries per sync.## Same-day updates are left in place (no extra reconciliations on repeated syncs).- def preserve_anchor_as_reconciliation_if_stale+ def preserve_anchor_as_reconciliation_if_stale(date)entry = current_anchor_valuation.entry- return if entry.date == Date.current # Same-day update — nothing to preserve+ return if entry.date == date # Same-day update — nothing to preservecurrent_anchor_valuation.update!(kind: "reconciliation")entry.update!(name: Valuation.build_reconciliation_name(account.accountable_type))@@ -139,9 +182,9 @@ class Account::CurrentBalanceManager@current_anchor_valuation = nilend- def create_current_anchor(balance)+ def create_current_anchor(balance, date)account.entries.create!(- date: Date.current,+ date: date,name: Valuation.build_current_anchor_name(account.accountable_type),amount: balance,currency: account.currency,@@ -152,7 +195,7 @@ class Account::CurrentBalanceManager@current_anchor_valuation = nilend- def update_current_anchor(balance)+ def update_current_anchor(balance, date)changes_made = false# Update associated entry attributes@@ -163,8 +206,8 @@ class Account::CurrentBalanceManagerchanges_made = trueend- if entry.date != Date.current- entry.date = Date.current+ if entry.date != date+ entry.date = datechanges_made = trueenddiff --git a/app/models/ibkr_account/processor.rb b/app/models/ibkr_account/processor.rbindex 0a924d4a7f..dbb424e79b 100644--- a/app/models/ibkr_account/processor.rb+++ b/app/models/ibkr_account/processor.rb@@ -25,14 +25,77 @@ class IbkrAccount::Processordef update_account_balance!total_balance = ibkr_account.current_balance || ibkr_account.cash_balance || 0cash_balance = ibkr_account.cash_balance || 0+ result = nil- account.assign_attributes(- balance: total_balance,- cash_balance: cash_balance,- currency: ibkr_account.currency- )- account.save!- account.set_current_balance(total_balance)+ # One lock across the whole of it. Which statement the account follows is+ # decided by the anchor's date, and a sync running beside this one can+ # move that anchor between any two of these writes -- so the currency,+ # the anchor and the cash split are settled together, and follow the same+ # statement. The manager is called directly: the Anchorable wrapper+ # queues the sync, which belongs after the lock is released.+ account.with_lock do+ manager = Account::CurrentBalanceManager.new(account)++ # The currency is written ahead of the anchor so the anchor is made in+ # it, but only when this statement is the one the anchor will follow:+ # an older one leaves the balance where it is, and the cached figures+ # must keep the denomination they were written in. Rolled back below+ # with everything else if the write fails.+ if ibkr_account.currency != account.currency && !statement_behind_anchor?(manager)+ account.update!(currency: ibkr_account.currency)+ end++ # Dated to the statement, not to today: the NAV is as of IBKR's report+ # date and the holdings imported beside it carry that same date.+ # Anchoring it to today instead pairs one day's NAV with the next day's+ # prices, and the cash plug absorbs the difference -- a phantom balance+ # the size of whatever the holdings moved that day, on every day of the+ # account's history.+ result = manager.set_current_balance(total_balance, date: balance_date)++ # The manager rescues and reports failure through its result, and its+ # own lock joined this transaction rather than opening one -- so what+ # it wrote before failing (an anchor already rotated into a+ # reconciliation, a reconciliation saved before its pledge failed)+ # would commit with the currency. Nothing of this statement may stay.+ raise ActiveRecord::Rollback unless result.success?++ # The cached balance and its cash split are what the account is worth+ # now, and set_current_balance owns the first of them. A statement+ # older than the anchor describes a day gone by, so it moves neither.+ account.update!(cash_balance: cash_balance) unless result.historical?+ end++ if result.success?+ account.sync_later+ else+ # set_current_balance rescues and reports through its result, so a failed+ # write is otherwise silent. Captured rather than raised, as the anchor+ # repair below is: broadcast_sync_complete still has to run.+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to set the current balance: #{result.error}",+ source: self.class.name,+ provider_key: "ibkr",+ account_provider: ibkr_account.account_provider,+ family: ibkr_account.ibkr_item&.family,+ metadata: { report_date: ibkr_account.report_date&.to_s, balance_date: balance_date.to_s }+ )+ end++ result+ end++ def statement_behind_anchor?(manager)+ manager.has_current_anchor? && manager.current_date > balance_date+ end++ def balance_date+ date = ibkr_account.report_date+ return Date.current if date.blank? || date > Date.current++ dateenddef repair_default_opening_anchor!diff --git a/test/models/account/current_balance_manager_test.rb b/test/models/account/current_balance_manager_test.rbindex b3499718ac..de261219ec 100644--- a/test/models/account/current_balance_manager_test.rb+++ b/test/models/account/current_balance_manager_test.rb@@ -208,6 +208,62 @@ class Account::CurrentBalanceManagerTest < ActiveSupport::TestCaseassert_equal 1000, @linked_account.balanceend+ # A provider whose figures come from a statement knows the day they describe,+ # which is not always today.+ test "anchors a linked account balance on the date it is given" do+ manager = Account::CurrentBalanceManager.new(@linked_account)+ statement_date = Date.current - 1.day++ result = manager.set_current_balance(1000, date: statement_date)+ assert result.success?++ entry = @linked_account.valuations.current_anchor.first.entry+ assert_equal statement_date, entry.date+ assert_equal 1000, entry.amount+ end++ # A statement older than the anchor is a correction to a day gone by. It is+ # recorded on that day, and the newer anchor -- with the newer figure, and the+ # balance the account reports -- is left alone. This also covers an account+ # whose anchor is still dated by the day it was written: that anchor keeps its+ # date until a statement catches up with it, and is corrected in place then.+ test "a statement older than the anchor is recorded on its own date" do+ manager = Account::CurrentBalanceManager.new(@linked_account)+ manager.set_current_balance(2000)+ anchor_id = @linked_account.valuations.current_anchor.first.id++ manager.set_current_balance(1000, date: Date.current - 1.day)++ anchor = @linked_account.valuations.current_anchor.first+ assert_equal anchor_id, anchor.id, "the newer anchor must survive"+ assert_equal Date.current, anchor.entry.date+ assert_equal 2000, anchor.entry.amount+ assert_equal 2000, @linked_account.reload.balance, "the cached balance must not go backwards"++ older = @linked_account.entries.valuations.find_by(date: Date.current - 1.day)+ assert_not_nil older, "the older statement is kept where it belongs"+ assert_equal 1000, older.amount+ end++ # Two statements carrying the same date are one anchor, not an anchor and a+ # reconciliation sitting on the same day.+ test "a repeated statement date updates the anchor in place" do+ manager = Account::CurrentBalanceManager.new(@linked_account)+ statement_date = Date.current - 1.day+ manager.set_current_balance(1000, date: statement_date)++ travel_to Date.current + 1.day do+ assert_no_difference -> { @linked_account.valuations.count } do+ manager.set_current_balance(1500, date: statement_date)+ end+ end++ assert_equal 1, @linked_account.valuations.current_anchor.count+ entry = @linked_account.valuations.current_anchor.first.entry+ assert_equal statement_date, entry.date+ assert_equal 1500, entry.amount+ end+test "preserves previous day anchor as reconciliation when updating linked account balance" do# First create a current anchormanager = Account::CurrentBalanceManager.new(@linked_account)diff --git a/test/models/ibkr_account/processor_test.rb b/test/models/ibkr_account/processor_test.rbnew file mode 100644index 0000000000..fd7e50eb03--- /dev/null+++ b/test/models/ibkr_account/processor_test.rb@@ -0,0 +1,140 @@+require "test_helper"++class IbkrAccount::ProcessorTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ @account = @family.accounts.create!(+ name: "IBKR Brokerage",+ balance: 0,+ cash_balance: 0,+ currency: "CHF",+ accountable: Investment.new(subtype: "brokerage")+ )+ @ibkr_account = @family.ibkr_items.create!(+ name: "IBKR",+ query_id: "QUERY123",+ token: "TOKEN123"+ ).ibkr_accounts.create!(+ name: "Main",+ ibkr_account_id: "U1234567",+ currency: "CHF",+ current_balance: 3351,+ cash_balance: 1000.5,+ report_date: Date.current - 1.day+ )+ @ibkr_account.ensure_account_provider!(@account)+ end++ # The NAV is as of IBKR's report date, and the holdings imported beside it+ # carry that same date. Anchored to today instead, one day's NAV is weighed+ # against the next day's prices and the cash plug absorbs the difference.+ test "anchors the balance on the statement's report date" do+ IbkrAccount::Processor.new(@ibkr_account).process++ entry = @account.valuations.current_anchor.first.entry+ assert_equal Date.current - 1.day, entry.date+ assert_equal 3351, entry.amount+ end++ # A statement that has not moved on is the same statement: it updates the+ # anchor where it stands rather than leaving a reconciliation behind it.+ test "a repeated report date does not accumulate valuations" do+ IbkrAccount::Processor.new(@ibkr_account).process++ travel_to Date.current + 1.day do+ assert_no_difference -> { @account.valuations.count } do+ IbkrAccount::Processor.new(@ibkr_account.reload).process+ end+ end++ assert_equal Date.current - 1.day, @account.valuations.current_anchor.first.entry.date+ end++ # An older statement describes a day gone by. The account's own balance, and+ # the cash split beside it, are what it is worth now, so neither follows it.+ test "an older statement leaves the account's own balance alone" do+ IbkrAccount::Processor.new(@ibkr_account).process+ assert_equal 3351, @account.reload.balance++ @ibkr_account.update!(report_date: Date.current - 3.days, current_balance: 2000, cash_balance: 40)+ IbkrAccount::Processor.new(@ibkr_account.reload).process++ @account.reload+ assert_equal 3351, @account.balance, "the cached balance must not follow an older statement"+ assert_equal 1000.5, @account.cash_balance, "nor its cash split"+ assert_equal Date.current - 1.day, @account.valuations.current_anchor.first.entry.date+ older = @account.entries.valuations.find_by(date: Date.current - 3.days)+ assert_not_nil older, "the older statement is kept where it belongs"+ assert_equal 2000, older.amount+ end++ # A failed NAV write leaves the anchor and the cached balance where they were,+ # so the cash split must stay with them rather than move on alone.+ test "a failed balance write leaves the cash split alone" do+ IbkrAccount::Processor.new(@ibkr_account).process+ assert_equal 1000.5, @account.reload.cash_balance++ Account::CurrentBalanceManager.any_instance.stubs(:set_current_balance).returns(+ Account::CurrentBalanceManager::Result.new(success?: false, changes_made?: false, error: "boom")+ )+ @ibkr_account.update!(cash_balance: 42)++ assert_difference -> { DebugLogEntry.where(source: "IbkrAccount::Processor", category: "provider_sync_error").count }, 1 do+ IbkrAccount::Processor.new(@ibkr_account.reload).process+ end++ assert_equal 1000.5, @account.reload.cash_balance+ end++ # The currency changes only with a balance that was actually written, so the+ # cached figures keep the denomination they were written in.+ test "an older statement or a failed write does not change the currency" do+ IbkrAccount::Processor.new(@ibkr_account).process++ @ibkr_account.update!(report_date: Date.current - 3.days, currency: "USD")+ IbkrAccount::Processor.new(@ibkr_account.reload).process+ assert_equal "CHF", @account.reload.currency, "an older statement leaves the currency alone"++ @ibkr_account.update!(report_date: Date.current)+ Account::CurrentBalanceManager.any_instance.stubs(:set_current_balance).returns(+ Account::CurrentBalanceManager::Result.new(success?: false, changes_made?: false, error: "boom")+ )+ IbkrAccount::Processor.new(@ibkr_account.reload).process+ assert_equal "CHF", @account.reload.currency, "a failed write puts the currency back"+ end++ # The manager's lock joins the processor's transaction, so a write that fails+ # part-way -- after the old anchor has already been rotated -- must be rolled+ # back here, or the rotation commits and the account is left with no current+ # anchor at all.+ test "a write that fails part-way leaves the previous anchor as it was" do+ IbkrAccount::Processor.new(@ibkr_account).process+ original = @account.valuations.current_anchor.first+ assert_equal Date.current - 1.day, original.entry.date++ @ibkr_account.update!(report_date: Date.current, current_balance: 4000, currency: "USD")+ Account::CurrentBalanceManager.any_instance.stubs(:create_current_anchor).raises(ActiveRecord::StatementInvalid, "boom")++ assert_no_difference -> { @account.valuations.count } do+ IbkrAccount::Processor.new(@ibkr_account.reload).process+ end++ @account.reload+ assert_equal "current_anchor", Valuation.find(original.id).kind, "the rotation must have been rolled back"+ assert_equal 3351, @account.balance+ assert_equal 1000.5, @account.cash_balance+ assert_equal "CHF", @account.currency, "the currency write must have been rolled back too"+ end++ # Nothing to date it by, or a statement dated ahead of today: fall back to+ # today rather than anchoring the account in the future.+ test "falls back to today when the report date is missing or ahead" do+ @ibkr_account.update!(report_date: nil)+ IbkrAccount::Processor.new(@ibkr_account).process+ assert_equal Date.current, @account.valuations.current_anchor.first.entry.date++ @ibkr_account.update!(report_date: Date.current + 3.days)+ IbkrAccount::Processor.new(@ibkr_account.reload).process+ assert_equal Date.current, @account.valuations.current_anchor.first.entry.date+ end+end