The personal finance app for everyone (by everyone)
Ruby
Keep a daily holding row for SimpleFIN and Lunchflow (#4119)
mrvruj2296269c3cff
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex f8439e51fa..1485cf9cbb 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -516,6 +516,10 @@ class Account::ProviderImportAdapterendend+ # A new row for a later day starts without the user's corrections, which+ # live on the earlier day's row. Carry them forward from that row.+ carried = holding.new_record? ? previous_holding_for(security: security, currency: currency, date: date, account_provider_id: account_provider_id) : nil+# Reconcile cost_basis to respect priority hierarchyreconciled = Holding::CostBasisReconciler.reconcile(existing_holding: holding.persisted? ? holding : nil,@@ -535,7 +539,11 @@ class Account::ProviderImportAdapter}# Only update security if not locked by user- if holding.new_record? || holding.security_replaceable_by_provider?+ if carried&.security_locked?+ attributes[:security] = carried.security+ attributes[:provider_security_id] = carried.provider_security_id || security.id+ attributes[:security_locked] = true+ elsif holding.new_record? || holding.security_replaceable_by_provider?attributes[:security] = security# Track the provider's original security so reset_security_to_provider! works# Only set if not already set (preserves original if user remapped then unlocked)@@ -543,7 +551,11 @@ class Account::ProviderImportAdapterend# Only update cost_basis if reconciliation says to- if reconciled[:should_update]+ if carried&.cost_basis_locked?+ attributes[:cost_basis] = carried.cost_basis+ attributes[:cost_basis_source] = carried.cost_basis_source+ attributes[:cost_basis_locked] = true+ elsif reconciled[:should_update]attributes[:cost_basis] = reconciled[:cost_basis]attributes[:cost_basis_source] = reconciled[:cost_basis_source]end@@ -1051,6 +1063,22 @@ class Account::ProviderImportAdapterprivate+ # The latest earlier holding of the security the provider reports. A+ # remapped row records that security in provider_security_id; an+ # unremapped one has it as its own security. Only the latest row counts, so+ # a correction the user has since undone is not revived from an older day.+ def previous_holding_for(security:, currency:, date:, account_provider_id:)+ scope = account.holdings+ .where(currency: currency)+ .where("holdings.date < ?", date)+ .where(+ "holdings.provider_security_id = :id OR (holdings.provider_security_id IS NULL AND holdings.security_id = :id)",+ id: security.id+ )+ scope = scope.where(account_provider_id: account_provider_id) if account_provider_id.present?+ scope.order(date: :desc).first+ end+# Loads the transfer together with both legs, their entries and accounts in# one joined query, so Transfer#kind_for_leg reads them without the lazy# loads it would otherwise pay on every re-imported row. Looked up per rowdiff --git a/app/models/lunchflow_account/investments/holdings_processor.rb b/app/models/lunchflow_account/investments/holdings_processor.rbindex a972f6f441..fbe46752d3 100644--- a/app/models/lunchflow_account/investments/holdings_processor.rb+++ b/app/models/lunchflow_account/investments/holdings_processor.rb@@ -74,15 +74,17 @@ class LunchflowAccount::Investments::HoldingsProcessorreturnend+ holding_date = Date.current+saved = import_adapter.import_holding(security: security,quantity: qty,amount: amount,currency: currency,- date: Date.current,+ date: holding_date,price: price,cost_basis: cost_basis,- external_id: "lunchflow_#{holding_id}",+ external_id: "lunchflow_#{holding_id}_#{holding_date}",account_provider_id: lunchflow_account.account_provider&.id,source: "lunchflow",delete_future_holdings: falsediff --git a/app/models/simplefin_account/investments/holdings_processor.rb b/app/models/simplefin_account/investments/holdings_processor.rbindex 4769934de1..c89b98a1a0 100644--- a/app/models/simplefin_account/investments/holdings_processor.rb+++ b/app/models/simplefin_account/investments/holdings_processor.rb@@ -102,7 +102,7 @@ class SimplefinAccount::Investments::HoldingsProcessorposition[:qty] += qty.to_dposition[:amount] += computed_amount.to_d- position[:external_ids] << "simplefin_#{holding_id}"+ position[:external_ids] << "simplefin_#{holding_id}_#{holding_date}"position[:fallback_price] ||= price if price.to_d.positive?if qty.to_d.positive?diff --git a/test/jobs/simplefin_holdings_apply_job_test.rb b/test/jobs/simplefin_holdings_apply_job_test.rbindex 1826e2495d..2c004c318c 100644--- a/test/jobs/simplefin_holdings_apply_job_test.rb+++ b/test/jobs/simplefin_holdings_apply_job_test.rb@@ -86,7 +86,7 @@ class SimplefinHoldingsApplyJobTest < ActiveSupport::TestCaseSimplefinHoldingsApplyJob.perform_now(@sfa.id)end- holding = @account.holdings.find_by(external_id: "simplefin_h_vanguard")+ holding = @account.holdings.find_by(external_id: "simplefin_h_vanguard_#{Date.current}")refute_nil holding# Price should be derived from market_value / shares, NOT from value / shares@@ -118,7 +118,7 @@ class SimplefinHoldingsApplyJobTest < ActiveSupport::TestCaseSimplefinHoldingsApplyJob.perform_now(@sfa.id)end- holding = @account.holdings.find_by(external_id: "simplefin_h_fallback")+ holding = @account.holdings.find_by(external_id: "simplefin_h_fallback_#{Date.current}")refute_nil holding# Price derived from market_valuediff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex b2a005af9b..decdc32a18 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -733,6 +733,48 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseassert_equal account_provider.id, holding.account_provider_idend+ test "carries a remapped security forward to the next day's holding" do+ account, adapter, account_provider = provider_holding_setup+ reported = Security.create!(ticker: "RPTD", name: "Reported Fund")+ chosen = Security.create!(ticker: "CHSN", name: "Chosen Fund")+ first_day = 20.days.ago.to_date++ import_daily_holding(adapter, account_provider, reported, first_day).remap_security!(chosen)+ next_day = import_daily_holding(adapter, account_provider, reported, first_day + 1)++ assert_equal chosen.id, next_day.security_id+ assert_equal reported.id, next_day.provider_security_id+ assert next_day.security_locked?+ assert_equal 2, account.holdings.where(security: chosen).count+ end++ test "carries a locked cost basis forward to the next day's holding" do+ _account, adapter, account_provider = provider_holding_setup+ security = Security.create!(ticker: "LCKD", name: "Locked Basis Fund")+ first_day = 20.days.ago.to_date++ import_daily_holding(adapter, account_provider, security, first_day).set_manual_cost_basis!(42)+ next_day = import_daily_holding(adapter, account_provider, security, first_day + 1, cost_basis: 10)++ assert_equal 42, next_day.cost_basis+ assert_equal "manual", next_day.cost_basis_source+ assert next_day.cost_basis_locked?+ end++ test "does not revive a correction the user has since undone" do+ _account, adapter, account_provider = provider_holding_setup+ security = Security.create!(ticker: "UNDO", name: "Unlocked Basis Fund")+ first_day = 20.days.ago.to_date++ import_daily_holding(adapter, account_provider, security, first_day).set_manual_cost_basis!(42)+ import_daily_holding(adapter, account_provider, security, first_day + 1).unlock_cost_basis!+ third_day = import_daily_holding(adapter, account_provider, security, first_day + 2, cost_basis: 10)++ assert_equal 10, third_day.cost_basis+ assert_equal "provider", third_day.cost_basis_source+ assert_not third_day.cost_basis_locked?+ end+test "does not delete future holdings when can_delete_holdings? returns false" doinvestment_account = accounts(:investment)adapter = Account::ProviderImportAdapter.new(investment_account)@@ -2270,4 +2312,27 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCasequeriesend++ def provider_holding_setup+ account = accounts(:investment)+ account_provider = AccountProvider.create!(account: account, provider: plaid_accounts(:one))+ [ account, Account::ProviderImportAdapter.new(account), account_provider ]+ end++ # One provider snapshot per day, identified the way the daily-snapshot+ # processors do it: the provider's id suffixed with the date.+ def import_daily_holding(adapter, account_provider, security, date, cost_basis: nil)+ adapter.import_holding(+ security: security,+ quantity: 10,+ amount: 1000,+ currency: "USD",+ date: date,+ price: 100,+ cost_basis: cost_basis,+ external_id: "provider_lot_#{date}",+ source: "plaid",+ account_provider_id: account_provider.id+ )+ endenddiff --git a/test/models/lunchflow_account/investments/holdings_processor_test.rb b/test/models/lunchflow_account/investments/holdings_processor_test.rbindex 229f8cb0c0..cfe41a0bac 100644--- a/test/models/lunchflow_account/investments/holdings_processor_test.rb+++ b/test/models/lunchflow_account/investments/holdings_processor_test.rb@@ -76,7 +76,7 @@ class LunchflowAccount::Investments::HoldingsProcessorTest < ActiveSupport::Testassert_equal 2, holdings.countassert_equal "USD", holdings.first.currency- assert_equal "lunchflow_hld_test_123", holdings.first.external_id+ assert_equal "lunchflow_hld_test_123_#{Date.current}", holdings.first.external_idendtest "skips processing for non-investment accounts" do@@ -149,7 +149,7 @@ class LunchflowAccount::Investments::HoldingsProcessorTest < ActiveSupport::Testendholding = Holding.where(account: @account).where.not(external_id: nil).last- assert_equal "lunchflow_hld_custom_123", holding.external_id+ assert_equal "lunchflow_hld_custom_123_#{Date.current}", holding.external_idassert_equal 100, holding.qtyassert_equal 5000.0, holding.amountenddiff --git a/test/models/simplefin_account/investments/holdings_processor_test.rb b/test/models/simplefin_account/investments/holdings_processor_test.rbindex 395e4ff203..fa978d6a05 100644--- a/test/models/simplefin_account/investments/holdings_processor_test.rb+++ b/test/models/simplefin_account/investments/holdings_processor_test.rb@@ -249,6 +249,42 @@ class SimplefinAccount::Investments::HoldingsProcessorTest < ActiveSupport::Testassert_in_delta 258.1781, position[:price].to_f, 0.01end+ test "each day's sync keeps its own holding row" do+ # The external_id carries the snapshot date, so the next day's sync+ # creates a new row instead of finding yesterday's by id and moving it+ # forward. Without that, the account never has more than one row per+ # security and its holdings history collapses onto the latest day.+ account = accounts(:investment)+ security = Security.create!(ticker: "DAILY", name: "Daily Snapshot Fund")+ processor = SimplefinAccount::Investments::HoldingsProcessor.new(nil)+ processor.stubs(:account).returns(account)+ processor.stubs(:resolve_security).returns(security)+ processor.stubs(:institution_reports_total_basis?).returns(false)+ processor.stubs(:simplefin_account).returns(+ stub(id: "sfa-test", name: "Test Investment Account", account_provider: nil)+ )++ first_day = Date.current++ processor.stubs(:holdings_data).returns([+ { "id" => "lot-a", "symbol" => "DAILY", "shares" => "10", "market_value" => "1000" }+ ])+ processor.process++ travel_to 1.day.from_now do+ processor.stubs(:holdings_data).returns([+ { "id" => "lot-a", "symbol" => "DAILY", "shares" => "12", "market_value" => "1260" }+ ])+ processor.process+ end++ holdings = account.holdings.where(security: security).order(:date)++ assert_equal [ first_day, first_day + 1 ], holdings.map(&:date)+ assert_equal [ 10, 12 ], holdings.map { |h| h.qty.to_i }+ assert_equal [ "simplefin_lot-a_#{first_day}", "simplefin_lot-a_#{first_day + 1}" ], holdings.map(&:external_id)+ end+test "a position with any unknown-basis lot reports no aggregate basis" do# Averaging only the lots that reported a basis would apply that figure to# shares whose cost is unknown, fabricating cost and gain/loss.