Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(sync): warn when the balance anchor is dated away from the holdings (#3876)

Daniel Garcia Sardina44b776180503
diff --git a/app/models/account/syncer.rb b/app/models/account/syncer.rb
index 60c2917c78..d7493701fd 100644
--- a/app/models/account/syncer.rb
+++ b/app/models/account/syncer.rb
@@ -10,6 +10,7 @@ class Account::Syncer
import_market_data
materialize_balances(window_start_date: sync.window_start_date)
apply_provider_balance_overrides
+ report_anchor_dated_away_from_holdings
end
def perform_post_sync
@@ -36,6 +37,67 @@ class Account::Syncer
Sentry.capture_exception(e)
end
+ # A provider that dates its holdings itself, but whose balance is anchored
+ # on the day of the sync, leaves the two a day apart; the reverse
+ # calculator reads the difference as cash, on every day, in the amount of
+ # the day's move (#3815 in IBKR, #3874 in Plaid). Nothing fails, so the only
+ # place it can show is here, once every provider has written.
+ #
+ # The log records changes, compared with the account's latest entry from
+ # this check: a new or different gap is a warning, a steady one adds
+ # nothing, and the dates lining up again is noted, so a gap that later
+ # returns is a new finding rather than one already on record.
+ def report_anchor_dated_away_from_holdings
+ return unless account.linked? && account.has_current_anchor?
+
+ newest_holding = account.holdings.where.not(account_provider_id: nil).order(date: :desc).first
+ return if newest_holding.nil?
+
+ holdings_date = newest_holding.date
+ anchor_date = account.current_anchor_date
+ gap_days = (anchor_date - holdings_date).to_i
+ last_gap = last_reported_anchor_gap
+
+ if gap_days.zero?
+ return if last_gap.nil? || last_gap.zero?
+
+ record_anchor_gap(newest_holding, anchor_date, holdings_date, 0, level: "info",
+ message: "Balance anchor and newest provider holding are dated alike again")
+ else
+ return if last_gap == gap_days
+
+ record_anchor_gap(newest_holding, anchor_date, holdings_date, gap_days, level: "warn",
+ message: "Balance anchor dated #{gap_days.abs} day(s) #{gap_days.positive? ? 'after' : 'before'} the newest provider holding")
+ end
+ rescue => e
+ Rails.logger.error("Error checking anchor date for account #{account.id}: #{e.class} - #{e.message}")
+ Sentry.capture_exception(e)
+ end
+
+ def last_reported_anchor_gap
+ DebugLogEntry
+ .where(account: account, category: "provider_sync", source: self.class.name)
+ .order(created_at: :desc)
+ .pick(Arel.sql("metadata->>'gap_days'"))
+ &.to_i
+ end
+
+ def record_anchor_gap(newest_holding, anchor_date, holdings_date, gap_days, level:, message:)
+ account_provider = newest_holding.account_provider
+
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: level,
+ message: message,
+ source: self.class.name,
+ provider_key: account_provider&.provider_type&.delete_suffix("Account")&.underscore,
+ account: account,
+ account_provider: account_provider,
+ family: account.family,
+ metadata: { anchor_date: anchor_date.to_s, holdings_date: holdings_date.to_s, gap_days: gap_days }
+ )
+ end
+
def apply_provider_balance_overrides
return unless account.linked_to?("IbkrAccount")
diff --git a/test/models/account/syncer_test.rb b/test/models/account/syncer_test.rb
index f725b25b0e..30171b186c 100644
--- a/test/models/account/syncer_test.rb
+++ b/test/models/account/syncer_test.rb
@@ -36,4 +36,132 @@ class Account::SyncerTest < ActiveSupport::TestCase
Account::Syncer.new(account).perform_sync(OpenStruct.new(window_start_date: nil))
end
+
+ # A provider that dates its holdings itself, but anchors the balance on the
+ # day of the sync, leaves the two a day apart and the gap reads as cash.
+ # Nothing fails, so the sync is the one place it can be seen.
+ test "warns once when the balance anchor is dated away from the newest provider holding" do
+ account, account_provider = linked_investment_account
+ account.set_current_balance(1000, date: Date.current, schedule_sync: false)
+ provider_holding(account, account_provider, date: Date.current - 1)
+
+ assert_difference "DebugLogEntry.count", 1 do
+ run_sync(account)
+ end
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "provider_sync", entry.category
+ assert_equal "warn", entry.level
+ assert_equal "Account::Syncer", entry.source
+ assert_equal "ibkr", entry.provider_key
+ assert_equal account, entry.account
+ assert_equal account_provider, entry.account_provider
+ assert_equal Date.current.to_s, entry.metadata["anchor_date"]
+ assert_equal (Date.current - 1).to_s, entry.metadata["holdings_date"]
+ assert_equal 1, entry.metadata["gap_days"]
+ assert_match(/1 day\(s\) after/, entry.message)
+
+ # The next day both dates have moved on and the gap has not: the shift is
+ # already on record, whatever the dates now read.
+ account.set_current_balance(1000, date: Date.current + 1, schedule_sync: false)
+ provider_holding(account, account_provider, date: Date.current)
+ assert_no_difference "DebugLogEntry.count" do
+ run_sync(Account.find(account.id))
+ end
+
+ # A different gap is a new finding.
+ account.set_current_balance(1000, date: Date.current + 3, schedule_sync: false)
+ assert_difference "DebugLogEntry.count", 1 do
+ run_sync(Account.find(account.id))
+ end
+ assert_equal 3, DebugLogEntry.order(:created_at).last.metadata["gap_days"]
+ end
+
+ # A gap that closes and later returns is a new finding, not one already on
+ # record; the closing itself is noted at info level.
+ test "notes the dates lining up again, and warns when the same gap returns" do
+ account, account_provider = linked_investment_account
+ provider_holding(account, account_provider, date: Date.current - 1)
+
+ account.set_current_balance(1000, date: Date.current, schedule_sync: false)
+ assert_difference "DebugLogEntry.where(level: \"warn\").count", 1 do
+ run_sync(Account.find(account.id))
+ end
+
+ # Aligned, as the next sync would leave it: holdings catch up with the
+ # anchor. One info entry, then nothing while it stays aligned.
+ account.holdings.create!(security: securities(:msft), qty: 1, price: 10, amount: 10, currency: "CHF",
+ date: Date.current, account_provider_id: account_provider.id)
+ assert_difference "DebugLogEntry.where(level: \"info\").count", 1 do
+ run_sync(Account.find(account.id))
+ end
+ assert_no_difference "DebugLogEntry.count" do
+ run_sync(Account.find(account.id))
+ end
+
+ # The same one-day gap again, a day later.
+ account.set_current_balance(1000, date: Date.current + 1, schedule_sync: false)
+ assert_difference "DebugLogEntry.where(level: \"warn\").count", 1 do
+ run_sync(Account.find(account.id))
+ end
+ assert_equal 1, DebugLogEntry.order(:created_at).last.metadata["gap_days"]
+ end
+
+ test "stays quiet when the anchor and the newest provider holding share a date" do
+ account, account_provider = linked_investment_account
+ account.set_current_balance(1000, date: Date.current - 1, schedule_sync: false)
+ provider_holding(account, account_provider, date: Date.current - 1)
+
+ assert_no_difference "DebugLogEntry.count" do
+ run_sync(account)
+ end
+ end
+
+ test "stays quiet without provider-dated holdings or without an anchor" do
+ account, account_provider = linked_investment_account
+
+ # An anchor and only materialized holdings, which carry no provider.
+ account.set_current_balance(1000, date: Date.current, schedule_sync: false)
+ account.holdings.create!(security: securities(:aapl), qty: 1, price: 10, amount: 10, currency: "CHF", date: Date.current - 1)
+ assert_no_difference "DebugLogEntry.count" do
+ run_sync(account)
+ end
+
+ # Provider holdings and no anchor yet.
+ unanchored, unanchored_provider = linked_investment_account
+ provider_holding(unanchored, unanchored_provider, date: Date.current - 1)
+ assert_no_difference "DebugLogEntry.count" do
+ run_sync(unanchored)
+ end
+ end
+
+ private
+ def linked_investment_account
+ 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")
+ ibkr_account.ensure_account_provider!(account)
+ [ account, account.account_providers.first ]
+ end
+
+ def provider_holding(account, account_provider, date:)
+ account.holdings.create!(
+ security: securities(:aapl), qty: 1, price: 10, amount: 10, currency: "CHF",
+ date: date, account_provider_id: account_provider.id
+ )
+ end
+
+ def run_sync(account)
+ Account::MarketDataImporter.any_instance.stubs(:import_all)
+ Balance::Materializer.any_instance.stubs(:materialize_balances)
+ IbkrAccount::HistoricalBalancesSync.any_instance.stubs(:sync!)
+ Account::Syncer.new(account).perform_sync(OpenStruct.new(window_start_date: nil))
+ end
end