The personal finance app for everyone (by everyone)
Ruby
fix(plaid): anchor an investment balance on the holdings' price date (#3874)
Daniel Garcia Sardinabf18e8c91329
diff --git a/app/models/plaid_account/processor.rb b/app/models/plaid_account/processor.rbindex c8e04115fd..9871aeedf6 100644--- a/app/models/plaid_account/processor.rb+++ b/app/models/plaid_account/processor.rb@@ -1,6 +1,8 @@class PlaidAccount::Processorinclude PlaidAccount::TypeMappable+ BalanceError = Class.new(StandardError)+attr_reader :plaid_accountdef initialize(plaid_account)@@ -73,13 +75,20 @@ class PlaidAccount::Processorsource: "plaid")- account.assign_attributes(- balance: balance_calculator.balance,- currency: plaid_account.currency,- cash_balance: balance_calculator.cash_balance- )+ balance = balance_calculator.balance+ cash_balance = balance_calculator.cash_balance+ balance_date = self.balance_datenew_account = account.new_record?+ if new_account+ # A new account is saved with what Plaid reports; the anchor below+ # is made in the same figures, under the lock.+ account.assign_attributes(+ currency: plaid_account.currency,+ balance: balance,+ cash_balance: cash_balance+ )+ endaccount.save!account.auto_share_with_family! if new_account && account.family.share_all_by_default?@@ -98,7 +107,32 @@ class PlaidAccount::Processor# to properly track the holdings vs. cash breakdown, but for now we're only tracking# the total balance in the current anchor. The cash_balance field on the account model# is still being used for the breakdown.- account.set_current_balance(balance_calculator.balance)+ #+ # One lock across the whole of it, as in IbkrAccount::Processor: which+ # snapshot 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. The currency, the anchor and the cash split are settled+ # together, and follow the same snapshot. The manager is called directly;+ # the Anchorable wrapper queues the sync, which belongs after the lock.+ result = nil+ account.with_lock do+ manager = Account::CurrentBalanceManager.new(account)+ behind_anchor = manager.has_current_anchor? && manager.current_date > balance_date++ # A snapshot dated behind the anchor is a correction to a day gone+ # by: the cached balance and cash describe now and stay as they are,+ # in the denomination they were written in.+ if !behind_anchor && account.currency != plaid_account.currency+ account.update!(currency: plaid_account.currency)+ end++ result = manager.set_current_balance(balance, date: balance_date)+ raise BalanceError, "Failed to set current balance: #{result.error}" unless result.success?++ account.update!(cash_balance: cash_balance) unless result.historical?+ end++ account.sync_laterendend@@ -135,6 +169,35 @@ class PlaidAccount::Processorreport_exception(e)end+ # Plaid dates each holding with the institution's price date, which for a+ # sync run before the close is the previous session's; the total it reports+ # alongside is as of that same date. Anchoring that total on today would+ # set it against holdings later repriced for today, and the difference+ # would read as cash on every day in between -- the shift #3815 removed+ # from IBKR. The anchor goes on the newest date the holdings carry; a+ # snapshot with no dated holdings is today's.+ def balance_date+ return Date.current unless plaid_account.plaid_type == "investment"++ # A holding dated ahead of today is discounted on its own, so one bad+ # feed does not pull the anchor off the date the rest agree on.+ dated = holdings.filter_map { |holding| parse_date(holding["institution_price_as_of"]) }+ dated.reject { |date| date > Date.current }.max || Date.current+ end++ def holdings+ plaid_account.raw_holdings_payload&.dig("holdings") || []+ end++ def parse_date(value)+ return nil if value.blank?+ return value.to_date if value.respond_to?(:to_date) && !value.is_a?(String)++ Date.parse(value.to_s)+ rescue ArgumentError, TypeError+ nil+ end+def balance_calculatorif plaid_account.plaid_type == "investment"@balance_calculator ||= PlaidAccount::Investments::BalanceCalculator.new(plaid_account, security_resolver: security_resolver)diff --git a/test/models/plaid_account/processor_test.rb b/test/models/plaid_account/processor_test.rbindex 6a6f48ee2c..afbe9f2474 100644--- a/test/models/plaid_account/processor_test.rb+++ b/test/models/plaid_account/processor_test.rb@@ -120,8 +120,8 @@ class PlaidAccount::ProcessorTest < ActiveSupport::TestCasetest "calculates balance using BalanceCalculator for investment accounts" do@plaid_account.update!(plaid_type: "investment")- # Balance is called twice: once for account.balance and once for set_current_balance- PlaidAccount::Investments::BalanceCalculator.any_instance.expects(:balance).returns(1000).twice+ # Balance is computed once and used for both account.balance and the anchor+ PlaidAccount::Investments::BalanceCalculator.any_instance.expects(:balance).returns(1000).oncePlaidAccount::Investments::BalanceCalculator.any_instance.expects(:cash_balance).returns(1000).oncePlaidAccount::Processor.new(@plaid_account).process@@ -233,6 +233,116 @@ class PlaidAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal "Current balance", current_anchor.entry.nameend+ test "an investment anchor is dated on the holdings' price date, not today" do+ expect_investment_product_processor_calls+ expect_depository_product_processor_calls+ expect_no_liability_processor_calls+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)++ price_date = Date.current - 1+ @plaid_account.update!(+ plaid_type: "investment",+ raw_holdings_payload: { "holdings" => [+ { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "90", "institution_price_as_of" => price_date.to_s },+ { "security_id" => "sec_2", "quantity" => "1", "institution_price" => "10", "institution_price_as_of" => (price_date - 3).to_s }+ ] }+ )++ PlaidAccount::Processor.new(@plaid_account).process++ account = @plaid_account.current_account+ current_anchor = account.valuations.current_anchor.first+ assert_equal price_date, current_anchor.entry.date, "the newest price date the holdings carry"+ assert_equal 1000, current_anchor.entry.amount+ assert_equal 1000, account.balance+ assert_equal 100, account.cash_balance+ end++ test "one holding dated ahead of today does not pull the anchor off the others' date" do+ expect_investment_product_processor_calls+ expect_depository_product_processor_calls+ expect_no_liability_processor_calls+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)++ price_date = Date.current - 1+ @plaid_account.update!(+ plaid_type: "investment",+ raw_holdings_payload: { "holdings" => [+ { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "90", "institution_price_as_of" => price_date.to_s },+ { "security_id" => "sec_2", "quantity" => "1", "institution_price" => "10", "institution_price_as_of" => (Date.current + 1).to_s }+ ] }+ )++ PlaidAccount::Processor.new(@plaid_account).process++ current_anchor = @plaid_account.current_account.valuations.current_anchor.first+ assert_equal price_date, current_anchor.entry.date+ end++ test "an investment anchor falls back to today without a usable price date" do+ expect_investment_product_processor_calls+ expect_depository_product_processor_calls+ expect_no_liability_processor_calls+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)++ @plaid_account.update!(+ plaid_type: "investment",+ raw_holdings_payload: { "holdings" => [+ { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "90", "institution_price_as_of" => nil },+ { "security_id" => "sec_2", "quantity" => "1", "institution_price" => "10", "institution_price_as_of" => "not a date" },+ { "security_id" => "sec_3", "quantity" => "1", "institution_price" => "10", "institution_price_as_of" => (Date.current + 1).to_s }+ ] }+ )++ PlaidAccount::Processor.new(@plaid_account).process++ current_anchor = @plaid_account.current_account.valuations.current_anchor.first+ assert_equal Date.current, current_anchor.entry.date+ end++ test "an investment snapshot dated behind the anchor is recorded on its own date and leaves the anchor alone" do+ PlaidAccount::Investments::TransactionsProcessor.any_instance.stubs(:process)+ PlaidAccount::Investments::HoldingsProcessor.any_instance.stubs(:process)+ PlaidAccount::Transactions::Processor.any_instance.stubs(:process)+ expect_no_liability_processor_calls+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)++ @plaid_account.update!(+ plaid_type: "investment",+ raw_holdings_payload: { "holdings" => [ { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "90", "institution_price_as_of" => Date.current.to_s } ] }+ )+ PlaidAccount::Processor.new(@plaid_account).process+ account = @plaid_account.current_account+ anchor = account.valuations.current_anchor.first++ # The next snapshot is dated behind the anchor, carries an older total,+ # and reports a different currency.+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(900)+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(50)+ @plaid_account.update!(+ currency: "EUR",+ raw_holdings_payload: { "holdings" => [ { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "85", "institution_price_as_of" => (Date.current - 1).to_s } ] }+ )++ assert_difference "account.valuations.reconciliation.count", 1 do+ PlaidAccount::Processor.new(@plaid_account).process+ end++ anchor.reload+ account.reload+ assert_equal Date.current, anchor.entry.date+ assert_equal 1000, anchor.entry.amount, "the anchor still describes now"+ assert_equal 1000, account.balance+ assert_equal 100, account.cash_balance+ assert_equal "USD", account.currency, "the cached figures keep the denomination they were written in"+ historical = account.valuations.reconciliation.joins(:entry).find_by(entries: { date: Date.current - 1 })+ assert_equal 900, historical.entry.amount+ end+test "updates existing current balance anchor when reprocessing" do# First process creates the account and anchorexpect_default_subprocessor_calls